Version in base suite: 17.0.14+7-1~deb12u1 Base version: openjdk-17_17.0.14+7-1~deb12u1 Target version: openjdk-17_17.0.15+6-1~deb12u1 Base file: /srv/ftp-master.debian.org/ftp/pool/main/o/openjdk-17/openjdk-17_17.0.14+7-1~deb12u1.dsc Target file: /srv/ftp-master.debian.org/policy/pool/main/o/openjdk-17/openjdk-17_17.0.15+6-1~deb12u1.dsc /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_he |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_id |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_yi |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_he |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_id |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_yi |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/jpeg/jdk_6355567.jpg |binary /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/sun/java2d/pipe/duke.gif |binary openjdk-17-17.0.15+6/.jcheck/conf | 2 openjdk-17-17.0.15+6/debian/changelog | 35 openjdk-17-17.0.15+6/debian/patches/log-generated-classes-test.patch | 39 openjdk-17-17.0.15+6/debian/patches/series | 1 openjdk-17-17.0.15+6/debian/rules | 14 openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.in | 8 openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.sh | 8 openjdk-17-17.0.15+6/debian/tests/problems.csv | 5 openjdk-17-17.0.15+6/make/common/MakeBase.gmk | 1 openjdk-17-17.0.15+6/make/conf/github-actions.conf | 20 openjdk-17-17.0.15+6/make/conf/version-numbers.conf | 4 openjdk-17-17.0.15+6/make/data/lsrdata/language-subtag-registry.txt | 12 openjdk-17-17.0.15+6/make/data/tzdata/VERSION | 2 openjdk-17-17.0.15+6/make/data/tzdata/antarctica | 2 openjdk-17-17.0.15+6/make/data/tzdata/asia | 111 openjdk-17-17.0.15+6/make/data/tzdata/australasia | 113 openjdk-17-17.0.15+6/make/data/tzdata/etcetera | 4 openjdk-17-17.0.15+6/make/data/tzdata/europe | 2 openjdk-17-17.0.15+6/make/data/tzdata/factory | 10 openjdk-17-17.0.15+6/make/data/tzdata/leapseconds | 8 openjdk-17-17.0.15+6/make/data/tzdata/northamerica | 9 openjdk-17-17.0.15+6/make/data/tzdata/southamerica | 27 openjdk-17-17.0.15+6/make/data/tzdata/zone.tab | 2 openjdk-17-17.0.15+6/make/hotspot/lib/CompileJvm.gmk | 7 openjdk-17-17.0.15+6/make/test/JtregNativeHotspot.gmk | 3 openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/register_aarch64.hpp | 8 openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp | 20 openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/c2_init_ppc.cpp | 18 openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/vm_version_ppc.cpp | 22 openjdk-17-17.0.15+6/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp | 4 openjdk-17-17.0.15+6/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp | 15 openjdk-17-17.0.15+6/src/hotspot/os_cpu/windows_x86/os_windows_x86.cpp | 9 openjdk-17-17.0.15+6/src/hotspot/share/asm/codeBuffer.cpp | 7 openjdk-17-17.0.15+6/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp | 8 openjdk-17-17.0.15+6/src/hotspot/share/logging/logSelectionList.hpp | 2 openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.cpp | 14 openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.hpp | 14 openjdk-17-17.0.15+6/src/hotspot/share/opto/addnode.cpp | 39 openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.cpp | 80 openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.hpp | 6 openjdk-17-17.0.15+6/src/hotspot/share/opto/parse1.cpp | 2 openjdk-17-17.0.15+6/src/hotspot/share/opto/postaloc.cpp | 1 openjdk-17-17.0.15+6/src/hotspot/share/prims/jni.cpp | 40 openjdk-17-17.0.15+6/src/hotspot/share/prims/universalUpcallHandler.cpp | 8 openjdk-17-17.0.15+6/src/hotspot/share/runtime/deoptimization.cpp | 2 openjdk-17-17.0.15+6/src/hotspot/share/runtime/handshake.cpp | 14 openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.cpp | 3 openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.hpp | 11 openjdk-17-17.0.15+6/src/hotspot/share/runtime/synchronizer.cpp | 3 openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.cpp | 43 openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.hpp | 15 openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.cpp | 25 openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.hpp | 4 openjdk-17-17.0.15+6/src/hotspot/share/utilities/debug.cpp | 14 openjdk-17-17.0.15+6/src/hotspot/share/utilities/globalDefinitions.hpp | 10 openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPrivateKey.java | 309 +- openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPublicKey.java | 254 +- openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java | 62 openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java | 38 openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Permissions.java | 7 openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/SignedObject.java | 56 openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Timestamp.java | 13 openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java | 40 openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java | 23 openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarFile.java | 3 openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarInputStream.java | 12 openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarVerifier.java | 5 openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java | 44 openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/GZIPOutputStream.java | 4 openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java | 28 openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/spec/SecretKeySpec.java | 30 openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java | 59 openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java | 139 - openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java | 6 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/action/GetPropertyAction.java | 64 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/DRBG.java | 12 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java | 45 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java | 45 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/rsa/RSAPadding.java | 109 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/tools/keytool/Main.java | 2 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/KeyUtil.java | 32 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java | 18 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java | 27 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java | 18 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CamerfirmaTLSPolicy.java | 114 openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java | 123 - openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/DNSName.java | 12 openjdk-17-17.0.15+6/src/java.base/share/conf/security/java.security | 5 openjdk-17-17.0.15+6/src/java.base/unix/native/libjsig/jsig.c | 8 openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m | 3 openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m | 10 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/AdobeMarkerSegment.java | 18 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java | 13 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java | 8 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java | 15 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java | 4 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java | 24 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java | 12 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java | 12 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java | 10 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java | 24 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java | 7 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java | 65 openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java | 8 openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Font.java | 5 openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Toolkit.java | 20 openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/beans/Beans.java | 6 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/imageio/ImageIO.java | 19 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JEditorPane.java | 17 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JTabbedPane.java | 43 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/UIManager.java | 7 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java | 40 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java | 9 openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java | 11 openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/DebugSettings.java | 6 openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/FontConfiguration.java | 5 openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/print/PSPrinterJob.java | 9 openjdk-17-17.0.15+6/src/java.desktop/share/native/libawt/java2d/loops/Blit.c | 18 openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java | 11 openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java | 6 openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/PlatformGraphicsInfo.java | 31 openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/Win32GraphicsEnvironment.java | 13 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.cpp | 81 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.h | 4 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp | 4 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp | 6 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp | 4 openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_PlatformGraphicsInfo.cpp | 37 openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java | 19 openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java | 17 openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBError.java | 42 openjdk-17-17.0.15+6/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java | 17 openjdk-17-17.0.15+6/src/jdk.accessibility/windows/native/include/bridge/AccessBridgePackages.h | 4 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java | 11 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java | 13 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11SecureRandom.java | 16 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java | 54 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md | 24 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h | 18 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h | 17 openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h | 285 +- openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/LinuxDebuggerLocal.cpp | 1 openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/symtab.c | 4 openjdk-17-17.0.15+6/src/jdk.hotspot.agent/macosx/native/libsaproc/ps_core.c | 15 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/BindingReader.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/KeyMap.java | 11 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Binding.java | 7 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Buffer.java | 6 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Candidate.java | 20 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Completer.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletingParsedLine.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletionMatcher.java | 12 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EOFError.java | 20 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Editor.java | 4 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EndOfFileException.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Expander.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Highlighter.java | 2 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/History.java | 12 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReader.java | 50 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReaderBuilder.java | 11 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Macro.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/MaskingCallback.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/ParsedLine.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Parser.java | 6 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/PrintAboveWriter.java | 2 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Reference.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/SyntaxError.java | 18 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/UserInterruptException.java | 12 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Widget.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/BufferImpl.java | 20 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/CompletionMatcherImpl.java | 83 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultExpander.java | 33 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultHighlighter.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultParser.java | 144 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/InputRC.java | 394 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/KillRing.java | 2 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/LineReaderImpl.java | 1205 +++++----- openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/ReaderUtils.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/SimpleMaskingCallback.java | 9 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/UndoTree.java | 4 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/AggregateCompleter.java | 11 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/ArgumentCompleter.java | 11 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/EnumCompleter.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/FileNameCompleter.java | 20 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/NullCompleter.java | 9 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/StringsCompleter.java | 7 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/SystemCompleter.java | 27 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/history/DefaultHistory.java | 77 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Attributes.java | 146 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Cursor.java | 2 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/MouseEvent.java | 15 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Size.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Terminal.java | 59 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/TerminalBuilder.java | 537 +++- openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPosixTerminal.java | 16 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPty.java | 164 + openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractTerminal.java | 39 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsConsoleWriter.java | 9 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsTerminal.java | 160 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/CursorSupport.java | 13 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/Diag.java | 64 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminal.java | 73 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminalProvider.java | 92 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExecPty.java | 296 -- openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExternalTerminal.java | 93 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/LineDisciplineTerminal.java | 132 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/MouseSupport.java | 22 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/NativeSignalHandler.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixPtyTerminal.java | 34 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixSysTerminal.java | 16 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecPty.java | 311 ++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecTerminalProvider.java | 228 + openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/Pty.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/SystemStream.java | 15 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalExt.java | 31 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalProvider.java | 60 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AnsiWriter.java | 155 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedCharSequence.java | 40 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedString.java | 33 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStringBuilder.java | 127 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStyle.java | 96 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ClosedException.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ColorPalette.java | 25 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Colors.java | 165 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Curses.java | 33 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/DiffHelper.java | 39 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Display.java | 98 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ExecHelper.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/FastBufferedOutputStream.java | 61 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InfoCmp.java | 968 ++++---- openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InputStreamReader.java | 32 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Levenshtein.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Log.java | 11 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlocking.java | 21 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStream.java | 8 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStreamImpl.java | 42 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpInputStream.java | 12 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpReader.java | 9 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReader.java | 6 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReaderImpl.java | 47 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/OSUtils.java | 122 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/PumpReader.java | 5 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ShutdownHooks.java | 17 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Signals.java | 13 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Status.java | 287 +- openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/StyleResolver.java | 14 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Timeout.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WCWidth.java | 159 - openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WriterOutputStream.java | 12 openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/windows-conemu.caps | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/share/legal/jline.md | 4 openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/JnaTerminalProvider.java | 141 - openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinConsoleWriter.java | 10 openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinSysTerminal.java | 165 - openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32.java | 305 +- openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32Impl.java | 3 openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/WindowsAnsiWriter.java | 118 openjdk-17-17.0.15+6/src/jdk.internal.le/windows/native/lible/Kernel32.cpp | 10 openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java | 18 openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Resources.java | 2 openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/tools/jar/Main.java | 279 +- openjdk-17-17.0.15+6/src/jdk.javadoc/share/man/javadoc.1 | 13 openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java | 100 openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java | 134 - openjdk-17-17.0.15+6/src/jdk.jpackage/share/native/common/Log.cpp | 4 openjdk-17-17.0.15+6/test/failure_handler/Makefile | 5 openjdk-17-17.0.15+6/test/failure_handler/README | 5 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java | 30 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java | 6 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java | 31 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java | 6 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java | 27 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java | 5 openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java | 39 openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/common.properties | 14 openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/linux.properties | 11 openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/mac.properties | 7 openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/windows.properties | 8 openjdk-17-17.0.15+6/test/hotspot/gtest/compiler/test_directivesParser.cpp | 5 openjdk-17-17.0.15+6/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp | 3 openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestFixture.cpp | 2 openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestUtils.inline.hpp | 4 openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logConfiguration.cpp | 24 openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logFileOutput.cpp | 24 openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp | 2 openjdk-17-17.0.15+6/test/hotspot/gtest/memory/test_guardedMemory.cpp | 2 openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_instanceKlass.cpp | 2 openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_markWord.cpp | 7 openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp | 30 openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_globals.cpp | 6 openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_os.cpp | 10 openjdk-17-17.0.15+6/test/hotspot/jtreg/ProblemList.txt | 15 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java | 87 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm | 76 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm | 74 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java | 45 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java | 44 openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java | 183 + openjdk-17-17.0.15+6/test/hotspot/jtreg/gc/TestDisableExplicitGC.java | 1 openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java | 42 openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c | 104 openjdk-17-17.0.15+6/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java | 128 + openjdk-17-17.0.15+6/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/libFieldIndicesTest.cpp | 515 ++++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java | 8 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/exceptions/GotWrongOOMEException.java | 38 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java | 1 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java | 25 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java | 24 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java | 3 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java | 5 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java | 3 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java | 3 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.cpp | 169 - openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.h | 29 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java | 118 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/README | 2 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AODTestRunner.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AbstractJarAgent.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java | 2 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java | 2 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/JVMTITest.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace007.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace008.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace009.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace010.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace011.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace012.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace013.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace014.java | 5 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace015.java | 7 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/compiler/coverage/parentheses/Parentheses.java | 4 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/HeapOOMEException.java | 36 openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/TriggerUnloadingByFillingMetaspace.java | 5 openjdk-17-17.0.15+6/test/jdk/ProblemList.txt | 42 openjdk-17-17.0.15+6/test/jdk/TEST.groups | 8 openjdk-17-17.0.15+6/test/jdk/com/sun/crypto/provider/KeyProtector/IterationCount.java | 24 openjdk-17-17.0.15+6/test/jdk/com/sun/jdi/InterruptHangTest.java | 6 openjdk-17-17.0.15+6/test/jdk/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java | 11 openjdk-17-17.0.15+6/test/jdk/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java | 1 openjdk-17-17.0.15+6/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Password.java | 16 openjdk-17-17.0.15+6/test/jdk/com/sun/tools/attach/BasicTests.java | 3 openjdk-17-17.0.15+6/test/jdk/java/awt/Component/ComponentEventTest.java | 357 ++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DefaultFrameIconTest.java | 67 openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DisposeTest.java | 112 openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameDialogMixedTest.java | 82 openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FramePaintTest.java | 91 openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.html | 50 openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.java | 673 ++--- openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MaximizeUndecoratedTest.java | 129 + openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MenuCrash.java | 168 + openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MinimizeUndecoratedTest.java | 139 + openjdk-17-17.0.15+6/test/jdk/java/awt/FullScreen/SetFullScreenTest.java | 89 openjdk-17-17.0.15+6/test/jdk/java/awt/Graphics2D/ScaledTransform/ScaledTransform.java | 101 openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/NonDefaultGC.java | 124 + openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/Position.java | 94 openjdk-17-17.0.15+6/test/jdk/java/awt/List/HandlingKeyEventIfMousePressedTest.java | 167 + openjdk-17-17.0.15+6/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java | 30 openjdk-17-17.0.15+6/test/jdk/java/awt/List/ListActionEventTest.java | 93 openjdk-17-17.0.15+6/test/jdk/java/awt/List/MultiSelectionListHorizScrollbar.java | 80 openjdk-17-17.0.15+6/test/jdk/java/awt/List/RepaintAfterResize.java | 73 openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/ActionCommandTest.java | 111 openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/CheckMenuShortcut.java | 139 + openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/FunctionKeyShortcut.java | 140 + openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/MenuItemShortcutReplaceTest.java | 111 openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java | 21 openjdk-17-17.0.15+6/test/jdk/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java | 18 openjdk-17-17.0.15+6/test/jdk/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java | 13 openjdk-17-17.0.15+6/test/jdk/java/awt/PrintJob/PrintCheckboxTest/PrintCheckboxManualTest.java | 315 -- openjdk-17-17.0.15+6/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java | 178 + openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/CaretPositionTest/CaretPositionTest.java | 104 openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetBoundsTest/SetBoundsTest.java | 123 + openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetEchoCharTest4/SetEchoCharTest4.java | 101 openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetPasswordTest/SetPasswordTest.java | 105 openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/ZeroEchoCharTest/ZeroEchoCharTest.java | 89 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionCommand/ActionCommand.java | 89 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ModalityTest/ModalityTest.java | 16 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java | 16 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SystemTrayIconHelper.java | 22 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java | 16 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java | 58 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupClickTest.java | 71 openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java | 77 openjdk-17-17.0.15+6/test/jdk/java/awt/a11y/AccessibleJTableTest.java | 28 openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/DropActionChangeTest.java | 93 openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/NextDropActionTest/NextDropActionTest.java | 12 openjdk-17-17.0.15+6/test/jdk/java/awt/grab/CursorTest.java | 101 openjdk-17-17.0.15+6/test/jdk/java/awt/grab/SystemMenuTest.java | 141 + openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.html | 28 openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.java | 67 openjdk-17-17.0.15+6/test/jdk/java/awt/image/MemoryLeakTest/MemoryLeakTest.java | 215 - openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest.java | 169 + openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.html | 62 openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.java | 145 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.html | 29 openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.java | 142 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/NullPaper.java | 193 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/Orient.java | 464 --- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/PageSetupDialog.java | 533 +--- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.html | 49 openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.java | 132 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Cancel/PrinterJobCancel.java | 294 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Collate2DPrintingTest.java | 284 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawImage.java | 293 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawStringMethods.java | 179 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/InvalidPage.java | 311 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/JobName/PrinterJobName.java | 200 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/NumCopies.java | 197 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintAllFonts.java | 202 - openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintNullString.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java | 764 ++---- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest.java | 93 openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.html | 43 openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.java | 262 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/ValidatePage/ValidatePage.java | 650 ++--- openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/XparColor.java | 4 openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/raster/RasterTest.java | 333 -- openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392.java | 211 + openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.html | 44 openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.java | 287 -- openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java | 10 openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/Util.java | 2 openjdk-17-17.0.15+6/test/jdk/java/io/File/createTempFile/SpecialTempFile.java | 42 openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/Assert.java | 40 openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/GetSystemPackage.java | 8 openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/getResource/GetResource.java | 22 openjdk-17-17.0.15+6/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForImageTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForJDKTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/LoggerInImageTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForImageTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForJDKTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForImageTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForJDKTest.java | 3 openjdk-17-17.0.15+6/test/jdk/java/lang/System/SecurityManagerWarnings.java | 10 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/PrivateInvokeTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java | 2 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/findSpecial/FindSpecialTest.java | 20 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LUtils.java | 171 - openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java | 87 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlTest.java | 8 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAsm.java | 37 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaStackTrace.java | 35 openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java | 198 - openjdk-17-17.0.15+6/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java | 33 openjdk-17-17.0.15+6/test/jdk/java/net/Socket/CloseAvailable.java | 213 + openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/ManyRequests2.java | 10 openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java | 27 openjdk-17-17.0.15+6/test/jdk/java/nio/channels/FileChannel/LoopingTruncate.java | 13 openjdk-17-17.0.15+6/test/jdk/java/nio/channels/Selector/WakeupNow.java | 24 openjdk-17-17.0.15+6/test/jdk/java/nio/file/Files/probeContentType/Basic.java | 10 openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTime.java | 30 openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTimeHelper.java | 4 openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/libCreationTimeHelper.c | 112 openjdk-17-17.0.15+6/test/jdk/java/security/Policy/Root/Root.java | 79 openjdk-17-17.0.15+6/test/jdk/java/security/Security/ConfigFileTest.java | 45 openjdk-17-17.0.15+6/test/jdk/java/security/cert/CertPathValidator/OCSP/OCSPTimeout.java | 302 ++ openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/CertificateBuilder.java | 123 - openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/SimpleOCSPServer.java | 16 openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/BreakIteratorTest.java | 194 - openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/Bug4533872.java | 44 openjdk-17-17.0.15+6/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java | 86 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/APITest.java | 120 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Bug6271411.java | 22 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/CollatorTest.java | 141 - openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DanishTest.java | 21 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DummyTest.java | 26 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/EnglishTest.java | 24 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FinnishTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FrenchTest.java | 18 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/G7Test.java | 38 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/GermanTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/IteratorTest.java | 44 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/MonkeyTest.java | 29 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Regression.java | 137 - openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SpanishTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SurrogatesTest.java | 21 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Test4401726.java | 18 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/ThaiTest.java | 14 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/TurkishTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/text/Collator/VietnameseTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java | 86 openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4387255.java | 59 openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug8001209.java | 96 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/Bug4322313.java | 24 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java | 290 +- openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java | 48 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatTest.java | 292 +- openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java | 51 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestDateFormatAPI.java | 71 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestDateFormatSymbols.java | 52 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestSimpleDateFormatAPI.java | 66 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/TimeZoneNameTest.java | 43 openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/bug4358730.java | 17 openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/Bug4185816Test.java | 56 openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/MessageRegression.java | 263 +- openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/MessageTest.java | 25 openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/bug4492719.java | 26 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java | 36 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java | 88 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/Bug4838107.java | 6 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSExponential.java | 61 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java | 37 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java | 93 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java | 40 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java | 71 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberRegression.java | 514 ++-- openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberRoundTrip.java | 52 openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberTest.java | 129 - openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/PositionTest.java | 82 openjdk-17-17.0.15+6/test/jdk/java/text/Format/common/FormatIteratorTest.java | 96 openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/ICUBasicTest.java | 120 openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/NormalizerAPITest.java | 48 openjdk-17-17.0.15+6/test/jdk/java/text/testlib/HexDumpReader.java | 11 openjdk-17-17.0.15+6/test/jdk/java/text/testlib/IntlTest.java | 274 -- openjdk-17-17.0.15+6/test/jdk/java/text/testlib/TestUtils.java | 132 + openjdk-17-17.0.15+6/test/jdk/java/time/tck/java/time/TCKInstant.java | 21 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/BuddhistCalendarTest.java | 351 +- openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4302966.java | 14 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4766302.java | 21 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarLimitTest.java | 44 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarRegression.java | 655 ++--- openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarTest.java | 242 +- openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/FieldStateTest.java | 85 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/GregorianCutoverTest.java | 148 - openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/JulianTest.java | 15 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/NonLenientTest.java | 43 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java | 36 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4028518.java | 39 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4100311.java | 25 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4243802.java | 119 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4316678.java | 87 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4372743.java | 158 - openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4401223.java | 94 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4409072.java | 43 openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4514831.java | 142 - openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateRegression.java | 79 openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateTest.java | 62 openjdk-17-17.0.15+6/test/jdk/java/util/Date/TimestampTest.java | 23 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java | 98 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4152725.java | 76 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873Test.java | 136 - openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4210525.java | 49 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4316602.java | 45 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4518797.java | 104 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug6989440.java | 86 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug7069824.java | 468 --- openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8004240.java | 50 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8035133.java | 159 - openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8135061.java | 81 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8154797.java | 99 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8159420.java | 224 - openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8166994.java | 74 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8179071.java | 90 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CaseCheckVariant.java | 62 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CompareProviderFormats.java | 115 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/FilteringModeTest.java | 90 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetAdapterPreference.java | 52 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetInstanceCheck.java | 126 + openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java | 108 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeTest.java | 21 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java | 4 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java | 110 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleConstructors.java | 71 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleEnhanceTest.java | 86 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleMatchingTest.java | 476 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleProvidersRun.java | 32 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java | 76 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleTest.java | 230 + openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LookupOnValidRangeTest.java | 80 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java | 144 + openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java | 88 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/RootLocale.java | 48 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java | 81 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ThaiGov.java | 102 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/TurkishLangRangeTest.java | 185 + openjdk-17-17.0.15+6/test/jdk/java/util/Locale/UseOldISOCodesTest.java | 62 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4122700.java | 60 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.html | 1 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.java | 60 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6277243.java | 39 openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6312358.java | 83 openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java | 16 openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java | 66 openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java | 19 openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java | 53 openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java | 18 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug4322313.java | 36 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug6329116.java | 25 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java | 6 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java | 225 - openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/VERSION | 2 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/aliases.txt | 3 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java | 22 openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneRegression.java | 182 - openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneTest.java | 160 - openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TransitionTest.java | 28 openjdk-17-17.0.15+6/test/jdk/java/util/logging/LoggingDeadlock2.java | 21 openjdk-17-17.0.15+6/test/jdk/java/util/zip/Available.java | 155 - openjdk-17-17.0.15+6/test/jdk/java/util/zip/EntryCount64k.java | 7 openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java | 105 openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java | 72 openjdk-17-17.0.15+6/test/jdk/javax/accessibility/TestJMenuItemShortcutAccessibility.java | 112 openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java | 96 openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/default_local.policy | 4 openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/jpeg/LargeAdobeMarkerSegmentTest.java | 59 openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/wbmp/WBMPStreamTruncateTest.java | 115 openjdk-17-17.0.15+6/test/jdk/javax/management/MBeanServer/ExceptionTest.java | 11 openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java | 23 openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java | 5 openjdk-17-17.0.15+6/test/jdk/javax/management/security/HashedPasswordFileTest.java | 16 openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/DTLS/TEST.properties | 1 openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java | 4 openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractButton/bug4290656.java | 116 openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractDocument/bug4549069.java | 124 + openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractWriter/bug4185537.java | 140 + openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java | 45 openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuUI/bug4244616.java | 77 openjdk-17-17.0.15+6/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java | 93 openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java | 147 - openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4323121.java | 106 openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4490179.java | 109 openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html | 36 openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java | 91 openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java | 116 openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/bug8032667.java | 108 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java | 28 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html | 40 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java | 32 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.html | 32 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.java | 60 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.html | 39 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.java | 104 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.html | 31 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.java | 30 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.html | 37 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.java | 89 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.html | 32 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.java | 52 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.html | 32 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.java | 76 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.html | 31 openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.java | 42 openjdk-17-17.0.15+6/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java | 20 openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4765272.java | 130 + openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4979794.java | 91 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html | 31 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java | 62 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java | 16 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/FileSystemView/WindowsDefaultIconSizeTest.java | 8 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/bug4587721.java | 77 openjdk-17-17.0.15+6/test/jdk/javax/swing/JFrame/DefaultCloseOperation.java | 2 openjdk-17-17.0.15+6/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java | 77 openjdk-17-17.0.15+6/test/jdk/javax/swing/JPanel/bug4907772.java | 89 openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java | 81 openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollPane/bug4688907.java | 44 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java | 36 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTableHeader/bug4243927.java | 45 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4138694.java | 59 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4140421.java | 42 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4196662.java | 48 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4243930.java | 50 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4368050.java | 51 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4465534.java | 43 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4700351.java | 64 openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolTip/bug4107843.java | 52 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4161685.java | 52 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4210432.java | 80 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4213868.java | 62 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4224491.java | 61 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4237370.java | 81 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4662505.java | 63 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4696499.java | 105 openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug5039542.java | 42 openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4546474.java | 50 openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4677611.java | 55 openjdk-17-17.0.15+6/test/jdk/javax/swing/KeyboardManager/bug4345798.java | 118 openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4306431.java | 53 openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4736093.java | 167 + openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java | 55 openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java | 53 openjdk-17-17.0.15+6/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java | 38 openjdk-17-17.0.15+6/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java | 110 openjdk-17-17.0.15+6/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java | 121 - openjdk-17-17.0.15+6/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java | 139 + openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4756178.java | 93 openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4803649.java | 91 openjdk-17-17.0.15+6/test/jdk/javax/swing/ToolTipManager/bug5078214.java | 136 + openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java | 57 openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java | 65 openjdk-17-17.0.15+6/test/jdk/javax/swing/reliability/HangDuringStaticInitialization.java | 3 openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java | 53 openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java | 223 - openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/SetCaretRateTest.java | 46 openjdk-17-17.0.15+6/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java | 131 - openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/AbstractVectorTest.java | 6 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java | 21 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template | 2 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template | 2 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template | 2 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template | 4 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template | 4 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template | 2 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Unit-header.template | 5 openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template | 3 openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/AbstractWindowsTerminalTest.java | 11 openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/KeyConversionTest.java | 13 openjdk-17-17.0.15+6/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java | 8 openjdk-17-17.0.15+6/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java | 12 openjdk-17-17.0.15+6/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java | 84 openjdk-17-17.0.15+6/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java | 4 openjdk-17-17.0.15+6/test/jdk/jdk/jfr/startupargs/TestStartDuration.java | 3 openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/DefaultImage.java | 19 openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/ImageModules.java | 5 openjdk-17-17.0.15+6/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java | 15 openjdk-17-17.0.15+6/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java | 20 openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/DitherTest.java | 147 + openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/MultiOp.java | 108 openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/ByteBinaryBitmask.java | 88 openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/CustomSourceCM.java | 142 + openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiBlitOffscreenTest.java | 121 + openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiLockTest.java | 95 openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/DrawRoundRect0Bug.java | 69 openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/RevalidateBug.java | 104 openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/ScaledPolyTest.java | 95 openjdk-17-17.0.15+6/test/jdk/sun/java2d/pipe/DrawImageBgTest.java | 97 openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/PKCS11Test.java | 34 openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh | 3 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/KeyStore/DKSTest.java | 4 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java | 15 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy | 2 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy | 2 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy | 2 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy | 2 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java | 47 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy | 14 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java | 43 openjdk-17-17.0.15+6/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java | 4 openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Camerfirma.java | 75 openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java | 10 openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersca-chain.pem | 64 openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachamberscommerceca-chain.pem | 48 openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersignca-chain.pem | 62 openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java | 190 + openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java | 4 openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/RemovedFiles.java | 94 openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java | 73 openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/warnings/Test.java | 3 openjdk-17-17.0.15+6/test/jdk/sun/security/validator/samedn.sh | 9 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java | 69 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh | 91 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf | 40 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem | 16 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem | 12 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem | 16 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem | 12 openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java | 292 ++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java | 145 - openjdk-17-17.0.15+6/test/jdk/sun/util/resources/TimeZone/IntlTest.java | 228 - openjdk-17-17.0.15+6/test/jdk/tools/jpackage/TEST.properties | 9 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java | 36 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java | 3 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java | 22 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderBase.java | 72 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java | 70 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderTest.java | 99 openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java | 99 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java | 1 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java | 12 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java | 15 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java | 18 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java | 21 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java | 23 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java | 44 openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java | 2 openjdk-17-17.0.15+6/test/langtools/jdk/jshell/ExecPtyGetFlagsToSetTest.java | 11 openjdk-17-17.0.15+6/test/langtools/tools/javac/newlines/NewLineTest.java | 7 openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.java | 6 openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.out | 2 openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOptionThroughAPI.java | 4 openjdk-17-17.0.15+6/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java | 39 openjdk-17-17.0.15+6/test/lib-test/jdk/test/lib/util/JarUtilsTest.java | 77 openjdk-17-17.0.15+6/test/lib/jdk/test/lib/Platform.java | 13 openjdk-17-17.0.15+6/test/lib/jdk/test/lib/SecurityTools.java | 17 openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/ForceGC.java | 43 openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/JarUtils.java | 53 openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/security/Signatures.java | 197 + openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/util/Base64Decode.java | 2 861 files changed, 31917 insertions(+), 20660 deletions(-) diff -Nru openjdk-17-17.0.14+7/.jcheck/conf openjdk-17-17.0.15+6/.jcheck/conf --- openjdk-17-17.0.14+7/.jcheck/conf 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/.jcheck/conf 2025-04-09 19:45:33.000000000 +0000 @@ -1,7 +1,7 @@ [general] project=jdk-updates jbs=JDK -version=17.0.14 +version=17.0.15 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists diff -Nru openjdk-17-17.0.14+7/debian/changelog openjdk-17-17.0.15+6/debian/changelog --- openjdk-17-17.0.14+7/debian/changelog 2025-01-30 23:01:36.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/changelog 2025-05-01 08:40:21.000000000 +0000 @@ -1,8 +1,37 @@ -openjdk-17 (17.0.14+7-1~deb12u1) bookworm-security; urgency=medium +openjdk-17 (17.0.15+6-1~deb12u1) bookworm-security; urgency=medium - * Rebuild for Bookworm + * Rebuild for bookworm - -- Moritz Muehlenhoff Fri, 31 Jan 2025 00:01:36 +0100 + -- Moritz Mühlenhoff Thu, 01 May 2025 10:40:21 +0200 + +openjdk-17 (17.0.15+6-1) unstable; urgency=high + + * OpenJDK 17.0.15 release, build 6. + - Addresses CVE-2025-30698, CVE-2025-30691, CVE-2025-21587. + + * Honour DEB_BUILD_OPTIONS=parallel=N while running jtreg tests (Helmut + Grohne). Addresses: #1095920. + + -- Matthias Klose Thu, 24 Apr 2025 02:05:43 +0200 + +openjdk-17 (17.0.15~5ea-1) unstable; urgency=medium + + * OpenJDK 17.0.14 early access, build 5. + + [ Vladimir Petko ] + * d/t/problems.csv: Disable tests failing due to upstream bugs. + + -- Matthias Klose Thu, 27 Mar 2025 13:35:58 +0100 + +openjdk-17 (17.0.15~4ea-1) unstable; urgency=medium + + * OpenJDK 17.0.14 early access, build 4. + + [ Vladimir Petko ] + * d/rules: Disable dtrace on jammy armhf (was not enabled before and cannot + be built due to a GCC ICE (see LP #2091225). + + -- Matthias Klose Sat, 15 Mar 2025 09:45:37 +0100 openjdk-17 (17.0.14+7-1) unstable; urgency=medium diff -Nru openjdk-17-17.0.14+7/debian/patches/log-generated-classes-test.patch openjdk-17-17.0.15+6/debian/patches/log-generated-classes-test.patch --- openjdk-17-17.0.14+7/debian/patches/log-generated-classes-test.patch 2024-03-20 22:00:09.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/patches/log-generated-classes-test.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -Description: Skip test when getFileStore() fails - Due to https://bugs.openjdk.org/browse/JDK-8166162 getFileStore() fails with exception - failing the test suite. Skip test when getFileStore() throws. -Author: Vladimir Petko -Bug: https://bugs.openjdk.org/browse/JDK-8166162 -Forwarded: not-needed -Last-Update: 2023-03-27 ---- a/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java -+++ b/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java -@@ -195,14 +195,21 @@ - - @Test - public void testDumpDirNotWritable() throws IOException { -- if (!Files.getFileStore(Paths.get(".")) -- .supportsFileAttributeView(PosixFileAttributeView.class)) { -- // No easy way to setup readonly directory without POSIX -- // We would like to skip the test with a cause with -- // throw new SkipException("Posix not supported"); -- // but jtreg will report failure so we just pass the test -- // which we can look at if jtreg changed its behavior -- System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); -+ try -+ { -+ if (!Files.getFileStore(Paths.get(".")) -+ .supportsFileAttributeView(PosixFileAttributeView.class)) { -+ // No easy way to setup readonly directory without POSIX -+ // We would like to skip the test with a cause with -+ // throw new SkipException("Posix not supported"); -+ // but jtreg will report failure so we just pass the test -+ // which we can look at if jtreg changed its behavior -+ System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); -+ return; -+ } -+ } -+ catch (Throwable t) { -+ System.out.println("WARNING: Mount point not found (JDK-8166162). Skipping testDumpDirNotWritable test."); - return; - } - diff -Nru openjdk-17-17.0.14+7/debian/patches/series openjdk-17-17.0.15+6/debian/patches/series --- openjdk-17-17.0.14+7/debian/patches/series 2024-09-09 13:48:15.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/patches/series 2025-03-15 09:15:16.000000000 +0000 @@ -31,7 +31,6 @@ 8314491-jexec.patch update-assertion-for-armhf.patch misalign-pointer-for-armhf.patch -log-generated-classes-test.patch update-permission-test.patch ldap-timeout-test-use-ip.patch test-use-ip-address.patch diff -Nru openjdk-17-17.0.14+7/debian/rules openjdk-17-17.0.15+6/debian/rules --- openjdk-17-17.0.14+7/debian/rules 2025-01-22 09:17:58.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/rules 2025-04-24 00:05:43.000000000 +0000 @@ -83,6 +83,7 @@ endif is_upstream_release = yes +#is_upstream_release = srcdir = . builddir = build @@ -393,7 +394,16 @@ # PPC*, S390x and SH do not support dtrace probes # https://github.com/openjdk/jdk/pull/13228 ifeq (,$(filter $(DEB_HOST_ARCH),$(no_dtrace_archs))) - COMMON_CONFIGURE_ARGS += --enable-dtrace + # disable dtrace due to GCC ICE in jammy: https://launchpad.net/bugs/2091225 + ifneq (,$(filter $(DEB_HOST_ARCH),armhf)) + ifneq (,$(filter $(distrel),jammy)) + COMMON_CONFIGURE_ARGS += --disable-dtrace + else + COMMON_CONFIGURE_ARGS += --enable-dtrace + endif + else + COMMON_CONFIGURE_ARGS += --enable-dtrace + endif endif COMMON_CONFIGURE_ARGS += --with-jni-libpath=/usr/lib/$(DEB_HOST_MULTIARCH)/jni:/lib/$(DEB_HOST_MULTIARCH):/usr/lib/$(DEB_HOST_MULTIARCH):/usr/lib/jni:/lib:/usr/lib @@ -1987,7 +1997,7 @@ dh_builddeb -a $(nodemo) $(nojrez) #$(bd_options) git_project = jdk17u -git_tag = jdk-17.0.14+7 +git_tag = jdk-17.0.15+6 package_version = $(subst jdk-,,$(git_tag)) package_version = $(shell echo $(PKGVERSION) | sed 's/-[^-][^-]*$$//') ifneq ($(is_upstream_release),yes) diff -Nru openjdk-17-17.0.14+7/debian/tests/jtreg-autopkgtest.in openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.in --- openjdk-17-17.0.14+7/debian/tests/jtreg-autopkgtest.in 2024-08-08 06:36:30.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.in 2025-04-03 11:07:08.000000000 +0000 @@ -30,7 +30,13 @@ jt_options+=" -Xmx256M" fi if dpkg --compare-versions ${jtreg_version} ge 4.2; then - jt_options+=" -conc:auto" + njobs=auto + for opt in ${DEB_BUILD_OPTIONS:-}; do + if test "${opt#parallel=}" != "$opt"; then + njobs="${opt#parallel=}" + fi + done + jt_options+=" -conc:$njobs" fi # check java binary diff -Nru openjdk-17-17.0.14+7/debian/tests/jtreg-autopkgtest.sh openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.sh --- openjdk-17-17.0.14+7/debian/tests/jtreg-autopkgtest.sh 2024-08-08 06:36:30.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/tests/jtreg-autopkgtest.sh 2025-04-03 11:07:08.000000000 +0000 @@ -30,7 +30,13 @@ jt_options+=" -Xmx256M" fi if dpkg --compare-versions ${jtreg_version} ge 4.2; then - jt_options+=" -conc:auto" + njobs=auto + for opt in ${DEB_BUILD_OPTIONS:-}; do + if test "${opt#parallel=}" != "$opt"; then + njobs="${opt#parallel=}" + fi + done + jt_options+=" -conc:$njobs" fi # check java binary diff -Nru openjdk-17-17.0.14+7/debian/tests/problems.csv openjdk-17-17.0.15+6/debian/tests/problems.csv --- openjdk-17-17.0.14+7/debian/tests/problems.csv 2025-01-17 08:14:54.000000000 +0000 +++ openjdk-17-17.0.15+6/debian/tests/problems.csv 2025-03-25 11:43:59.000000000 +0000 @@ -33,6 +33,7 @@ FAILED: java/nio/file/Files/Misc.java,JDK-8166162,Container issue,:openjdk-lts:openjdk-11::openjdk-17:openjdk-21:openjdk-22:openjdk-23:openjdk-24:openjdk-25:,:arch-all,:release-all FAILED: java/nio/file/Files/TemporaryFiles.java,JDK-8166162,Container issue,:openjdk-lts:openjdk-11::openjdk-17:openjdk-21:openjdk-22:openjdk-23:openjdk-24:openjdk-25:,:arch-all,:release-all FAILED: java/nio/file/FileStore/Basic.java,JDK-8166162,Container issue,:openjdk-lts:openjdk-11::openjdk-17:openjdk-21:openjdk-22:openjdk-23:openjdk-24:openjdk-25:,:arch-all,:release-all +FAILED: com/sun/net/httpserver/simpleserver/RootDirPermissionsTest.java,JDK-8166162,Container issue,:openjdk-lts:openjdk-11::openjdk-17:openjdk-21:openjdk-22:openjdk-23:openjdk-24:openjdk-25:,:arch-all,:release-all FAILED: runtime/cds/appcds/jcmd/JCmdTestDynamicDump.java,,flaky test (?) existing comment,:openjdk-17,:arch-all,:release-all FAILED: runtime/cds/appcds/jcmd/JCmdTestFileSafety.java,,flaky test (?) existing comment,:openjdk-17,i386:arm64:amd64:ppc64el,:release-all FAILED: runtime/cds/appcds/jcmd/JCmdTestStaticDump.java,,flaky test (?) existing comment,:openjdk-17,:arch-all,:release-all @@ -74,6 +75,7 @@ FAILED: java/foreign/TestDowncallScope.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: java/foreign/TestSegments.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: java/foreign/TestLinker.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all +FAILED: java/foreign/nested/TestNested.java,CODETOOLS-7903948, test is compiled without --enable-preview flag,:openjdk-21,:arch-all,:release-all FAILED: java/foreign/TestAddressDereference.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: java/foreign/TestUpcallHighArity.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: java/foreign/TestUpcallStructScope.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all @@ -82,5 +84,6 @@ FAILED: java/foreign/TestUpcallStack.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: java/foreign/TestVarArgs.java,, asserts due to the invalid structure size. Ignore as this is a preview API and the issue does not occur in openjdk-22. I will add it to the problemlist.,:openjdk-21,:armhf,:release-all FAILED: runtime/os/TestTrimNative.java#trimNative,, java.lang.RuntimeException: We found fewer (periodic) trim lines in UL log than expected (expected at least 13 found 11). This looks like a flaky test - it asserts number of lines from the periodic trimmer e.g. src/hotspot/share/runtime/trimNativeHeap.hpp:56 which causes the test to fail due to the slow VM. Test passes locally.,:openjdk-21,:armhf,:release-all -FAILED: jdk/sun/security/util/Debug/DebugOptions.java,JDK-8339713,Stack overflow error on 32-bit platforms,:openjdk-17:openjdk-21:openjdk-23:openjdk-24:openjdk-25:,:armhf:i386:s390x,:release-all +FAILED: sun/security/util/Debug/DebugOptions.java,JDK-8339713,Stack overflow error on 32-bit platforms,:openjdk-17:openjdk-21:openjdk-23:openjdk-24:openjdk-25:,:armhf:i386:s390x,:release-all Error: jdk/jshell/TerminalNoExecTest.java,,BackingStoreException: Couldn't get file lock - possibly because the LP (non-root) container has no home directory,:openjdk-23:openjdk-24:openjdk-25:,:arch-all,:release-all +FAILED: applications/ctw/modules/jdk_jfr.java,JDK-8352567, Unimplemented SharedRuntime::generate_jfr_write_checkpoint for S390x, :openjdk-25:,:s390x,:release-all diff -Nru openjdk-17-17.0.14+7/make/common/MakeBase.gmk openjdk-17-17.0.15+6/make/common/MakeBase.gmk --- openjdk-17-17.0.14+7/make/common/MakeBase.gmk 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/common/MakeBase.gmk 2025-04-09 19:45:33.000000000 +0000 @@ -290,6 +290,7 @@ $(CP) -fRP '$(call DecodeSpace, $<)' '$(call DecodeSpace, $@)'; \ fi if [ -n "`$(XATTR) -ls '$(call DecodeSpace, $@)'`" ]; then \ + $(CHMOD) -h u+w '$(call DecodeSpace, $@)'; \ $(XATTR) -cs '$(call DecodeSpace, $@)'; \ fi endef diff -Nru openjdk-17-17.0.14+7/make/conf/github-actions.conf openjdk-17-17.0.15+6/make/conf/github-actions.conf --- openjdk-17-17.0.14+7/make/conf/github-actions.conf 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/conf/github-actions.conf 2025-04-09 19:45:33.000000000 +0000 @@ -29,17 +29,17 @@ JTREG_VERSION=7.3.1+1 LINUX_X64_BOOT_JDK_EXT=tar.gz -LINUX_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.11%2B9/OpenJDK17U-jdk_x64_linux_hotspot_17.0.11_9.tar.gz -LINUX_X64_BOOT_JDK_SHA256=aa7fb6bb342319d227a838af5c363bfa1b4a670c209372f9e6585bd79da6220c - -MACOS_X64_BOOT_JDK_EXT=tar.gz -MACOS_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.11%2B9/OpenJDK17U-jdk_x64_mac_hotspot_17.0.11_9.tar.gz -MACOS_X64_BOOT_JDK_SHA256=f8b96724618f4df557c47f11048d1084e98ed3eb87f0dbd5b84f768a80c3348e +LINUX_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14%2B7/OpenJDK17U-jdk_x64_linux_hotspot_17.0.14_7.tar.gz +LINUX_X64_BOOT_JDK_SHA256=a3af83983fb94dd7d11b13ba2dba0fb6819dc2caaf87e6937afd22ad4680ae9a MACOS_AARCH64_BOOT_JDK_EXT=tar.gz -MACOS_AARCH64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.11%2B9/OpenJDK17U-jdk_aarch64_mac_hotspot_17.0.11_9.tar.gz -MACOS_AARCH64_BOOT_JDK_SHA256=09a162c58dd801f7cfacd87e99703ed11fb439adc71cfa14ceb2d3194eaca01c +MACOS_AARCH64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14%2B7/OpenJDK17U-jdk_aarch64_mac_hotspot_17.0.14_7.tar.gz +MACOS_AARCH64_BOOT_JDK_SHA256=95bcc8052340394b87644d71a60fb26f31857f4090a7dfee57113e9e0f2dfacb + +MACOS_X64_BOOT_JDK_EXT=tar.gz +MACOS_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14%2B7/OpenJDK17U-jdk_x64_mac_hotspot_17.0.14_7.tar.gz +MACOS_X64_BOOT_JDK_SHA256=bc2e9225d156d27149fc7a91817e6b64f76132b2b81d1f44cb8c90d7497b6ea7 WINDOWS_X64_BOOT_JDK_EXT=zip -WINDOWS_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.11%2B9/OpenJDK17U-jdk_x64_windows_hotspot_17.0.11_9.zip -WINDOWS_X64_BOOT_JDK_SHA256=fdd6664d4131370398fbc8bfbb7b46dbfec4a22a090a511fe5c379dae188c390 +WINDOWS_X64_BOOT_JDK_URL=https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.14%2B7/OpenJDK17U-jdk_x64_windows_hotspot_17.0.14_7.zip +WINDOWS_X64_BOOT_JDK_SHA256=dddb108e0bf8c3e3a9c5c782fee5874a6a86d5323189969f17094260cf3a1125 diff -Nru openjdk-17-17.0.14+7/make/conf/version-numbers.conf openjdk-17-17.0.15+6/make/conf/version-numbers.conf --- openjdk-17-17.0.14+7/make/conf/version-numbers.conf 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/conf/version-numbers.conf 2025-04-09 19:45:33.000000000 +0000 @@ -28,12 +28,12 @@ DEFAULT_VERSION_FEATURE=17 DEFAULT_VERSION_INTERIM=0 -DEFAULT_VERSION_UPDATE=14 +DEFAULT_VERSION_UPDATE=15 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2025-01-21 +DEFAULT_VERSION_DATE=2025-04-15 DEFAULT_VERSION_CLASSFILE_MAJOR=61 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 diff -Nru openjdk-17-17.0.14+7/make/data/lsrdata/language-subtag-registry.txt openjdk-17-17.0.15+6/make/data/lsrdata/language-subtag-registry.txt --- openjdk-17-17.0.14+7/make/data/lsrdata/language-subtag-registry.txt 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/lsrdata/language-subtag-registry.txt 2025-04-09 19:45:33.000000000 +0000 @@ -1,4 +1,4 @@ -File-Date: 2024-06-14 +File-Date: 2024-11-19 %% Type: language Subtag: aa @@ -47991,6 +47991,16 @@ Prefix: kw %% Type: variant +Subtag: kleinsch +Description: Kleinschmidt orthography +Description: Allattaasitaamut +Added: 2024-07-20 +Prefix: kl +Prefix: kl-tunumiit +Comments: Orthography for Greenlandic designed by Samuel Kleinschmidt, + used from 1851 to 1973. +%% +Type: variant Subtag: kociewie Description: The Kociewie dialect of Polish Added: 2014-11-27 diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/VERSION openjdk-17-17.0.15+6/make/data/tzdata/VERSION --- openjdk-17-17.0.14+7/make/data/tzdata/VERSION 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/VERSION 2025-04-09 19:45:33.000000000 +0000 @@ -21,4 +21,4 @@ # or visit www.oracle.com if you need additional information or have any # questions. # -tzdata2024b +tzdata2025a diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/antarctica openjdk-17-17.0.15+6/make/data/tzdata/antarctica --- openjdk-17-17.0.14+7/make/data/tzdata/antarctica 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/antarctica 2025-04-09 19:45:33.000000000 +0000 @@ -197,6 +197,8 @@ # France & Italy - year-round base # Concordia, -750600+1232000, since 2005 +# https://en.wikipedia.org/wiki/Concordia_Station +# Can use Asia/Singapore, which it has agreed with since inception. # Germany - year-round base # Neumayer III, -704080-0081602, since 2009 diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/asia openjdk-17-17.0.15+6/make/data/tzdata/asia --- openjdk-17-17.0.14+7/make/data/tzdata/asia 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/asia 2025-04-09 19:45:33.000000000 +0000 @@ -3688,21 +3688,70 @@ # be immediately followed by 1845-01-01; see R.H. van Gent's # History of the International Date Line # https://webspace.science.uu.nl/~gent0113/idl/idl_philippines.htm -# The rest of the data entries are from Shanks & Pottenger. -# From Jesper Nørgaard Welen (2006-04-26): -# ... claims that Philippines had DST last time in 1990: -# http://story.philippinetimes.com/p.x/ct/9/id/145be20cc6b121c0/cid/3e5bbccc730d258c/ -# [a story dated 2006-04-25 by Cris Larano of Dow Jones Newswires, -# but no details] - -# From Paul Eggert (2014-08-14): -# The following source says DST may be instituted November-January and again -# March-June, but this is not definite. It also says DST was last proclaimed -# during the Ramos administration (1992-1998); but again, no details. -# Carcamo D. PNoy urged to declare use of daylight saving time. -# Philippine Star 2014-08-05 -# http://www.philstar.com/headlines/2014/08/05/1354152/pnoy-urged-declare-use-daylight-saving-time +# From P Chan (2021-05-10): +# Here's a fairly comprehensive article in Japanese: +# https://wiki.suikawiki.org/n/Philippine%20Time +# (2021-05-16): +# According to the references listed in the article, +# the periods that the Philippines (Manila) observed DST or used +9 are: +# +# 1936-10-31 24:00 to 1937-01-15 24:00 +# (Proclamation No. 104, Proclamation No. 126) +# 1941-12-15 24:00 to 1945-11-30 24:00 +# (Proclamation No. 789, Proclamation No. 20) +# 1954-04-11 24:00 to 1954-06-04 24:00 +# (Proclamation No. 13, Proclamation No. 33) +# 1977-03-27 24:00 to 1977-09-21 24:00 +# (Proclamation No. 1629, Proclamation No. 1641) +# 1990-05-21 00:00 to 1990-07-28 24:00 +# (National Emergency Memorandum Order No. 17, Executive Order No. 415) +# +# Proclamation No. 104 ... October 30, 1936 +# https://www.officialgazette.gov.ph/1936/10/30/proclamation-no-104-s-1936/ +# Proclamation No. 126 ... January 15, 1937 +# https://www.officialgazette.gov.ph/1937/01/15/proclamation-no-126-s-1937/ +# Proclamation No. 789 ... December 13, 1941 +# https://www.officialgazette.gov.ph/1941/12/13/proclamation-no-789-s-1941/ +# Proclamation No. 20 ... November 11, 1945 +# https://www.officialgazette.gov.ph/1945/11/11/proclamation-no-20-s-1945/ +# Proclamation No. 13 ... April 6, 1954 +# https://www.officialgazette.gov.ph/1954/04/06/proclamation-no-13-s-1954/ +# Proclamation No. 33 ... June 3, 1954 +# https://www.officialgazette.gov.ph/1954/06/03/proclamation-no-33-s-1954/ +# Proclamation No. 1629 ... March 25, 1977 +# https://www.officialgazette.gov.ph/1977/03/25/proclamation-no-1629-s-1977/ +# Proclamation No. 1641 ...May 26, 1977 +# https://www.officialgazette.gov.ph/1977/05/26/proclamation-no-1641-s-1977/ +# National Emergency Memorandum Order No. 17 ... May 2, 1990 +# https://www.officialgazette.gov.ph/1990/05/02/national-emergency-memorandum-order-no-17-s-1990/ +# Executive Order No. 415 ... July 20, 1990 +# https://www.officialgazette.gov.ph/1990/07/20/executive-order-no-415-s-1990/ +# +# During WWII, Proclamation No. 789 fixed two periods of DST. The first period +# was set to continue only until January 31, 1942. But Manila was occupied by +# the Japanese earlier in the month.... +# +# For the date of the adoption of standard time, Shank[s] gives 1899-05-11. +# The article is not able to state the basis of that. I guess it was based on +# a US War Department Circular issued on that date. +# https://books.google.com/books?id=JZ1PAAAAYAAJ&pg=RA3-PA8 +# +# However, according to other sources, standard time was adopted on +# 1899-09-06. Also, the LMT was GMT+8:03:52 +# https://books.google.com/books?id=MOYIAQAAIAAJ&pg=PA521 +# https://books.google.com/books?id=lSnqqatpYikC&pg=PA21 +# +# From Paul Eggert (2024-09-05): +# The penultimate URL in P Chan's email refers to page 521 of +# Selga M, The Time Service in the Philippines. +# Proc Pan-Pacific Science Congress. Vol. 1 (1923), 519-532. +# It says, "The change from the meridian 120° 58' 04" to the 120th implied a +# change of 3 min. 52s.26 in time; consequently on 6th September, 1899, +# Manila Observatory gave the noon signal 3 min. 52s.26 later than before". +# +# Wikipedia says the US declared Manila liberated on March 4, 1945; +# this doesn't affect clocks, just our time zone abbreviation and DST flag. # From Paul Goyette (2018-06-15) with URLs updated by Guy Harris (2024-02-15): # In the Philippines, there is a national law, Republic Act No. 10535 @@ -3720,24 +3769,26 @@ # influence of the sources. There is no current abbreviation for DST, # so use "PDT", the usual American style. -# From P Chan (2021-05-10): -# Here's a fairly comprehensive article in Japanese: -# https://wiki.suikawiki.org/n/Philippine%20Time -# From Paul Eggert (2021-05-10): -# The info in the Japanese table has not been absorbed (yet) below. - # Rule NAME FROM TO - IN ON AT SAVE LETTER/S -Rule Phil 1936 only - Nov 1 0:00 1:00 D -Rule Phil 1937 only - Feb 1 0:00 0 S -Rule Phil 1954 only - Apr 12 0:00 1:00 D -Rule Phil 1954 only - Jul 1 0:00 0 S -Rule Phil 1978 only - Mar 22 0:00 1:00 D -Rule Phil 1978 only - Sep 21 0:00 0 S +Rule Phil 1936 only - Oct 31 24:00 1:00 D +Rule Phil 1937 only - Jan 15 24:00 0 S +Rule Phil 1941 only - Dec 15 24:00 1:00 D +# The following three rules were canceled by Japan: +#Rule Phil 1942 only - Jan 31 24:00 0 S +#Rule Phil 1942 only - Mar 1 0:00 1:00 D +#Rule Phil 1942 only - Jun 30 24:00 0 S +Rule Phil 1945 only - Nov 30 24:00 0 S +Rule Phil 1954 only - Apr 11 24:00 1:00 D +Rule Phil 1954 only - Jun 4 24:00 0 S +Rule Phil 1977 only - Mar 27 24:00 1:00 D +Rule Phil 1977 only - Sep 21 24:00 0 S +Rule Phil 1990 only - May 21 0:00 1:00 D +Rule Phil 1990 only - Jul 28 24:00 0 S # Zone NAME STDOFF RULES FORMAT [UNTIL] -Zone Asia/Manila -15:56:00 - LMT 1844 Dec 31 - 8:04:00 - LMT 1899 May 11 - 8:00 Phil P%sT 1942 May - 9:00 - JST 1944 Nov +Zone Asia/Manila -15:56:08 - LMT 1844 Dec 31 + 8:03:52 - LMT 1899 Sep 6 4:00u + 8:00 Phil P%sT 1942 Feb 11 24:00 + 9:00 - JST 1945 Mar 4 8:00 Phil P%sT # Bahrain diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/australasia openjdk-17-17.0.15+6/make/data/tzdata/australasia --- openjdk-17-17.0.14+7/make/data/tzdata/australasia 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/australasia 2025-04-09 19:45:33.000000000 +0000 @@ -1262,10 +1262,10 @@ # The 1992 ending date used in the rules is a best guess; # it matches what was used in the past. -# The Australian Bureau of Meteorology FAQ -# http://www.bom.gov.au/faq/faqgen.htm -# (1999-09-27) writes that Giles Meteorological Station uses -# South Australian time even though it's located in Western Australia. +# From Christopher Hunt (2006-11-21), after an advance warning +# from Jesper Nørgaard Welen (2006-11-01): +# WA are trialing DST for three years. +# http://www.parliament.wa.gov.au/parliament/bills.nsf/9A1B183144403DA54825721200088DF1/$File/Bill175-1B.pdf # From Paul Eggert (2018-04-01): # The Guardian Express of Perth, Australia reported today that the @@ -1277,54 +1277,10 @@ # https://www.communitynews.com.au/guardian-express/news/exclusive-daylight-savings-coming-wa-summer-2018/ # [The article ends with "Today's date is April 1."] -# Queensland - -# From Paul Eggert (2018-02-26): -# I lack access to the following source for Queensland DST: -# Pearce C. History of daylight saving time in Queensland. -# Queensland Hist J. 2017 Aug;23(6):389-403 -# https://search.informit.com.au/documentSummary;dn=994682348436426;res=IELHSS - -# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): -# # The state of QUEENSLAND.. [ Courtesy Qld. Dept Premier Econ&Trade Devel ] -# # [ Dec 1990 ] -# ... -# Zone Australia/Queensland 10:00 AQ %sST -# ... -# Rule AQ 1971 only - Oct lastSun 2:00 1:00 D -# Rule AQ 1972 only - Feb lastSun 3:00 0 E -# Rule AQ 1989 max - Oct lastSun 2:00 1:00 D -# Rule AQ 1990 max - Mar Sun>=1 3:00 0 E - -# From Bradley White (1989-12-24): -# "Australia/Queensland" now observes daylight time (i.e. from -# October 1989). - -# From Bradley White (1991-03-04): -# A recent excerpt from an Australian newspaper... -# ...Queensland...[has] agreed to end daylight saving -# at 3am tomorrow (March 3)... - -# From John Mackin (1991-03-06): -# I can certainly confirm for my part that Daylight Saving in NSW did in fact -# end on Sunday, 3 March. I don't know at what hour, though. (It surprised -# me.) - -# From Bradley White (1992-03-08): -# ...there was recently a referendum in Queensland which resulted -# in the experimental daylight saving system being abandoned. So, ... -# ... -# Rule QLD 1989 1991 - Oct lastSun 2:00 1:00 D -# Rule QLD 1990 1992 - Mar Sun>=1 3:00 0 S -# ... - -# From Arthur David Olson (1992-03-08): -# The chosen rules the union of the 1971/1972 change and the 1989-1992 changes. - -# From Christopher Hunt (2006-11-21), after an advance warning -# from Jesper Nørgaard Welen (2006-11-01): -# WA are trialing DST for three years. -# http://www.parliament.wa.gov.au/parliament/bills.nsf/9A1B183144403DA54825721200088DF1/$File/Bill175-1B.pdf +# The Australian Bureau of Meteorology FAQ +# http://www.bom.gov.au/faq/faqgen.htm +# (1999-09-27) writes that Giles Meteorological Station uses +# South Australian time even though it's located in Western Australia. # From Rives McDow (2002-04-09): # The most interesting region I have found consists of three towns on the @@ -1382,6 +1338,59 @@ # For lack of better info, assume the tradition dates back to the # introduction of standard time in 1895. +# From Stuart Bishop (2024-11-12): +# An article discussing the in-use but technically unofficial timezones +# in the Western Australian portion of the Nullarbor Plain. +# https://www.abc.net.au/news/2024-11-22/outback-wa-properties-strange-time-zones/104542494 +# From Paul Eggert (2024-11-12): +# As the article says, the Eyre Bird Observatory and nearby sheep stations +# can use Tokyo time. Other possibilities include Asia/Chita, Asia/Seoul, +# and Asia/Jayapura. + +# Queensland + +# From Paul Eggert (2018-02-26): +# I lack access to the following source for Queensland DST: +# Pearce C. History of daylight saving time in Queensland. +# Queensland Hist J. 2017 Aug;23(6):389-403 +# https://search.informit.com.au/documentSummary;dn=994682348436426;res=IELHSS + +# From George Shepherd via Simon Woodhead via Robert Elz (1991-03-06): +# # The state of QUEENSLAND.. [ Courtesy Qld. Dept Premier Econ&Trade Devel ] +# # [ Dec 1990 ] +# ... +# Zone Australia/Queensland 10:00 AQ %sST +# ... +# Rule AQ 1971 only - Oct lastSun 2:00 1:00 D +# Rule AQ 1972 only - Feb lastSun 3:00 0 E +# Rule AQ 1989 max - Oct lastSun 2:00 1:00 D +# Rule AQ 1990 max - Mar Sun>=1 3:00 0 E + +# From Bradley White (1989-12-24): +# "Australia/Queensland" now observes daylight time (i.e. from +# October 1989). + +# From Bradley White (1991-03-04): +# A recent excerpt from an Australian newspaper... +# ...Queensland...[has] agreed to end daylight saving +# at 3am tomorrow (March 3)... + +# From John Mackin (1991-03-06): +# I can certainly confirm for my part that Daylight Saving in NSW did in fact +# end on Sunday, 3 March. I don't know at what hour, though. (It surprised +# me.) + +# From Bradley White (1992-03-08): +# ...there was recently a referendum in Queensland which resulted +# in the experimental daylight saving system being abandoned. So, ... +# ... +# Rule QLD 1989 1991 - Oct lastSun 2:00 1:00 D +# Rule QLD 1990 1992 - Mar Sun>=1 3:00 0 S +# ... + +# From Arthur David Olson (1992-03-08): +# The chosen rules the union of the 1971/1972 change and the 1989-1992 changes. + # southeast Australia # diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/etcetera openjdk-17-17.0.15+6/make/data/tzdata/etcetera --- openjdk-17-17.0.14+7/make/data/tzdata/etcetera 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/etcetera 2025-04-09 19:45:33.000000000 +0000 @@ -74,6 +74,10 @@ # so we moved the names into the Etc subdirectory. # Also, the time zone abbreviations are now compatible with %z. +# There is no "Etc/Unknown" entry, as CLDR says that "Etc/Unknown" +# corresponds to an unknown or invalid time zone, and things would get +# confusing if Etc/Unknown were made valid here. + Zone Etc/GMT-14 14 - %z Zone Etc/GMT-13 13 - %z Zone Etc/GMT-12 12 - %z diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/europe openjdk-17-17.0.15+6/make/data/tzdata/europe --- openjdk-17-17.0.14+7/make/data/tzdata/europe 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/europe 2025-04-09 19:45:33.000000000 +0000 @@ -1170,7 +1170,7 @@ # However, Greenland will change to Daylight Saving Time again in 2024 # and onwards. -# From a contributor who wishes to remain anonymous for now (2023-10-29): +# From Jule Dabars (2023-10-29): # https://www.dr.dk/nyheder/seneste/i-nat-skal-uret-stilles-en-time-tilbage-men-foerste-gang-sker-det-ikke-i-groenland # with a link to that page: # https://naalakkersuisut.gl/Nyheder/2023/10/2710_sommertid diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/factory openjdk-17-17.0.15+6/make/data/tzdata/factory --- openjdk-17-17.0.14+7/make/data/tzdata/factory 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/factory 2025-04-09 19:45:33.000000000 +0000 @@ -31,5 +31,15 @@ # time zone abbreviation "-00", indicating that the actual time zone # is unknown. +# TZ="Factory" was added to TZDB in 1989, and in 2016 its abbreviation +# was changed to "-00" from a longish English-language error message. +# Around 2010, CLDR added "Etc/Unknown" for use with TZDB, to stand +# for an unknown or invalid time zone. These two notions differ: +# TZ="Factory" is a valid timezone, so tzalloc("Factory") succeeds, whereas +# TZ="Etc/Unknown" is invalid and tzalloc("Etc/Unknown") fails. +# Also, a downstream distributor could modify Factory to be a +# default timezone suitable for the devices it manufactures, +# whereas that cannot happen for Etc/Unknown. + # Zone NAME STDOFF RULES FORMAT Zone Factory 0 - -00 diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/leapseconds openjdk-17-17.0.15+6/make/data/tzdata/leapseconds --- openjdk-17-17.0.14+7/make/data/tzdata/leapseconds 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/leapseconds 2025-04-09 19:45:33.000000000 +0000 @@ -92,11 +92,11 @@ # Any additional leap seconds will come after this. # This Expires line is commented out for now, # so that pre-2020a zic implementations do not reject this file. -#Expires 2025 Jun 28 00:00:00 +#Expires 2025 Dec 28 00:00:00 # POSIX timestamps for the data in this file: -#updated 1720104763 (2024-07-04 14:52:43 UTC) -#expires 1751068800 (2025-06-28 00:00:00 UTC) +#updated 1736208000 (2025-01-07 00:00:00 UTC) +#expires 1766880000 (2025-12-28 00:00:00 UTC) # Updated through IERS Bulletin C (https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat) -# File expires on 28 June 2025 +# File expires on 28 December 2025 diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/northamerica openjdk-17-17.0.15+6/make/data/tzdata/northamerica --- openjdk-17-17.0.14+7/make/data/tzdata/northamerica 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/northamerica 2025-04-09 19:45:33.000000000 +0000 @@ -50,9 +50,12 @@ # in New York City (1869-10). His 1870 proposal was based on Washington, DC, # but in 1872-05 he moved the proposed origin to Greenwich. -# From Paul Eggert (2018-03-20): +# From Paul Eggert (2024-11-18): # Dowd's proposal left many details unresolved, such as where to draw -# lines between time zones. The key individual who made time zones +# lines between time zones. Sandford Fleming of the Canadian Pacific Railway +# argued for Dowd's proposal in 1876, and Cleveland Abbe of the American +# Meteorology Society published a report in 1879 recommending four US time +# zones based on GMT. However, the key individual who made time zones # work in the US was William Frederick Allen - railway engineer, # managing editor of the Travelers' Guide, and secretary of the # General Time Convention, a railway standardization group. Allen @@ -2654,7 +2657,7 @@ # http://puentelibre.mx/noticia/ciudad_juarez_cambio_horario_noviembre_2022/ # Rule NAME FROM TO - IN ON AT SAVE LETTER/S -Rule Mexico 1931 only - April 30 0:00 1:00 D +Rule Mexico 1931 only - Apr 30 0:00 1:00 D Rule Mexico 1931 only - Oct 1 0:00 0 S Rule Mexico 1939 only - Feb 5 0:00 1:00 D Rule Mexico 1939 only - Jun 25 0:00 0 S diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/southamerica openjdk-17-17.0.15+6/make/data/tzdata/southamerica --- openjdk-17-17.0.14+7/make/data/tzdata/southamerica 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/southamerica 2025-04-09 19:45:33.000000000 +0000 @@ -1710,7 +1710,7 @@ # and that on the first Sunday of the month of October, it is to be set # forward 60 minutes, in all the territory of the Paraguayan Republic. # ... -Rule Para 2010 max - Oct Sun>=1 0:00 1:00 - +Rule Para 2010 2024 - Oct Sun>=1 0:00 1:00 - Rule Para 2010 2012 - Apr Sun>=8 0:00 0 - # # From Steffen Thorsen (2013-03-07): @@ -1729,14 +1729,35 @@ # https://www.abc.com.py/politica/2023/07/12/promulgacion-el-cambio-de-hora-sera-por-ley/ # From Carlos Raúl Perasso (2023-07-27): # http://silpy.congreso.gov.py/descarga/ley-144138 -Rule Para 2013 max - Mar Sun>=22 0:00 0 - +Rule Para 2013 2024 - Mar Sun>=22 0:00 0 - +# +# From Heitor David Pinto (2024-09-24): +# Today the Congress of Paraguay passed a bill to observe UTC-3 permanently.... +# The text of the bill says that it would enter into force on the first +# Sunday in October 2024, the same date currently scheduled to start DST.... +# https://silpy.congreso.gov.py/web/expediente/132531 +# (2024-10-14): +# The president approved the law on 11 October 2024, +# and it was officially published on 14 October 2024. +# https://www.gacetaoficial.gov.py/index/detalle_publicacion/89723 +# The text of the law says that it enters into force on the first +# Sunday in October 2024 (6 October 2024). But the constitution +# prohibits retroactive effect, and the civil code says that laws +# enter into force on the day after their publication or on the day +# that they specify, and it also says that they don't have retroactive +# effect. So I think that the time change on 6 October 2024 should +# still be considered as DST according to the previous law, and +# permanently UTC-3 from 15 October 2024 according to the new law.... +# https://www.constituteproject.org/constitution/Paraguay_2011 +# https://www.oas.org/dil/esp/codigo_civil_paraguay.pdf # Zone NAME STDOFF RULES FORMAT [UNTIL] Zone America/Asuncion -3:50:40 - LMT 1890 -3:50:40 - AMT 1931 Oct 10 # Asunción Mean Time -4:00 - %z 1972 Oct -3:00 - %z 1974 Apr - -4:00 Para %z + -4:00 Para %z 2024 Oct 15 + -3:00 - %z # Peru # diff -Nru openjdk-17-17.0.14+7/make/data/tzdata/zone.tab openjdk-17-17.0.15+6/make/data/tzdata/zone.tab --- openjdk-17-17.0.14+7/make/data/tzdata/zone.tab 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/data/tzdata/zone.tab 2025-04-09 19:45:33.000000000 +0000 @@ -333,7 +333,7 @@ PF -2308-13457 Pacific/Gambier Gambier Islands PG -0930+14710 Pacific/Port_Moresby most of Papua New Guinea PG -0613+15534 Pacific/Bougainville Bougainville -PH +1435+12100 Asia/Manila +PH +143512+1205804 Asia/Manila PK +2452+06703 Asia/Karachi PL +5215+02100 Europe/Warsaw PM +4703-05620 America/Miquelon diff -Nru openjdk-17-17.0.14+7/make/hotspot/lib/CompileJvm.gmk openjdk-17-17.0.15+6/make/hotspot/lib/CompileJvm.gmk --- openjdk-17-17.0.14+7/make/hotspot/lib/CompileJvm.gmk 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/hotspot/lib/CompileJvm.gmk 2025-04-09 19:45:33.000000000 +0000 @@ -87,6 +87,13 @@ DISABLED_WARNINGS_gcc += return-type switch clobbered endif +ifeq ($(DEBUG_LEVEL), fastdebug) + ifeq ($(call And, $(call isTargetOs, linux) $(call isTargetCpu, aarch64)), true) + # False positive warnings for atomic_linux_aarch64.hpp on GCC >= 13 + DISABLED_WARNINGS_gcc += stringop-overflow + endif +endif + DISABLED_WARNINGS_clang := tautological-compare \ undefined-var-template sometimes-uninitialized unknown-pragmas \ delete-non-virtual-dtor missing-braces char-subscripts \ diff -Nru openjdk-17-17.0.14+7/make/test/JtregNativeHotspot.gmk openjdk-17-17.0.15+6/make/test/JtregNativeHotspot.gmk --- openjdk-17-17.0.14+7/make/test/JtregNativeHotspot.gmk 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/make/test/JtregNativeHotspot.gmk 2025-04-09 19:45:33.000000000 +0000 @@ -873,7 +873,7 @@ ifeq ($(call isTargetOs, windows), true) BUILD_HOTSPOT_JTREG_EXECUTABLES_CFLAGS_exeFPRegs := -MT - BUILD_HOTSPOT_JTREG_EXCLUDE += exesigtest.c libterminatedThread.c libTestJNI.c libnativeStack.c + BUILD_HOTSPOT_JTREG_EXCLUDE += exesigtest.c libterminatedThread.c libTestJNI.c libnativeStack.c exeGetCreatedJavaVMs.c BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libatExit := jvm.lib else BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libbootclssearch_agent += -lpthread @@ -1511,6 +1511,7 @@ BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libterminatedThread += -lpthread BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libatExit += -ljvm BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libnativeStack += -lpthread + BUILD_HOTSPOT_JTREG_EXECUTABLES_LIBS_exeGetCreatedJavaVMs := -ljvm -lpthread endif # This evaluation is expensive and should only be done if this target was diff -Nru openjdk-17-17.0.14+7/src/hotspot/cpu/aarch64/register_aarch64.hpp openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/register_aarch64.hpp --- openjdk-17-17.0.14+7/src/hotspot/cpu/aarch64/register_aarch64.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/register_aarch64.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -140,7 +140,13 @@ max_slots_per_register = 8, save_slots_per_register = 2, slots_per_neon_register = 4, - extra_save_slots_per_neon_register = slots_per_neon_register - save_slots_per_register + extra_save_slots_per_neon_register = slots_per_neon_register - save_slots_per_register, + neon_vl = 16, + // VLmax: The maximum sve vector length is determined by the hardware + // sve_vl_min <= VLmax <= sve_vl_max. + sve_vl_min = 16, + // Maximum supported vector length across all CPUs + sve_vl_max = 256 }; // construction diff -Nru openjdk-17-17.0.14+7/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp --- openjdk-17-17.0.14+7/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/cpu/aarch64/vm_version_aarch64.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -24,6 +24,7 @@ */ #include "precompiled.hpp" +#include "register_aarch64.hpp" #include "runtime/arguments.hpp" #include "runtime/globals_extension.hpp" #include "runtime/java.hpp" @@ -400,14 +401,27 @@ if (FLAG_IS_DEFAULT(UseSVE)) { FLAG_SET_DEFAULT(UseSVE, (_features & CPU_SVE2) ? 2 : 1); } - if (UseSVE > 0) { - _initial_sve_vector_length = get_current_sve_vector_length(); - } } else if (UseSVE > 0) { warning("UseSVE specified, but not supported on current CPU. Disabling SVE."); FLAG_SET_DEFAULT(UseSVE, 0); } + if (UseSVE > 0) { + int vl = get_current_sve_vector_length(); + if (vl < 0) { + warning("Unable to get SVE vector length on this system. " + "Disabling SVE. Specify -XX:UseSVE=0 to shun this warning."); + FLAG_SET_DEFAULT(UseSVE, 0); + } else if ((vl == 0) || ((vl % FloatRegisterImpl::sve_vl_min) != 0) || !is_power_of_2(vl)) { + warning("Detected SVE vector length (%d) should be a power of two and a multiple of %d. " + "Disabling SVE. Specify -XX:UseSVE=0 to shun this warning.", + vl, FloatRegisterImpl::sve_vl_min); + FLAG_SET_DEFAULT(UseSVE, 0); + } else { + _initial_sve_vector_length = vl; + } + } + // This machine allows unaligned memory accesses if (FLAG_IS_DEFAULT(UseUnalignedAccesses)) { FLAG_SET_DEFAULT(UseUnalignedAccesses, true); diff -Nru openjdk-17-17.0.14+7/src/hotspot/cpu/ppc/c2_init_ppc.cpp openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/c2_init_ppc.cpp --- openjdk-17-17.0.14+7/src/hotspot/cpu/ppc/c2_init_ppc.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/c2_init_ppc.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -34,21 +34,5 @@ // Processor dependent initialization of C2 compiler for ppc. void Compile::pd_compiler2_init() { - - // Power7 and later. - if (PowerArchitecturePPC64 > 6) { - if (FLAG_IS_DEFAULT(UsePopCountInstruction)) { - FLAG_SET_ERGO(UsePopCountInstruction, true); - } - } - - if (!VM_Version::has_isel() && FLAG_IS_DEFAULT(ConditionalMoveLimit)) { - FLAG_SET_ERGO(ConditionalMoveLimit, 0); - } - - if (OptimizeFill) { - warning("OptimizeFill is not supported on this CPU."); - FLAG_SET_DEFAULT(OptimizeFill, false); - } - + guarantee(CodeEntryAlignment >= InteriorEntryAlignment, ""); } diff -Nru openjdk-17-17.0.14+7/src/hotspot/cpu/ppc/vm_version_ppc.cpp openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/vm_version_ppc.cpp --- openjdk-17-17.0.14+7/src/hotspot/cpu/ppc/vm_version_ppc.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/cpu/ppc/vm_version_ppc.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -117,6 +117,17 @@ FLAG_SET_ERGO(TrapBasedRangeChecks, false); } + // Power7 and later. + if (PowerArchitecturePPC64 > 6) { + if (FLAG_IS_DEFAULT(UsePopCountInstruction)) { + FLAG_SET_ERGO(UsePopCountInstruction, true); + } + } + + if (!VM_Version::has_isel() && FLAG_IS_DEFAULT(ConditionalMoveLimit)) { + FLAG_SET_ERGO(ConditionalMoveLimit, 0); + } + if (PowerArchitecturePPC64 >= 8) { if (FLAG_IS_DEFAULT(SuperwordUseVSX)) { FLAG_SET_ERGO(SuperwordUseVSX, true); @@ -176,6 +187,17 @@ FLAG_SET_DEFAULT(UseByteReverseInstructions, false); } } + + if (OptimizeFill) { + warning("OptimizeFill is not supported on this CPU."); + FLAG_SET_DEFAULT(OptimizeFill, false); + } + + if (OptoScheduling) { + // The OptoScheduling information is not maintained in ppd.ad. + warning("OptoScheduling is not supported on this CPU."); + FLAG_SET_DEFAULT(OptoScheduling, false); + } #endif // Create and print feature-string. diff -Nru openjdk-17-17.0.14+7/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp openjdk-17-17.0.15+6/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp --- openjdk-17-17.0.14+7/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -225,9 +225,9 @@ jlong kmem_limit = kernel_memory_limit_in_bytes(); jlong kmem_max_usage = kernel_memory_max_usage_in_bytes(); + OSContainer::print_container_helper(st, kmem_limit, "kernel_memory_limit_in_bytes"); OSContainer::print_container_helper(st, kmem_usage, "kernel_memory_usage_in_bytes"); - OSContainer::print_container_helper(st, kmem_limit, "kernel_memory_max_usage_in_bytes"); - OSContainer::print_container_helper(st, kmem_max_usage, "kernel_memory_limit_in_bytes"); + OSContainer::print_container_helper(st, kmem_max_usage, "kernel_memory_max_usage_in_bytes"); } char * CgroupV1Subsystem::cpu_cpuset_cpus() { diff -Nru openjdk-17-17.0.14+7/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp openjdk-17-17.0.15+6/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp --- openjdk-17-17.0.14+7/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/os_cpu/linux_x86/os_linux_x86.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -560,6 +560,21 @@ st->print(", ERR=" INTPTR_FORMAT, (intptr_t)uc->uc_mcontext.gregs[REG_ERR]); st->cr(); st->print(" TRAPNO=" INTPTR_FORMAT, (intptr_t)uc->uc_mcontext.gregs[REG_TRAPNO]); + // Add XMM registers + MXCSR. Note that C2 uses XMM to spill GPR values including pointers. + st->cr(); + st->cr(); + // Sanity check: fpregs should point into the context. + if ((address)uc->uc_mcontext.fpregs < (address)uc || + pointer_delta(uc->uc_mcontext.fpregs, uc, 1) >= sizeof(ucontext_t)) { + st->print_cr("bad uc->uc_mcontext.fpregs: " INTPTR_FORMAT " (uc: " INTPTR_FORMAT ")", + p2i(uc->uc_mcontext.fpregs), p2i(uc)); + } else { + for (int i = 0; i < 16; ++i) { + const int64_t* xmm_val_addr = (int64_t*)&(uc->uc_mcontext.fpregs->_xmm[i]); + st->print_cr("XMM[%d]=" INTPTR_FORMAT " " INTPTR_FORMAT, i, xmm_val_addr[1], xmm_val_addr[0]); + } + st->print(" MXCSR=" UINT32_FORMAT_X_0, uc->uc_mcontext.fpregs->mxcsr); + } #else st->print( "EAX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EAX]); st->print(", EBX=" INTPTR_FORMAT, uc->uc_mcontext.gregs[REG_EBX]); diff -Nru openjdk-17-17.0.14+7/src/hotspot/os_cpu/windows_x86/os_windows_x86.cpp openjdk-17-17.0.15+6/src/hotspot/os_cpu/windows_x86/os_windows_x86.cpp --- openjdk-17-17.0.14+7/src/hotspot/os_cpu/windows_x86/os_windows_x86.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/os_cpu/windows_x86/os_windows_x86.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -432,6 +432,15 @@ st->cr(); st->print( "RIP=" INTPTR_FORMAT, uc->Rip); st->print(", EFLAGS=" INTPTR_FORMAT, uc->EFlags); + // Add XMM registers + MXCSR. Note that C2 uses XMM to spill GPR values including pointers. + st->cr(); + st->cr(); + for (int i = 0; i < 16; ++i) { + const uint64_t *xmm = ((const uint64_t*)&(uc->Xmm0)) + 2 * i; + st->print_cr("XMM[%d]=" INTPTR_FORMAT " " INTPTR_FORMAT, + i, xmm[1], xmm[0]); + } + st->print(" MXCSR=" UINT32_FORMAT_X_0, uc->MxCsr); #else st->print( "EAX=" INTPTR_FORMAT, uc->Eax); st->print(", EBX=" INTPTR_FORMAT, uc->Ebx); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/asm/codeBuffer.cpp openjdk-17-17.0.15+6/src/hotspot/share/asm/codeBuffer.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/asm/codeBuffer.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/asm/codeBuffer.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -135,10 +135,11 @@ // Previous incarnations of this buffer are held live, so that internal // addresses constructed before expansions will not be confused. cb->free_blob(); + } + if (_overflow_arena != nullptr) { // free any overflow storage - delete cb->_overflow_arena; + delete _overflow_arena; } - // Claim is that stack allocation ensures resources are cleaned up. // This is resource clean up, let's hope that all were properly copied out. NOT_PRODUCT(free_strings();) @@ -940,8 +941,6 @@ CodeSection* this_sect = code_section(n); this_sect->take_over_code_from(cb_sect); } - _overflow_arena = cb->_overflow_arena; - cb->_overflow_arena = NULL; // Make sure the old cb won't try to use it or free it. DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress); } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp openjdk-17-17.0.15+6/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/jfr/leakprofiler/checkpoint/rootResolver.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -248,12 +248,6 @@ ReferenceLocateClosure rcl(_callback, OldObjectRoot::_threads, OldObjectRoot::_stack_variable, jt); if (jt->has_last_Java_frame()) { - // Traverse the monitor chunks - MonitorChunk* chunk = jt->monitor_chunks(); - for (; chunk != NULL; chunk = chunk->next()) { - chunk->oops_do(&rcl); - } - if (rcl.complete()) { return true; } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/logging/logSelectionList.hpp openjdk-17-17.0.15+6/src/hotspot/share/logging/logSelectionList.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/logging/logSelectionList.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/logging/logSelectionList.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -37,7 +37,7 @@ // Consists of ordered LogSelections, i.e. "tag1+tag2=level1,tag3*=level2". class LogSelectionList : public StackObj { public: - static const size_t MaxSelections = 256; + static const size_t MaxSelections = 320; private: friend void LogConfiguration::configure_stdout(LogLevelType, int, ...); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/memory/resourceArea.cpp openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/memory/resourceArea.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,18 @@ #ifdef ASSERT +ResourceMark::ResourceMark(ResourceArea* area, Thread* thread) : + _impl(area), + _thread(thread), + _previous_resource_mark(nullptr) +{ + if (_thread != nullptr) { + assert(_thread == Thread::current(), "not the current thread"); + _previous_resource_mark = _thread->current_resource_mark(); + _thread->set_current_resource_mark(this); + } +} + void ResourceArea::verify_has_resource_mark() { if (_nesting <= 0) { // Only report the first occurrence of an allocating thread that diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/memory/resourceArea.hpp openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/memory/resourceArea.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/memory/resourceArea.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -195,17 +195,7 @@ #ifndef ASSERT ResourceMark(ResourceArea* area, Thread* thread) : _impl(area) {} #else - ResourceMark(ResourceArea* area, Thread* thread) : - _impl(area), - _thread(thread), - _previous_resource_mark(nullptr) - { - if (_thread != nullptr) { - assert(_thread == Thread::current(), "not the current thread"); - _previous_resource_mark = _thread->current_resource_mark(); - _thread->set_current_resource_mark(this); - } - } + ResourceMark(ResourceArea* area, Thread* thread); #endif // ASSERT public: diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/opto/addnode.cpp openjdk-17-17.0.15+6/src/hotspot/share/opto/addnode.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/opto/addnode.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/opto/addnode.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1164,6 +1164,14 @@ (c > 0 && (java_add(t_hi, c) < t_hi))); } +// Check if addition of a long with type 't' and a constant 'c' can overflow. +static bool can_overflow(const TypeLong* t, jlong c) { + jlong t_lo = t->_lo; + jlong t_hi = t->_hi; + return ((c < 0 && (java_add(t_lo, c) > t_lo)) || + (c > 0 && (java_add(t_hi, c) < t_hi))); +} + //============================================================================= //------------------------------Idealize--------------------------------------- // MINs show up in range-check loop limit calculations. Look for @@ -1285,6 +1293,31 @@ // // Note: we assume that SubL was already replaced by an AddL, and that the stride // has its sign flipped: SubL(limit, stride) -> AddL(limit, -stride). +// +// Proof MaxL collapsed version equivalent to original (MinL version similar): +// is_sub_con ensures that con1, con2 ∈ [min_int, 0[ +// +// Original: +// - AddL2 underflow => x + con2 ∈ ]max_long - min_int, max_long], ALWAYS BAILOUT as x + con1 + con2 surely fails can_overflow (*) +// - AddL2 no underflow => x + con2 ∈ [min_long, max_long] +// - MaxL2 clamp => min_int +// - AddL1 underflow: NOT POSSIBLE: cannot underflow since min_int + con1 ∈ [2 * min_int, min_int] always > min_long +// - AddL1 no underflow => min_int + con1 ∈ [2 * min_int, min_int] +// - MaxL1 clamp => min_int (RESULT 1) +// - MaxL1 no clamp: NOT POSSIBLE: min_int + con1 ∈ [2 * min_int, min_int] always <= min_int, so clamp always taken +// - MaxL2 no clamp => x + con2 ∈ [min_int, max_long] +// - AddL1 underflow: NOT POSSIBLE: cannot underflow since x + con2 + con1 ∈ [2 * min_int, max_long] always > min_long +// - AddL1 no underflow => x + con2 + con1 ∈ [2 * min_int, max_long] +// - MaxL1 clamp => min_int (RESULT 2) +// - MaxL1 no clamp => x + con2 + con1 ∈ ]min_int, max_long] (RESULT 3) +// +// Collapsed: +// - AddL2 (cannot underflow) => con2 + con1 ∈ [2 * min_int, 0] +// - AddL1 underflow: NOT POSSIBLE: would have bailed out at can_overflow (*) +// - AddL1 no underflow => x + con2 + con1 ∈ [min_long, max_long] +// - MaxL clamp => min_int (RESULT 1 and RESULT 2) +// - MaxL no clamp => x + con2 + con1 ∈ ]min_int, max_long] (RESULT 3) +// Node* fold_subI_no_underflow_pattern(Node* n, PhaseGVN* phase) { assert(n->Opcode() == Op_MaxL || n->Opcode() == Op_MinL, "sanity"); // Check that the two clamps have the correct values. @@ -1314,6 +1347,10 @@ Node* x = add2->in(1); Node* con2 = add2->in(2); if (is_sub_con(con2)) { + // Collapsed graph not equivalent if potential over/underflow -> bailing out (*) + if (can_overflow(phase->type(x)->is_long(), con1->get_long() + con2->get_long())) { + return nullptr; + } Node* new_con = phase->transform(new AddLNode(con1, con2)); Node* new_sub = phase->transform(new AddLNode(x, new_con)); n->set_req_X(1, new_sub, phase); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/opto/loopnode.cpp openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/opto/loopnode.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -3930,23 +3930,6 @@ return progress; } -#ifdef ASSERT -// Goes over all children of the root of the loop tree. Check if any of them have a path -// down to Root, that does not go via a NeverBranch exit. -bool PhaseIdealLoop::only_has_infinite_loops() { - ResourceMark rm; - Unique_Node_List worklist; - // start traversal at all loop heads of first-level loops - for (IdealLoopTree* l = _ltree_root->_child; l != nullptr; l = l->_next) { - Node* head = l->_head; - assert(head->is_Region(), ""); - worklist.push(head); - } - return RegionNode::are_all_nodes_in_infinite_subgraph(worklist); -} -#endif - - //============================================================================= //----------------------------build_and_optimize------------------------------- // Create a PhaseLoop. Build the ideal Loop tree. Map each Ideal Node to @@ -4005,13 +3988,9 @@ return; } - // Verify that the has_loops() flag set at parse time is consistent - // with the just built loop tree. With infinite loops, it could be - // that one pass of loop opts only finds infinite loops, clears the - // has_loops() flag but adds NeverBranch nodes so the next loop opts - // verification pass finds a non empty loop tree. When the back edge + // Verify that the has_loops() flag set at parse time is consistent with the just built loop tree. When the back edge // is an exception edge, parsing doesn't set has_loops(). - assert(_ltree_root->_child == nullptr || C->has_loops() || only_has_infinite_loops() || C->has_exception_backedge(), "parsing found no loops but there are some"); + assert(_ltree_root->_child == nullptr || C->has_loops() || C->has_exception_backedge(), "parsing found no loops but there are some"); // No loops after all if( !_ltree_root->_child && !_verify_only ) C->set_has_loops(false); @@ -4759,7 +4738,7 @@ if ( bltstack.length() == stack_size ) { // There were no additional children, post visit node now (void)bltstack.pop(); // Remove node from stack - pre_order = build_loop_tree_impl( n, pre_order ); + pre_order = build_loop_tree_impl(n, pre_order); // Check for bailout if (C->failing()) { return; @@ -4776,7 +4755,7 @@ } //------------------------------build_loop_tree_impl--------------------------- -int PhaseIdealLoop::build_loop_tree_impl( Node *n, int pre_order ) { +int PhaseIdealLoop::build_loop_tree_impl(Node* n, int pre_order) { // ---- Post-pass Work ---- // Pre-walked but not post-walked nodes need a pre_order number. @@ -4787,24 +4766,24 @@ // for it. Then find the tightest enclosing loop for the self Node. for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) { Node* m = n->fast_out(i); // Child - if( n == m ) continue; // Ignore control self-cycles - if( !m->is_CFG() ) continue;// Ignore non-CFG edges + if (n == m) continue; // Ignore control self-cycles + if (!m->is_CFG()) continue;// Ignore non-CFG edges IdealLoopTree *l; // Child's loop - if( !is_postvisited(m) ) { // Child visited but not post-visited? + if (!is_postvisited(m)) { // Child visited but not post-visited? // Found a backedge - assert( get_preorder(m) < pre_order, "should be backedge" ); + assert(get_preorder(m) < pre_order, "should be backedge"); // Check for the RootNode, which is already a LoopNode and is allowed // to have multiple "backedges". - if( m == C->root()) { // Found the root? + if (m == C->root()) { // Found the root? l = _ltree_root; // Root is the outermost LoopNode } else { // Else found a nested loop // Insert a LoopNode to mark this loop. l = new IdealLoopTree(this, m, n); } // End of Else found a nested loop - if( !has_loop(m) ) // If 'm' does not already have a loop set + if (!has_loop(m)) { // If 'm' does not already have a loop set set_loop(m, l); // Set loop header to loop now - + } } else { // Else not a nested loop if( !_nodes[m->_idx] ) continue; // Dead code has no loop IdealLoopTree* m_loop = get_loop(m); @@ -4813,23 +4792,17 @@ // is a member of some outer enclosing loop. Since there are no // shared headers (I've split them already) I only need to go up // at most 1 level. - while( l && l->_head == m ) // Successor heads loop? + while (l && l->_head == m) { // Successor heads loop? l = l->_parent; // Move up 1 for me + } // If this loop is not properly parented, then this loop // has no exit path out, i.e. its an infinite loop. - if( !l ) { + if (!l) { // Make loop "reachable" from root so the CFG is reachable. Basically // insert a bogus loop exit that is never taken. 'm', the loop head, // points to 'n', one (of possibly many) fall-in paths. There may be // many backedges as well. - // Here I set the loop to be the root loop. I could have, after - // inserting a bogus loop exit, restarted the recursion and found my - // new loop exit. This would make the infinite loop a first-class - // loop and it would then get properly optimized. What's the use of - // optimizing an infinite loop? - l = _ltree_root; // Oops, found infinite loop - if (!_verify_only) { // Insert the NeverBranch between 'm' and it's control user. NeverBranchNode *iff = new NeverBranchNode( m ); @@ -4854,7 +4827,7 @@ // Now create the never-taken loop exit Node *if_f = new CProjNode( iff, 1 ); _igvn.register_new_node_with_optimizer(if_f); - set_loop(if_f, l); + set_loop(if_f, _ltree_root); // Find frame ptr for Halt. Relies on the optimizer // V-N'ing. Easier and quicker than searching through // the program structure. @@ -4863,10 +4836,27 @@ // Halt & Catch Fire Node* halt = new HaltNode(if_f, frame, "never-taken loop exit reached"); _igvn.register_new_node_with_optimizer(halt); - set_loop(halt, l); + set_loop(halt, _ltree_root); C->root()->add_req(halt); } set_loop(C->root(), _ltree_root); + // move to outer most loop with same header + l = m_loop; + while (true) { + IdealLoopTree* next = l->_parent; + if (next == nullptr || next->_head != m) { + break; + } + l = next; + } + // properly insert infinite loop in loop tree + sort(_ltree_root, l); + // fix child link from parent + IdealLoopTree* p = l->_parent; + l->_next = p->_child; + p->_child = l; + // code below needs enclosing loop + l = l->_parent; } } // Weeny check for irreducible. This child was already visited (this @@ -4906,7 +4896,7 @@ assert( get_loop(n) == innermost, "" ); IdealLoopTree *p = innermost->_parent; IdealLoopTree *l = innermost; - while( p && l->_head == n ) { + while (p && l->_head == n) { l->_next = p->_child; // Put self on parents 'next child' p->_child = l; // Make self as first child of parent l = p; // Now walk up the parent chain @@ -4920,7 +4910,7 @@ // Record tightest enclosing loop for self. Mark as post-visited. set_loop(n, innermost); // Also record has_call flag early on - if( innermost ) { + if (innermost) { if( n->is_Call() && !n->is_CallLeaf() && !n->is_macro() ) { // Do not count uncommon calls if( !n->is_CallStaticJava() || !n->as_CallStaticJava()->_name ) { diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/opto/loopnode.hpp openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/opto/loopnode.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/opto/loopnode.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -927,10 +927,6 @@ void update_main_loop_skeleton_predicates(Node* ctrl, CountedLoopNode* loop_head, Node* init, int stride_con); void copy_skeleton_predicates_to_post_loop(LoopNode* main_loop_head, CountedLoopNode* post_loop_head, Node* init, Node* stride); void insert_loop_limit_check(ProjNode* limit_check_proj, Node* cmp_limit, Node* bol); -#ifdef ASSERT - bool only_has_infinite_loops(); -#endif - void log_loop_tree(); public: @@ -1036,7 +1032,7 @@ // Place 'n' in some loop nest, where 'n' is a CFG node void build_loop_tree(); - int build_loop_tree_impl( Node *n, int pre_order ); + int build_loop_tree_impl(Node* n, int pre_order); // Insert loop into the existing loop tree. 'innermost' is a leaf of the // loop tree, not the root. IdealLoopTree *sort( IdealLoopTree *loop, IdealLoopTree *innermost ); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/opto/parse1.cpp openjdk-17-17.0.15+6/src/hotspot/share/opto/parse1.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/opto/parse1.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/opto/parse1.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1621,7 +1621,7 @@ // The ex_oop must be pushed on the stack, unlike throw_to_exit. void Parse::merge_exception(int target_bci) { #ifdef ASSERT - if (target_bci < bci()) { + if (target_bci <= bci()) { C->set_exception_backedge(); } #endif diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/opto/postaloc.cpp openjdk-17-17.0.15+6/src/hotspot/share/opto/postaloc.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/opto/postaloc.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/opto/postaloc.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -403,7 +403,6 @@ // as they get encountered with the merge node and keep adding these defs to the merge inputs. void PhaseChaitin::merge_multidefs() { Compile::TracePhase tp("mergeMultidefs", &timers[_t_mergeMultidefs]); - ResourceMark rm; // Keep track of the defs seen in registers and collect their uses in the block. RegToDefUseMap reg2defuse(_max_reg, _max_reg, RegDefUse()); for (uint i = 0; i < _cfg.number_of_blocks(); i++) { diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/prims/jni.cpp openjdk-17-17.0.15+6/src/hotspot/share/prims/jni.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/prims/jni.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/prims/jni.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -3527,7 +3527,15 @@ extern const struct JNIInvokeInterface_ jni_InvokeInterface; // Global invocation API vars -volatile int vm_created = 0; +enum VM_Creation_State { + NOT_CREATED = 0, + IN_PROGRESS, // Most JNI operations are permitted during this phase to + // allow for initialization actions by libraries and agents. + COMPLETE +}; + +volatile VM_Creation_State vm_created = NOT_CREATED; + // Indicate whether it is safe to recreate VM. Recreation is only // possible after a failed initial creation attempt in some cases. volatile int safe_to_recreate_vm = 1; @@ -3596,7 +3604,7 @@ // We use Atomic::xchg rather than Atomic::add/dec since on some platforms // the add/dec implementations are dependent on whether we are running // on a multiprocessor Atomic::xchg does not have this problem. - if (Atomic::xchg(&vm_created, 1) == 1) { + if (Atomic::xchg(&vm_created, IN_PROGRESS) != NOT_CREATED) { return JNI_EEXIST; // already created, or create attempt in progress } @@ -3609,8 +3617,6 @@ return JNI_ERR; } - assert(vm_created == 1, "vm_created is true during the creation"); - /** * Certain errors during initialization are recoverable and do not * prevent this method from being called again at a later time @@ -3627,9 +3633,11 @@ if (result == JNI_OK) { JavaThread *thread = JavaThread::current(); assert(!thread->has_pending_exception(), "should have returned not OK"); - /* thread is thread_in_vm here */ + // thread is thread_in_vm here *vm = (JavaVM *)(&main_vm); *(JNIEnv**)penv = thread->jni_environment(); + // mark creation complete for other JNI ops + Atomic::release_store(&vm_created, COMPLETE); #if INCLUDE_JVMCI if (EnableJVMCI) { @@ -3694,7 +3702,8 @@ *(JNIEnv**)penv = 0; // reset vm_created last to avoid race condition. Use OrderAccess to // control both compiler and architectural-based reordering. - Atomic::release_store(&vm_created, 0); + assert(vm_created == IN_PROGRESS, "must be"); + Atomic::release_store(&vm_created, NOT_CREATED); } // Flush stdout and stderr before exit. @@ -3723,7 +3732,7 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_GetCreatedJavaVMs(JavaVM **vm_buf, jsize bufLen, jsize *numVMs) { HOTSPOT_JNI_GETCREATEDJAVAVMS_ENTRY((void **) vm_buf, bufLen, (uintptr_t *) numVMs); - if (vm_created == 1) { + if (vm_created == COMPLETE) { if (numVMs != NULL) *numVMs = 1; if (bufLen > 0) *vm_buf = (JavaVM *)(&main_vm); } else { @@ -3743,7 +3752,7 @@ jint res = JNI_ERR; DT_RETURN_MARK(DestroyJavaVM, jint, (const jint&)res); - if (vm_created == 0) { + if (vm_created == NOT_CREATED) { res = JNI_ERR; return res; } @@ -3767,7 +3776,7 @@ ThreadStateTransition::transition_from_native(thread, _thread_in_vm); Threads::destroy_vm(); // Don't bother restoring thread state, VM is gone. - vm_created = 0; + vm_created = NOT_CREATED; return JNI_OK; } @@ -3904,7 +3913,8 @@ jint JNICALL jni_AttachCurrentThread(JavaVM *vm, void **penv, void *_args) { HOTSPOT_JNI_ATTACHCURRENTTHREAD_ENTRY(vm, penv, _args); - if (vm_created == 0) { + if (vm_created == NOT_CREATED) { + // Not sure how we could possibly get here. HOTSPOT_JNI_ATTACHCURRENTTHREAD_RETURN((uint32_t) JNI_ERR); return JNI_ERR; } @@ -3917,7 +3927,8 @@ jint JNICALL jni_DetachCurrentThread(JavaVM *vm) { HOTSPOT_JNI_DETACHCURRENTTHREAD_ENTRY(vm); - if (vm_created == 0) { + if (vm_created == NOT_CREATED) { + // Not sure how we could possibly get here. HOTSPOT_JNI_DETACHCURRENTTHREAD_RETURN(JNI_ERR); return JNI_ERR; } @@ -3980,7 +3991,7 @@ jint ret = JNI_ERR; DT_RETURN_MARK(GetEnv, jint, (const jint&)ret); - if (vm_created == 0) { + if (vm_created == NOT_CREATED) { *penv = NULL; ret = JNI_EDETACHED; return ret; @@ -4031,8 +4042,9 @@ jint JNICALL jni_AttachCurrentThreadAsDaemon(JavaVM *vm, void **penv, void *_args) { HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_ENTRY(vm, penv, _args); - if (vm_created == 0) { - HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN((uint32_t) JNI_ERR); + if (vm_created == NOT_CREATED) { + // Not sure how we could possibly get here. + HOTSPOT_JNI_ATTACHCURRENTTHREADASDAEMON_RETURN((uint32_t) JNI_ERR); return JNI_ERR; } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/prims/universalUpcallHandler.cpp openjdk-17-17.0.15+6/src/hotspot/share/prims/universalUpcallHandler.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/prims/universalUpcallHandler.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/prims/universalUpcallHandler.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -131,21 +131,17 @@ // restore previous handle block thread->set_active_handles(context->old_handles); - thread->frame_anchor()->zap(); - debug_only(thread->dec_java_call_counter()); + thread->frame_anchor()->copy(&context->jfa); + // Old thread-local info. has been restored. We are now back in native code. ThreadStateTransition::transition_from_java(thread, _thread_in_native); - thread->frame_anchor()->copy(&context->jfa); - // Release handles after we are marked as being in native code again, since this // operation might block JNIHandleBlock::release_block(context->new_handles, thread); - assert(!thread->has_pending_exception(), "Upcall can not throw an exception"); - if (context->should_detach) { detach_current_thread(); } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/deoptimization.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/deoptimization.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/deoptimization.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/deoptimization.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1612,7 +1612,7 @@ ObjectSynchronizer::exit(src->obj(), src->lock(), thread); } } - array->element(i)->free_monitors(thread); + array->element(i)->free_monitors(); #ifdef ASSERT array->element(i)->set_removed_monitors(); #endif diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/handshake.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/handshake.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/handshake.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/handshake.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -245,6 +245,10 @@ number_of_threads_issued++; } + // Separate the arming of the poll in add_operation() above from + // the read of JavaThread state in the try_process() call below. + OrderAccess::fence(); + if (number_of_threads_issued < 1) { log_handshake_info(start_time_ns, _op->name(), 0, 0, "no threads alive"); return; @@ -357,6 +361,10 @@ return; } + // Separate the arming of the poll in add_operation() above from + // the read of JavaThread state in the try_process() call below. + OrderAccess::fence(); + // Keeps count on how many of own emitted handshakes // this thread execute. int emitted_handshakes_executed = 0; @@ -481,6 +489,10 @@ // It by-passes the NSV by manually doing the transition. NoSafepointVerifier nsv; + // Separate all the writes above for other threads reading state + // set by this thread in case the operation is ThreadSuspendHandshake. + OrderAccess::fence(); + while (has_operation()) { MutexLocker ml(&_lock, Mutex::_no_safepoint_check_flag); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/monitorChunk.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/monitorChunk.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ MonitorChunk::MonitorChunk(int number_on_monitors) { _number_of_monitors = number_on_monitors; _monitors = NEW_C_HEAP_ARRAY(BasicObjectLock, number_on_monitors, mtSynchronizer); - _next = NULL; } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/monitorChunk.hpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/monitorChunk.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/monitorChunk.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,26 +35,17 @@ int _number_of_monitors; BasicObjectLock* _monitors; BasicObjectLock* monitors() const { return _monitors; } - MonitorChunk* _next; public: // Constructor MonitorChunk(int number_on_monitors); ~MonitorChunk(); - // link operations - MonitorChunk* next() const { return _next; } - void set_next(MonitorChunk* next) { _next = next; } - - // Tells whether the monitor chunk is linked into the JavaThread - bool is_linked() const { return next() != NULL; } - // Returns the number of monitors int number_of_monitors() const { return _number_of_monitors; } // Returns the index'th monitor BasicObjectLock* at(int index) { assert(index >= 0 && index < number_of_monitors(), "out of bounds check"); return &monitors()[index]; } - // Memory management void oops_do(OopClosure* f); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/synchronizer.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/synchronizer.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/synchronizer.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/synchronizer.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -961,7 +961,8 @@ } // Fall thru so we only have one place that installs the hash in // the ObjectMonitor. - } else if (current->is_lock_owned((address)mark.locker())) { + } else if (current->is_Java_thread() + && current->as_Java_thread()->is_lock_owned((address)mark.locker())) { // This is a stack lock owned by the calling thread so fetch the // displaced markWord from the BasicLock on the stack. temp = mark.displaced_mark_helper(); diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/thread.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/thread.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -699,15 +699,6 @@ } #endif // ASSERT -// We had to move these methods here, because vm threads get into ObjectSynchronizer::enter -// However, there is a note in JavaThread::is_lock_owned() about the VM threads not being -// used for compilation in the future. If that change is made, the need for these methods -// should be revisited, and they should be removed if possible. - -bool Thread::is_lock_owned(address adr) const { - return is_in_full_stack(adr); -} - bool Thread::set_as_starting_thread() { assert(_starting_thread == NULL, "already initialized: " "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread)); @@ -1035,8 +1026,6 @@ _current_waiting_monitor(NULL), _Stalled(0), - _monitor_chunks(nullptr), - _suspend_flags(0), _async_exception_condition(_no_async_condition), _pending_async_exception(nullptr), @@ -1573,13 +1562,7 @@ } bool JavaThread::is_lock_owned(address adr) const { - if (Thread::is_lock_owned(adr)) return true; - - for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { - if (chunk->contains(adr)) return true; - } - - return false; + return is_in_full_stack(adr); } oop JavaThread::exception_oop() const { @@ -1590,23 +1573,6 @@ Atomic::store(&_exception_oop, o); } -void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { - chunk->set_next(monitor_chunks()); - set_monitor_chunks(chunk); -} - -void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { - guarantee(monitor_chunks() != NULL, "must be non empty"); - if (monitor_chunks() == chunk) { - set_monitor_chunks(chunk->next()); - } else { - MonitorChunk* prev = monitor_chunks(); - while (prev->next() != chunk) prev = prev->next(); - prev->set_next(chunk->next()); - } -} - - // Asynchronous exceptions support // // Note: this function shouldn't block if it's called in @@ -1994,13 +1960,6 @@ DEBUG_ONLY(verify_frame_info();) - if (has_last_Java_frame()) { - // Traverse the monitor chunks - for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { - chunk->oops_do(f); - } - } - assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); // If we have deferred set_locals there might be oops waiting to be // written diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/thread.hpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/thread.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/thread.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -497,9 +497,6 @@ } public: - // Used by fast lock support - virtual bool is_lock_owned(address adr) const; - // Check if address is within the given range of this thread's // stack: stack_base() > adr >= limit bool is_in_stack_range_incl(address adr, address limit) const { @@ -803,10 +800,6 @@ } private: - MonitorChunk* _monitor_chunks; // Contains the off stack monitors - // allocated during deoptimization - // and by JNI_MonitorEnter/Exit - enum SuspendFlags { // NOTE: avoid using the sign-bit as cc generates different test code // when the sign-bit is used, and sometimes incorrectly - see CR 6398077 @@ -1211,7 +1204,7 @@ (_suspend_flags & (_obj_deopt JFR_ONLY(| _trace_flag))) != 0; } - // Fast-locking support + // Stack-locking support bool is_lock_owned(address adr) const; // Accessors for vframe array top @@ -1388,13 +1381,7 @@ int depth_first_number() { return _depth_first_number; } void set_depth_first_number(int dfn) { _depth_first_number = dfn; } - private: - void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; } - public: - MonitorChunk* monitor_chunks() const { return _monitor_chunks; } - void add_monitor_chunk(MonitorChunk* chunk); - void remove_monitor_chunk(MonitorChunk* chunk); bool in_deopt_handler() const { return _in_deopt_handler > 0; } void inc_in_deopt_handler() { _in_deopt_handler++; } void dec_in_deopt_handler() { diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/vframeArray.cpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/vframeArray.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ #include "runtime/handles.inline.hpp" #include "runtime/monitorChunk.hpp" #include "runtime/sharedRuntime.hpp" +#include "runtime/synchronizer.hpp" #include "runtime/vframe.hpp" #include "runtime/vframeArray.hpp" #include "runtime/vframe_hp.hpp" @@ -48,11 +49,10 @@ int vframeArrayElement:: bci(void) const { return (_bci == SynchronizationEntryBCI ? 0 : _bci); } -void vframeArrayElement::free_monitors(JavaThread* jt) { +void vframeArrayElement::free_monitors() { if (_monitors != NULL) { MonitorChunk* chunk = _monitors; _monitors = NULL; - jt->remove_monitor_chunk(chunk); delete chunk; } } @@ -72,7 +72,7 @@ int index; { - Thread* current_thread = Thread::current(); + JavaThread* current_thread = JavaThread::current(); ResourceMark rm(current_thread); HandleMark hm(current_thread); @@ -85,7 +85,6 @@ // Allocate monitor chunk _monitors = new MonitorChunk(list->length()); - vf->thread()->add_monitor_chunk(_monitors); // Migrate the BasicLocks from the stack to the monitor chunk for (index = 0; index < list->length(); index++) { @@ -95,9 +94,16 @@ if (monitor->owner_is_scalar_replaced()) { dest->set_obj(NULL); } else { - assert(monitor->owner() == NULL || (!monitor->owner()->is_unlocked() && !monitor->owner()->has_bias_pattern()), "object must be null or locked, and unbiased"); + assert(monitor->owner() != nullptr, "monitor owner must not be null"); + assert(!monitor->owner()->is_unlocked() && !monitor->owner()->has_bias_pattern(), "object must be locked, and unbiased"); dest->set_obj(monitor->owner()); + assert(ObjectSynchronizer::current_thread_holds_lock(current_thread, Handle(current_thread, dest->obj())), + "should be held, before move_to"); + monitor->lock()->move_to(monitor->owner(), dest->lock()); + + assert(ObjectSynchronizer::current_thread_holds_lock(current_thread, Handle(current_thread, dest->obj())), + "should be held, after move_to"); } } } @@ -308,7 +314,11 @@ top = iframe()->previous_monitor_in_interpreter_frame(top); BasicObjectLock* src = _monitors->at(index); top->set_obj(src->obj()); + assert(src->obj() != nullptr || ObjectSynchronizer::current_thread_holds_lock(thread, Handle(thread, src->obj())), + "should be held, before move_to"); src->lock()->move_to(src->obj(), top->lock()); + assert(src->obj() != nullptr || ObjectSynchronizer::current_thread_holds_lock(thread, Handle(thread, src->obj())), + "should be held, after move_to"); } if (ProfileInterpreter) { iframe()->interpreter_frame_set_mdp(0); // clear out the mdp. @@ -615,9 +625,8 @@ } void vframeArray::deallocate_monitor_chunks() { - JavaThread* jt = JavaThread::current(); for (int index = 0; index < frames(); index++ ) { - element(index)->free_monitors(jt); + element(index)->free_monitors(); } } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/runtime/vframeArray.hpp openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/runtime/vframeArray.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/runtime/vframeArray.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -77,7 +77,7 @@ MonitorChunk* monitors(void) const { return _monitors; } - void free_monitors(JavaThread* jt); + void free_monitors(); StackValueCollection* locals(void) const { return _locals; } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/utilities/debug.cpp openjdk-17-17.0.15+6/src/hotspot/share/utilities/debug.cpp --- openjdk-17-17.0.14+7/src/hotspot/share/utilities/debug.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/utilities/debug.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -743,10 +743,22 @@ static void store_context(const void* context) { memcpy(&g_stored_assertion_context, context, sizeof(ucontext_t)); -#if defined(LINUX) && defined(PPC64) +#if defined(LINUX) // on Linux ppc64, ucontext_t contains pointers into itself which have to be patched up // after copying the context (see comment in sys/ucontext.h): +#if defined(PPC64) *((void**) &g_stored_assertion_context.uc_mcontext.regs) = &(g_stored_assertion_context.uc_mcontext.gp_regs); +#elif defined(AMD64) + // In the copied version, fpregs should point to the copied contents. + // Sanity check: fpregs should point into the context. + if ((address)((const ucontext_t*)context)->uc_mcontext.fpregs > (address)context) { + size_t fpregs_offset = pointer_delta(((const ucontext_t*)context)->uc_mcontext.fpregs, context, 1); + if (fpregs_offset < sizeof(ucontext_t)) { + // Preserve the offset. + *((void**) &g_stored_assertion_context.uc_mcontext.fpregs) = (void*)((address)(void*)&g_stored_assertion_context + fpregs_offset); + } + } +#endif #endif } diff -Nru openjdk-17-17.0.14+7/src/hotspot/share/utilities/globalDefinitions.hpp openjdk-17-17.0.15+6/src/hotspot/share/utilities/globalDefinitions.hpp --- openjdk-17-17.0.14+7/src/hotspot/share/utilities/globalDefinitions.hpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/hotspot/share/utilities/globalDefinitions.hpp 2025-04-09 19:45:33.000000000 +0000 @@ -94,10 +94,12 @@ #define BOOL_TO_STR(_b_) ((_b_) ? "true" : "false") // Format 32-bit quantities. -#define INT32_FORMAT "%" PRId32 -#define UINT32_FORMAT "%" PRIu32 -#define INT32_FORMAT_W(width) "%" #width PRId32 -#define UINT32_FORMAT_W(width) "%" #width PRIu32 +#define INT32_FORMAT "%" PRId32 +#define INT32_FORMAT_X_0 "0x%08" PRIx32 +#define INT32_FORMAT_W(width) "%" #width PRId32 +#define UINT32_FORMAT "%" PRIu32 +#define UINT32_FORMAT_X_0 "0x%08" PRIx32 +#define UINT32_FORMAT_W(width) "%" #width PRIu32 #define PTR32_FORMAT "0x%08" PRIx32 #define PTR32_FORMAT_W(width) "0x%" #width PRIx32 diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/DHPrivateKey.java openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPrivateKey.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/DHPrivateKey.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPrivateKey.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -57,6 +57,7 @@ private BigInteger x; // the key bytes, without the algorithm information + // cannot be final as it's re-assigned for deserialization private byte[] key; // the encoded key @@ -71,6 +72,135 @@ // the private-value length (optional) private int l; + private static class DHComponents { + final BigInteger x; + final BigInteger p; + final BigInteger g; + final int l; + final byte[] key; + + DHComponents(BigInteger x, BigInteger p, BigInteger g, int l, + byte[] key) { + this.x = x; + this.p = p; + this.g = g; + this.l = l; + this.key = key; + } + } + + // parses the specified encoding into a DHComponents object + private static DHComponents decode(byte[] encodedKey) + throws IOException { + DerValue val = null; + + try { + val = new DerValue(encodedKey); + if (val.tag != DerValue.tag_Sequence) { + throw new IOException("Key not a SEQUENCE"); + } + + // version + BigInteger parsedVersion = val.data.getBigInteger(); + if (!parsedVersion.equals(PKCS8_VERSION)) { + throw new IOException("version mismatch: (supported: " + + PKCS8_VERSION + ", parsed: " + parsedVersion); + } + + // privateKeyAlgorithm + DerValue algid = val.data.getDerValue(); + if (algid.tag != DerValue.tag_Sequence) { + throw new IOException("AlgId is not a SEQUENCE"); + } + DerInputStream derInStream = algid.toDerInputStream(); + ObjectIdentifier oid = derInStream.getOID(); + if (oid == null) { + throw new IOException("Null OID"); + } + if (derInStream.available() == 0) { + throw new IOException("Parameters missing"); + } + // parse the parameters + DerValue params = derInStream.getDerValue(); + if (params.tag == DerValue.tag_Null) { + throw new IOException("Null parameters"); + } + if (params.tag != DerValue.tag_Sequence) { + throw new IOException("Parameters not a SEQUENCE"); + } + params.data.reset(); + BigInteger p = params.data.getBigInteger(); + BigInteger g = params.data.getBigInteger(); + // Private-value length is OPTIONAL + int l = (params.data.available() != 0 ? + params.data.getInteger() : 0); + // should have no trailing data + if (params.data.available() != 0) { + throw new IOException("Extra parameter data"); + } + + // privateKey + byte[] key = val.data.getOctetString(); + DerInputStream in = new DerInputStream(key); + BigInteger x = in.getBigInteger(); + + // should have no trailing data + if (val.data.available() != 0) { + throw new IOException("Excess trailing data"); + } + return new DHComponents(x, p, g, l, key); + } catch (NumberFormatException e) { + throw new IOException("Error parsing key encoding", e); + } finally { + if (val != null) { + val.clear(); + } + } + } + + // Generates the ASN.1 encoding + private static byte[] encode(BigInteger p, BigInteger g, int l, + byte[] key) { + try { + DerOutputStream tmp = new DerOutputStream(); + + // version + tmp.putInteger(PKCS8_VERSION); + + // privateKeyAlgorithm + DerOutputStream algid = new DerOutputStream(); + + // store OID + algid.putOID(DHPublicKey.DH_OID); + // encode parameters + DerOutputStream params = new DerOutputStream(); + params.putInteger(p); + params.putInteger(g); + if (l != 0) { + params.putInteger(l); + } + // wrap parameters into SEQUENCE + DerValue paramSequence = new DerValue(DerValue.tag_Sequence, + params.toByteArray()); + // store parameter SEQUENCE in algid + algid.putDerValue(paramSequence); + // wrap algid into SEQUENCE + tmp.write(DerValue.tag_Sequence, algid); + + // privateKey + tmp.putOctetString(key); + + // make it a SEQUENCE + DerValue val = DerValue.wrap(DerValue.tag_Sequence, tmp); + byte[] encoded = val.toByteArray(); + val.clear(); + + return encoded; + } catch (IOException e) { + throw new AssertionError(e); + } + } + /** * Make a DH private key out of a private value x, a prime * modulus p, and a base generator g. @@ -82,7 +212,7 @@ * @throws ProviderException if the key cannot be encoded */ DHPrivateKey(BigInteger x, BigInteger p, BigInteger g) - throws InvalidKeyException { + throws InvalidKeyException { this(x, p, g, 0); } @@ -103,16 +233,18 @@ this.p = p; this.g = g; this.l = l; + + byte[] xbytes = x.toByteArray(); + DerValue val = new DerValue(DerValue.tag_Integer, xbytes); try { - byte[] xbytes = x.toByteArray(); - DerValue val = new DerValue(DerValue.tag_Integer, xbytes); this.key = val.toByteArray(); - val.clear(); - Arrays.fill(xbytes, (byte)0); - encode(); } catch (IOException e) { throw new ProviderException("Cannot produce ASN.1 encoding", e); + } finally { + val.clear(); + Arrays.fill(xbytes, (byte) 0); } + this.encodedKey = encode(p, g, l, key); } /** @@ -124,71 +256,18 @@ * a Diffie-Hellman private key */ DHPrivateKey(byte[] encodedKey) throws InvalidKeyException { - DerValue val = null; + this.encodedKey = encodedKey.clone(); + DHComponents dc; try { - val = new DerValue(encodedKey); - if (val.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException ("Key not a SEQUENCE"); - } - - // - // version - // - BigInteger parsedVersion = val.data.getBigInteger(); - if (!parsedVersion.equals(PKCS8_VERSION)) { - throw new IOException("version mismatch: (supported: " + - PKCS8_VERSION + ", parsed: " + - parsedVersion); - } - - // - // privateKeyAlgorithm - // - DerValue algid = val.data.getDerValue(); - if (algid.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException("AlgId is not a SEQUENCE"); - } - DerInputStream derInStream = algid.toDerInputStream(); - ObjectIdentifier oid = derInStream.getOID(); - if (oid == null) { - throw new InvalidKeyException("Null OID"); - } - if (derInStream.available() == 0) { - throw new InvalidKeyException("Parameters missing"); - } - // parse the parameters - DerValue params = derInStream.getDerValue(); - if (params.tag == DerValue.tag_Null) { - throw new InvalidKeyException("Null parameters"); - } - if (params.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException("Parameters not a SEQUENCE"); - } - params.data.reset(); - this.p = params.data.getBigInteger(); - this.g = params.data.getBigInteger(); - // Private-value length is OPTIONAL - if (params.data.available() != 0) { - this.l = params.data.getInteger(); - } - if (params.data.available() != 0) { - throw new InvalidKeyException("Extra parameter data"); - } - - // - // privateKey - // - this.key = val.data.getOctetString(); - parseKeyBits(); - - this.encodedKey = encodedKey.clone(); - } catch (IOException | NumberFormatException e) { - throw new InvalidKeyException("Error parsing key encoding", e); - } finally { - if (val != null) { - val.clear(); - } + dc = decode(this.encodedKey); + } catch (IOException e) { + throw new InvalidKeyException("Invalid encoding", e); } + this.x = dc.x; + this.p = dc.p; + this.g = dc.g; + this.l = dc.l; + this.key = dc.key; } /** @@ -209,60 +288,10 @@ * Get the encoding of the key. */ public synchronized byte[] getEncoded() { - encode(); return encodedKey.clone(); } /** - * Generate the encodedKey field if it has not been calculated. - * Could generate null. - */ - private void encode() { - if (this.encodedKey == null) { - try { - DerOutputStream tmp = new DerOutputStream(); - - // - // version - // - tmp.putInteger(PKCS8_VERSION); - - // - // privateKeyAlgorithm - // - DerOutputStream algid = new DerOutputStream(); - - // store OID - algid.putOID(DHPublicKey.DH_OID); - // encode parameters - DerOutputStream params = new DerOutputStream(); - params.putInteger(this.p); - params.putInteger(this.g); - if (this.l != 0) { - params.putInteger(this.l); - } - // wrap parameters into SEQUENCE - DerValue paramSequence = new DerValue(DerValue.tag_Sequence, - params.toByteArray()); - // store parameter SEQUENCE in algid - algid.putDerValue(paramSequence); - // wrap algid into SEQUENCE - tmp.write(DerValue.tag_Sequence, algid); - - // privateKey - tmp.putOctetString(this.key); - - // make it a SEQUENCE - DerValue val = DerValue.wrap(DerValue.tag_Sequence, tmp); - this.encodedKey = val.toByteArray(); - val.clear(); - } catch (IOException e) { - throw new AssertionError(e); - } - } - } - - /** * Returns the private value, x. * * @return the private value, x @@ -284,18 +313,6 @@ } } - private void parseKeyBits() throws InvalidKeyException { - try { - DerInputStream in = new DerInputStream(this.key); - this.x = in.getBigInteger(); - } catch (IOException e) { - InvalidKeyException ike = new InvalidKeyException( - "Error parsing key encoding: " + e.getMessage()); - ike.initCause(e); - throw ike; - } - } - /** * Calculates a hash code value for the object. * Objects that are equal will also have the same hashcode. @@ -328,10 +345,7 @@ */ @java.io.Serial private Object writeReplace() throws java.io.ObjectStreamException { - encode(); - return new KeyRep(KeyRep.Type.PRIVATE, - getAlgorithm(), - getFormat(), + return new KeyRep(KeyRep.Type.PRIVATE, getAlgorithm(), getFormat(), encodedKey); } @@ -351,11 +365,30 @@ if ((key == null) || (key.length == 0)) { throw new InvalidObjectException("key not deserializable"); } - this.key = key.clone(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidObjectException( "encoded key not deserializable"); } - this.encodedKey = encodedKey.clone(); + // check if the "encodedKey" value matches the deserialized fields + DHComponents c; + byte[] encodedKeyIntern = encodedKey.clone(); + try { + c = decode(encodedKeyIntern); + } catch (IOException e) { + InvalidObjectException ioe = new InvalidObjectException("Invalid encoding"); + ioe.initCause(e); + throw ioe; + } + if (!Arrays.equals(c.key, key) || !c.x.equals(x) || !c.p.equals(p) + || !c.g.equals(g) || c.l != l) { + throw new InvalidObjectException( + "encoded key not matching internal fields"); + } + // zero out external arrays + Arrays.fill(key, (byte)0x00); + Arrays.fill(encodedKey, (byte)0x00); + // use self-created internal copies + this.key = c.key; + this.encodedKey = encodedKeyIntern; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/DHPublicKey.java openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPublicKey.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/DHPublicKey.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/DHPublicKey.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package com.sun.crypto.provider; import java.io.*; +import java.util.Arrays; import java.util.Objects; import java.math.BigInteger; import java.security.KeyRep; @@ -71,6 +72,116 @@ static ObjectIdentifier DH_OID = ObjectIdentifier.of(KnownOIDs.DiffieHellman); + private static class DHComponents { + final BigInteger y; + final BigInteger p; + final BigInteger g; + final int l; + final byte[] key; + + DHComponents(BigInteger y, BigInteger p, BigInteger g, int l, + byte[] key) { + this.y = y; + this.p = p; + this.g = g; + this.l = l; + this.key = key; + } + } + + // parses the specified encoding into a DHComponents object + private static DHComponents decode(byte[] encodedKey) + throws IOException { + DerValue val = null; + + try { + val = new DerValue(encodedKey); + if (val.tag != DerValue.tag_Sequence) { + throw new IOException("Invalid key format"); + } + + // algorithm identifier + DerValue algid = val.data.getDerValue(); + if (algid.tag != DerValue.tag_Sequence) { + throw new IOException("AlgId is not a SEQUENCE"); + } + DerInputStream derInStream = algid.toDerInputStream(); + ObjectIdentifier oid = derInStream.getOID(); + if (oid == null) { + throw new IOException("Null OID"); + } + if (derInStream.available() == 0) { + throw new IOException("Parameters missing"); + } + + // parse the parameters + DerValue params = derInStream.getDerValue(); + if (params.tag == DerValue.tag_Null) { + throw new IOException("Null parameters"); + } + if (params.tag != DerValue.tag_Sequence) { + throw new IOException("Parameters not a SEQUENCE"); + } + params.data.reset(); + + BigInteger p = params.data.getBigInteger(); + BigInteger g = params.data.getBigInteger(); + // Private-value length is OPTIONAL + int l = (params.data.available() != 0 ? params.data.getInteger() : + 0); + if (params.data.available() != 0) { + throw new IOException("Extra parameter data"); + } + + // publickey + byte[] key = val.data.getBitString(); + DerInputStream in = new DerInputStream(key); + BigInteger y = in.getBigInteger(); + + if (val.data.available() != 0) { + throw new IOException("Excess key data"); + } + return new DHComponents(y, p, g, l, key); + } catch (NumberFormatException e) { + throw new IOException("Error parsing key encoding", e); + } + } + + // generates the ASN.1 encoding + private static byte[] encode(BigInteger p, BigInteger g, int l, + byte[] key) throws IOException { + DerOutputStream algid = new DerOutputStream(); + + // store oid in algid + algid.putOID(DH_OID); + + // encode parameters + DerOutputStream params = new DerOutputStream(); + params.putInteger(p); + params.putInteger(g); + if (l != 0) { + params.putInteger(l); + } + + // wrap parameters into SEQUENCE + DerValue paramSequence = new DerValue(DerValue.tag_Sequence, + params.toByteArray()); + // store parameter SEQUENCE in algid + algid.putDerValue(paramSequence); + + // wrap algid into SEQUENCE, and store it in key encoding + DerOutputStream tmpDerKey = new DerOutputStream(); + tmpDerKey.write(DerValue.tag_Sequence, algid); + + // store key data + tmpDerKey.putBitString(key); + + // wrap algid and key into SEQUENCE + DerOutputStream derKey = new DerOutputStream(); + derKey.write(DerValue.tag_Sequence, tmpDerKey); + return derKey.toByteArray(); + } + /** * Make a DH public key out of a public value y, a prime * modulus p, and a base generator g. @@ -106,7 +217,7 @@ try { this.key = new DerValue(DerValue.tag_Integer, this.y.toByteArray()).toByteArray(); - this.encodedKey = getEncoded(); + this.encodedKey = encode(p, g, l, key); } catch (IOException e) { throw new ProviderException("Cannot produce ASN.1 encoding", e); } @@ -121,63 +232,19 @@ * a Diffie-Hellman public key */ DHPublicKey(byte[] encodedKey) throws InvalidKeyException { - InputStream inStream = new ByteArrayInputStream(encodedKey); - try { - DerValue derKeyVal = new DerValue(inStream); - if (derKeyVal.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException ("Invalid key format"); - } - - /* - * Parse the algorithm identifier - */ - DerValue algid = derKeyVal.data.getDerValue(); - if (algid.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException("AlgId is not a SEQUENCE"); - } - DerInputStream derInStream = algid.toDerInputStream(); - ObjectIdentifier oid = derInStream.getOID(); - if (oid == null) { - throw new InvalidKeyException("Null OID"); - } - if (derInStream.available() == 0) { - throw new InvalidKeyException("Parameters missing"); - } - - /* - * Parse the parameters - */ - DerValue params = derInStream.getDerValue(); - if (params.tag == DerValue.tag_Null) { - throw new InvalidKeyException("Null parameters"); - } - if (params.tag != DerValue.tag_Sequence) { - throw new InvalidKeyException("Parameters not a SEQUENCE"); - } - params.data.reset(); - this.p = params.data.getBigInteger(); - this.g = params.data.getBigInteger(); - // Private-value length is OPTIONAL - if (params.data.available() != 0) { - this.l = params.data.getInteger(); - } - if (params.data.available() != 0) { - throw new InvalidKeyException("Extra parameter data"); - } - - /* - * Parse the key - */ - this.key = derKeyVal.data.getBitString(); - parseKeyBits(); - if (derKeyVal.data.available() != 0) { - throw new InvalidKeyException("Excess key data"); - } + this.encodedKey = encodedKey.clone(); - this.encodedKey = encodedKey.clone(); - } catch (IOException | NumberFormatException e) { - throw new InvalidKeyException("Error parsing key encoding", e); + DHComponents dc; + try { + dc = decode(this.encodedKey); + } catch (IOException e) { + throw new InvalidKeyException("Invalid encoding", e); } + this.y = dc.y; + this.p = dc.p; + this.g = dc.g; + this.l = dc.l; + this.key = dc.key; } /** @@ -198,41 +265,6 @@ * Get the encoding of the key. */ public synchronized byte[] getEncoded() { - if (this.encodedKey == null) { - try { - DerOutputStream algid = new DerOutputStream(); - - // store oid in algid - algid.putOID(DH_OID); - - // encode parameters - DerOutputStream params = new DerOutputStream(); - params.putInteger(this.p); - params.putInteger(this.g); - if (this.l != 0) { - params.putInteger(this.l); - } - // wrap parameters into SEQUENCE - DerValue paramSequence = new DerValue(DerValue.tag_Sequence, - params.toByteArray()); - // store parameter SEQUENCE in algid - algid.putDerValue(paramSequence); - - // wrap algid into SEQUENCE, and store it in key encoding - DerOutputStream tmpDerKey = new DerOutputStream(); - tmpDerKey.write(DerValue.tag_Sequence, algid); - - // store key data - tmpDerKey.putBitString(this.key); - - // wrap algid and key into SEQUENCE - DerOutputStream derKey = new DerOutputStream(); - derKey.write(DerValue.tag_Sequence, tmpDerKey); - this.encodedKey = derKey.toByteArray(); - } catch (IOException e) { - return null; - } - } return this.encodedKey.clone(); } @@ -269,19 +301,10 @@ + Debug.toHexString(this.p) + LINE_SEP + "g:" + LINE_SEP + Debug.toHexString(this.g)); - if (this.l != 0) + if (this.l != 0) { sb.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l); - return sb.toString(); - } - - private void parseKeyBits() throws InvalidKeyException { - try { - DerInputStream in = new DerInputStream(this.key); - this.y = in.getBigInteger(); - } catch (IOException e) { - throw new InvalidKeyException( - "Error parsing key encoding: " + e.toString()); } + return sb.toString(); } /** @@ -320,7 +343,7 @@ return new KeyRep(KeyRep.Type.PUBLIC, getAlgorithm(), getFormat(), - getEncoded()); + encodedKey); } /** @@ -339,11 +362,30 @@ if ((key == null) || (key.length == 0)) { throw new InvalidObjectException("key not deserializable"); } - this.key = key.clone(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidObjectException( "encoded key not deserializable"); } - this.encodedKey = encodedKey.clone(); + // check if the "encodedKey" value matches the deserialized fields + DHComponents c; + byte[] encodedKeyIntern = encodedKey.clone(); + try { + c = decode(encodedKeyIntern); + } catch (IOException e) { + InvalidObjectException ioe = new InvalidObjectException("Invalid encoding"); + ioe.initCause(e); + throw ioe; + } + if (!Arrays.equals(c.key, key) || !c.y.equals(y) || !c.p.equals(p) + || !c.g.equals(g) || c.l != l) { + throw new InvalidObjectException( + "encoded key not matching internal fields"); + } + // zero out external arrays + Arrays.fill(key, (byte)0x00); + Arrays.fill(encodedKey, (byte)0x00); + // use self-created internal copies + this.key = c.key; + this.encodedKey = encodedKeyIntern; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/RSACipher.java 2025-04-09 19:45:33.000000000 +0000 @@ -385,7 +385,7 @@ byte[] decryptBuffer = RSACore.convert(buffer, 0, bufOfs); paddingCopy = RSACore.rsa(decryptBuffer, privateKey, false); result = padding.unpad(paddingCopy); - if (result == null && !forTlsPremasterSecret) { + if (!forTlsPremasterSecret && result == null) { throw new BadPaddingException ("Padding error in decryption"); } @@ -405,6 +405,34 @@ } } + // TLS master secret decode version of the doFinal() method. + private byte[] doFinalForTls(int clientVersion, int serverVersion) + throws BadPaddingException, IllegalBlockSizeException { + if (bufOfs > buffer.length) { + throw new IllegalBlockSizeException("Data must not be longer " + + "than " + buffer.length + " bytes"); + } + byte[] paddingCopy = null; + byte[] result = null; + try { + byte[] decryptBuffer = RSACore.convert(buffer, 0, bufOfs); + + paddingCopy = RSACore.rsa(decryptBuffer, privateKey, false); + result = padding.unpadForTls(paddingCopy, clientVersion, + serverVersion); + + return result; + } finally { + Arrays.fill(buffer, 0, bufOfs, (byte)0); + bufOfs = 0; + if (paddingCopy != null + && paddingCopy != buffer // already cleaned + && paddingCopy != result) { // DO NOT CLEAN, THIS IS RESULT + Arrays.fill(paddingCopy, (byte)0); + } + } + } + // see JCE spec protected byte[] engineUpdate(byte[] in, int inOfs, int inLen) { update(in, inOfs, inLen); @@ -478,37 +506,33 @@ update(wrappedKey, 0, wrappedKey.length); try { - encoded = doFinal(); - } catch (BadPaddingException | IllegalBlockSizeException e) { - // BadPaddingException cannot happen for TLS RSA unwrap. - // In that case, padding error is indicated by returning null. - // IllegalBlockSizeException cannot happen in any case, - // because of the length check above. - throw new InvalidKeyException("Unwrapping failed", e); - } - - try { if (isTlsRsaPremasterSecret) { if (!forTlsPremasterSecret) { throw new IllegalStateException( "No TlsRsaPremasterSecretParameterSpec specified"); } - - // polish the TLS premaster secret - encoded = KeyUtil.checkTlsPreMasterSecretKey( - ((TlsRsaPremasterSecretParameterSpec) spec).getClientVersion(), - ((TlsRsaPremasterSecretParameterSpec) spec).getServerVersion(), - random, encoded, encoded == null); + TlsRsaPremasterSecretParameterSpec parameterSpec = + (TlsRsaPremasterSecretParameterSpec) spec; + encoded = doFinalForTls(parameterSpec.getClientVersion(), + parameterSpec.getServerVersion()); + } else { + encoded = doFinal(); } - return ConstructKeys.constructKey(encoded, algorithm, type); + + } catch (BadPaddingException | IllegalBlockSizeException e) { + // BadPaddingException cannot happen for TLS RSA unwrap. + // Neither padding error nor server version error is indicated + // for TLS, but a fake unwrapped value is returned. + // IllegalBlockSizeException cannot happen in any case, + // because of the length check above. + throw new InvalidKeyException("Unwrapping failed", e); } finally { if (encoded != null) { Arrays.fill(encoded, (byte) 0); } } } - // see JCE spec protected int engineGetKeySize(Key key) throws InvalidKeyException { RSAKey rsaKey = RSAKeyFactory.toRSAKey(key); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/com/sun/crypto/provider/TlsMasterSecretGenerator.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -196,22 +196,24 @@ return key.clone(); } - /** - * Restores the state of this object from the stream. - * - * @param stream the {@code ObjectInputStream} from which data is read - * @throws IOException if an I/O error occurs - * @throws ClassNotFoundException if a serialized class cannot be loaded - */ - @java.io.Serial - private void readObject(ObjectInputStream stream) - throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - if ((key == null) || (key.length == 0)) { - throw new InvalidObjectException("TlsMasterSecretKey is null"); - } - key = key.clone(); - } - } + /** + * Restores the state of this object from the stream. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) + throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + if (key == null || key.length == 0) { + throw new InvalidObjectException("TlsMasterSecretKey is null"); + } + byte[] temp = key; + this.key = temp.clone(); + Arrays.fill(temp, (byte)0); + } + } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/Permissions.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Permissions.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/Permissions.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Permissions.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -403,6 +403,11 @@ @SuppressWarnings("unchecked") Hashtable, PermissionCollection> perms = (Hashtable, PermissionCollection>)gfields.get("perms", null); + + if (perms == null) { + throw new InvalidObjectException("perms can't be null"); + } + permsMap = new ConcurrentHashMap<>(perms.size()*2); permsMap.putAll(perms); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/SignedObject.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/SignedObject.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/SignedObject.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/SignedObject.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -152,20 +152,20 @@ */ public SignedObject(Serializable object, PrivateKey signingKey, Signature signingEngine) - throws IOException, InvalidKeyException, SignatureException { - // creating a stream pipe-line, from a to b - ByteArrayOutputStream b = new ByteArrayOutputStream(); - ObjectOutput a = new ObjectOutputStream(b); - - // write and flush the object content to byte array - a.writeObject(object); - a.flush(); - a.close(); - this.content = b.toByteArray(); - b.close(); + throws IOException, InvalidKeyException, SignatureException { + // creating a stream pipe-line, from a to b + ByteArrayOutputStream b = new ByteArrayOutputStream(); + ObjectOutput a = new ObjectOutputStream(b); + + // write and flush the object content to byte array + a.writeObject(object); + a.flush(); + a.close(); + this.content = b.toByteArray(); + b.close(); - // now sign the encapsulated object - this.sign(signingKey, signingEngine); + // now sign the encapsulated object + this.sign(signingKey, signingEngine); } /** @@ -245,12 +245,12 @@ * @throws SignatureException if signing fails. */ private void sign(PrivateKey signingKey, Signature signingEngine) - throws InvalidKeyException, SignatureException { - // initialize the signing engine - signingEngine.initSign(signingKey); - signingEngine.update(this.content.clone()); - this.signature = signingEngine.sign().clone(); - this.thealgorithm = signingEngine.getAlgorithm(); + throws InvalidKeyException, SignatureException { + // initialize the signing engine + signingEngine.initSign(signingKey); + signingEngine.update(this.content.clone()); + this.signature = signingEngine.sign(); + this.thealgorithm = signingEngine.getAlgorithm(); } /** @@ -263,10 +263,16 @@ */ @Serial private void readObject(ObjectInputStream s) - throws IOException, ClassNotFoundException { - ObjectInputStream.GetField fields = s.readFields(); - content = ((byte[])fields.get("content", null)).clone(); - signature = ((byte[])fields.get("signature", null)).clone(); - thealgorithm = (String)fields.get("thealgorithm", null); + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField fields = s.readFields(); + byte[] c = (byte[]) fields.get("content", null); + byte[] sig = (byte[]) fields.get("signature", null); + String a = (String) fields.get("thealgorithm", null); + if (c == null || sig == null || a == null) { + throw new InvalidObjectException("One or more null fields"); + } + content = c.clone(); + signature = sig.clone(); + thealgorithm = a; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/Timestamp.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Timestamp.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/Timestamp.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/Timestamp.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,7 +74,7 @@ * @throws NullPointerException if timestamp or signerCertPath is null. */ public Timestamp(Date timestamp, CertPath signerCertPath) { - if (timestamp == null || signerCertPath == null) { + if (isNull(timestamp, signerCertPath)) { throw new NullPointerException(); } this.timestamp = new Date(timestamp.getTime()); // clone @@ -161,9 +161,16 @@ */ @java.io.Serial private void readObject(ObjectInputStream ois) - throws IOException, ClassNotFoundException { + throws IOException, ClassNotFoundException { ois.defaultReadObject(); + if (isNull(timestamp, signerCertPath)) { + throw new InvalidObjectException("Invalid null field(s)"); + } myhash = -1; timestamp = new Date(timestamp.getTime()); } + + private static boolean isNull(Date d, CertPath c) { + return (d == null || c == null); + } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/UnresolvedPermissionCollection.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; +import java.io.InvalidObjectException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -203,23 +204,32 @@ ObjectInputStream.GetField gfields = in.readFields(); // Get permissions - @SuppressWarnings("unchecked") // writeObject writes a Hashtable> // for the permissions key, so this cast is safe, unless the data is corrupt. - Hashtable> permissions = - (Hashtable>) - gfields.get("permissions", null); - perms = new ConcurrentHashMap<>(permissions.size()*2); - - // Convert each entry (Vector) into a List - Set>> set = permissions.entrySet(); - for (Map.Entry> e : set) { - // Convert Vector into ArrayList - Vector vec = e.getValue(); - List list = new CopyOnWriteArrayList<>(vec); + try { + @SuppressWarnings("unchecked") + Hashtable> permissions = + (Hashtable>) + gfields.get("permissions", null); - // Add to Hashtable being serialized - perms.put(e.getKey(), list); + if (permissions == null) { + throw new InvalidObjectException("Invalid null permissions"); + } + + perms = new ConcurrentHashMap<>(permissions.size()*2); + + // Convert each entry (Vector) into a List + Set>> set = permissions.entrySet(); + for (Map.Entry> e : set) { + // Convert Vector into ArrayList + Vector vec = e.getValue(); + List list = new CopyOnWriteArrayList<>(vec); + + // Add to Hashtable being serialized + perms.put(e.getKey(), list); + } + } catch (ClassCastException cce) { + throw new InvalidObjectException("Invalid type for permissions"); } } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/security/cert/CertificateRevokedException.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; +import java.io.InvalidObjectException; import java.util.Collections; import java.util.Date; import java.util.HashMap; @@ -70,6 +71,13 @@ private transient Map extensions; + private static boolean isNull(Date revocationDate, + CRLReason reason, X500Principal authority, + Map extensions) { + return (revocationDate == null || reason == null || authority == null + || extensions == null); + } + /** * Constructs a {@code CertificateRevokedException} with * the specified revocation date, reason code, authority name, and map @@ -92,8 +100,7 @@ */ public CertificateRevokedException(Date revocationDate, CRLReason reason, X500Principal authority, Map extensions) { - if (revocationDate == null || reason == null || authority == null || - extensions == null) { + if (isNull(revocationDate, reason, authority, extensions)) { throw new NullPointerException(); } this.revocationDate = new Date(revocationDate.getTime()); @@ -234,9 +241,6 @@ // (revocationDate, reason, authority) ois.defaultReadObject(); - // Defensively copy the revocation date - revocationDate = new Date(revocationDate.getTime()); - // Read in the size (number of mappings) of the extensions map // and create the extensions map int size = ois.readInt(); @@ -247,6 +251,13 @@ } else { extensions = new HashMap<>(size > 20 ? 20 : size); } + // make sure all fields are set before checking + if (isNull(revocationDate, reason, authority, extensions)) { + throw new InvalidObjectException("Invalid null field(s)"); + } + + // Defensively copy the revocation date + revocationDate = new Date(revocationDate.getTime()); // Read in the extensions and put the mappings in the extensions map for (int i = 0; i < size; i++) { diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarFile.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarFile.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarFile.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarFile.java 2025-04-09 19:45:33.000000000 +0000 @@ -422,7 +422,8 @@ jv = new JarVerifier(manEntry.getName(), b); } else { if (JarVerifier.debug != null) { - JarVerifier.debug.println("Multiple MANIFEST.MF found. Treat JAR file as unsigned"); + JarVerifier.debug.println( + JarVerifier.MULTIPLE_MANIFEST_WARNING); } } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarInputStream.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarInputStream.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarInputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarInputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -97,7 +97,17 @@ jv = new JarVerifier(e.getName(), bytes); mev = new ManifestEntryVerifier(man, jv.manifestName); } - return (JarEntry)super.getNextEntry(); + JarEntry nextEntry = (JarEntry)super.getNextEntry(); + if (nextEntry != null && + JarFile.MANIFEST_NAME.equalsIgnoreCase(nextEntry.getName())) { + if (JarVerifier.debug != null) { + JarVerifier.debug.println(JarVerifier.MULTIPLE_MANIFEST_WARNING); + } + + jv = null; + mev = null; + } + return nextEntry; } return e; } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarVerifier.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarVerifier.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/jar/JarVerifier.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/jar/JarVerifier.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,6 +44,9 @@ */ class JarVerifier { + public static final String MULTIPLE_MANIFEST_WARNING = + "WARNING: Multiple MANIFEST.MF found. Treat JAR file as unsigned."; + /* Are we debugging ? */ static final Debug debug = Debug.getInstance("jar"); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -40,6 +40,26 @@ * @since 1.1 */ public class DeflaterOutputStream extends FilterOutputStream { + + /* + * The default size of the output buffer + */ + static final int DEFAULT_BUF_SIZE = 512; + + /* + * When calling Deflater.deflate() with Deflater.SYNC_FLUSH or Deflater.FULL_FLUSH, + * the callers are expected to ensure that the size of the buffer is greater than 6. + * This expectation comes from the underlying zlib library which in its zlib.h + * states: + * "If deflate returns with avail_out == 0, this function must be called again + * with the same value of the flush parameter and more output space (updated + * avail_out), until the flush is complete (deflate returns with non-zero + * avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + * avail_out is greater than six when the flush marker begins, in order to avoid + * repeated flush markers upon calling deflate() again when avail_out == 0." + */ + private static final int SYNC_FLUSH_MIN_BUF_SIZE = 7; + /** * Compressor for this stream. */ @@ -123,7 +143,7 @@ public DeflaterOutputStream(OutputStream out, Deflater def, boolean syncFlush) { - this(out, def, 512, syncFlush); + this(out, def, DEFAULT_BUF_SIZE, syncFlush); } @@ -138,7 +158,7 @@ * @param def the compressor ("deflater") */ public DeflaterOutputStream(OutputStream out, Deflater def) { - this(out, def, 512, false); + this(out, def, DEFAULT_BUF_SIZE, false); } boolean usesDefaultDeflater = false; @@ -158,7 +178,7 @@ * @since 1.7 */ public DeflaterOutputStream(OutputStream out, boolean syncFlush) { - this(out, out != null ? new Deflater() : null, 512, syncFlush); + this(out, out != null ? new Deflater() : null, DEFAULT_BUF_SIZE, syncFlush); usesDefaultDeflater = true; } @@ -181,6 +201,7 @@ * @param b the byte to be written * @throws IOException if an I/O error has occurred */ + @Override public void write(int b) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)(b & 0xff); @@ -195,6 +216,7 @@ * @param len the length of the data * @throws IOException if an I/O error has occurred */ + @Override public void write(byte[] b, int off, int len) throws IOException { if (def.finished()) { throw new IOException("write beyond end of stream"); @@ -238,6 +260,7 @@ * underlying stream. * @throws IOException if an I/O error has occurred */ + @Override public void close() throws IOException { if (!closed) { try { @@ -277,13 +300,20 @@ * * @since 1.7 */ + @Override public void flush() throws IOException { if (syncFlush && !def.finished()) { int len = 0; - while ((len = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH)) > 0) - { - out.write(buf, 0, len); - if (len < buf.length) + // For SYNC_FLUSH, the Deflater.deflate() expects the callers + // to use a buffer whose length is greater than 6 to avoid + // flush marker (5 bytes) being repeatedly output to the output buffer + // every time it is invoked. + final byte[] flushBuf = buf.length < SYNC_FLUSH_MIN_BUF_SIZE + ? new byte[DEFAULT_BUF_SIZE] + : buf; + while ((len = def.deflate(flushBuf, 0, flushBuf.length, Deflater.SYNC_FLUSH)) > 0) { + out.write(flushBuf, 0, len); + if (len < flushBuf.length) break; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/zip/GZIPOutputStream.java openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/GZIPOutputStream.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/java/util/zip/GZIPOutputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/java/util/zip/GZIPOutputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -109,7 +109,7 @@ * @throws IOException If an I/O error has occurred. */ public GZIPOutputStream(OutputStream out) throws IOException { - this(out, 512, false); + this(out, DeflaterOutputStream.DEFAULT_BUF_SIZE, false); } /** @@ -131,7 +131,7 @@ public GZIPOutputStream(OutputStream out, boolean syncFlush) throws IOException { - this(out, 512, syncFlush); + this(out, DeflaterOutputStream.DEFAULT_BUF_SIZE, syncFlush); } /** diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java 2025-04-09 19:45:33.000000000 +0000 @@ -70,6 +70,7 @@ // Convenience variables for parsing private StreamTokenizer st; private int lookahead; + private boolean allPermEntryFound = false; /** * Creates a CryptoPolicyParser object. @@ -128,7 +129,7 @@ * The crypto jurisdiction policy must be consistent. The * following hashtable is used for checking consistency. */ - Hashtable> processedPermissions = null; + Hashtable> processedPermissions = new Hashtable<>(); /* * The main parsing loop. The loop is executed once for each entry @@ -191,6 +192,16 @@ e.cryptoPermission = match("permission type"); if (e.cryptoPermission.equals("javax.crypto.CryptoAllPermission")) { + /* + * This catches while processing the "javax.crypto.CryptoAllPermission" + * entry, but the "processedPermissions" Hashtable already contains + * an entry for "javax.crypto.CryptoPermission". + */ + if (!processedPermissions.isEmpty()) { + throw new ParsingException(st.lineno(), "Inconsistent policy"); + } + allPermEntryFound = true; + // Done with the CryptoAllPermission entry. e.alg = CryptoAllPermission.ALG_NAME; e.maxKeySize = Integer.MAX_VALUE; @@ -498,18 +509,21 @@ String thisExemptionMechanism = exemptionMechanism == null ? "none" : exemptionMechanism; - if (processedPermissions == null) { - processedPermissions = new Hashtable>(); + /* + * This catches while processing a "javax.crypto.CryptoPermission" entry, but + * "javax.crypto.CryptoAllPermission" entry already exists. + */ + if (allPermEntryFound) { + return false; + } + + if (processedPermissions.isEmpty()) { Vector exemptionMechanisms = new Vector<>(1); exemptionMechanisms.addElement(thisExemptionMechanism); processedPermissions.put(alg, exemptionMechanisms); return true; } - if (processedPermissions.containsKey(CryptoAllPermission.ALG_NAME)) { - return false; - } - Vector exemptionMechanisms; if (processedPermissions.containsKey(alg)) { diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/javax/crypto/spec/SecretKeySpec.java openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/spec/SecretKeySpec.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/javax/crypto/spec/SecretKeySpec.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/javax/crypto/spec/SecretKeySpec.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -106,11 +106,9 @@ * is null or key is null or empty. */ public SecretKeySpec(byte[] key, String algorithm) { - if (key == null || algorithm == null) { - throw new IllegalArgumentException("Missing argument"); - } - if (key.length == 0) { - throw new IllegalArgumentException("Empty key"); + String errMsg = doSanityCheck(key, algorithm); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); } this.key = key.clone(); this.algorithm = algorithm; @@ -274,14 +272,22 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); + String errMsg = doSanityCheck(key, algorithm); + if (errMsg != null) { + throw new InvalidObjectException(errMsg); + } + byte[] temp = key; + this.key = temp.clone(); + Arrays.fill(temp, (byte) 0); + } + private static String doSanityCheck(byte[] key, String algorithm) { + String errMsg = null; if (key == null || algorithm == null) { - throw new InvalidObjectException("Missing argument"); - } - - this.key = key.clone(); - if (key.length == 0) { - throw new InvalidObjectException("Invalid key length"); + errMsg = "Missing argument"; + } else if (key.length == 0) { + errMsg = "Empty key"; } + return errMsg; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ChoiceCallback.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -103,20 +103,18 @@ public ChoiceCallback(String prompt, String[] choices, int defaultChoice, boolean multipleSelectionsAllowed) { - if (prompt == null || prompt.isEmpty() || - choices == null || choices.length == 0 || - defaultChoice < 0 || defaultChoice >= choices.length) - throw new IllegalArgumentException(); - + choices = (choices == null || choices.length == 0 ? choices : + choices.clone()); + String errMsg = doSanityCheck(prompt, choices, defaultChoice, + multipleSelectionsAllowed); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); + } this.prompt = prompt; this.defaultChoice = defaultChoice; this.multipleSelectionsAllowed = multipleSelectionsAllowed; - this.choices = choices.clone(); - for (int i = 0; i < choices.length; i++) { - if (choices[i] == null || choices[i].isEmpty()) - throw new IllegalArgumentException(); - } + this.choices = choices; } /** @@ -184,9 +182,11 @@ * @see #getSelectedIndexes */ public void setSelectedIndexes(int[] selections) { - if (!multipleSelectionsAllowed) + if (!multipleSelectionsAllowed) { throw new UnsupportedOperationException(); - this.selections = selections == null ? null : selections.clone(); + } + this.selections = ((selections == null || selections.length == 0) ? + selections : selections.clone()); } /** @@ -212,26 +212,35 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); + choices = (choices == null || choices.length == 0 ? + choices : choices.clone()); + String errMsg = doSanityCheck(prompt, choices, defaultChoice, + multipleSelectionsAllowed); + if (errMsg != null) { + throw new InvalidObjectException(errMsg); + } + selections = (selections == null || selections.length == 0 ? + selections : selections.clone()); + if (selections != null && selections.length > 1 && + !multipleSelectionsAllowed) { + throw new InvalidObjectException("Multiple selections not allowed"); + } + } + + private static String doSanityCheck(String prompt, String[] choices, + int defaultChoice, boolean allowMultiple) { if ((prompt == null) || prompt.isEmpty() || (choices == null) || (choices.length == 0) || (defaultChoice < 0) || (defaultChoice >= choices.length)) { - throw new InvalidObjectException( - "Missing/invalid prompt/choices"); + return "Missing/invalid prompt/choices"; } - choices = choices.clone(); for (int i = 0; i < choices.length; i++) { - if ((choices[i] == null) || choices[i].isEmpty()) - throw new InvalidObjectException("Null/empty choices"); - } - - if (selections != null) { - selections = selections.clone(); - if (!multipleSelectionsAllowed && (selections.length != 1)) { - throw new InvalidObjectException( - "Multiple selections not allowed"); + if ((choices[i] == null) || choices[i].isEmpty()) { + return "Null/empty choices value"; } } + return null; } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/ConfirmationCallback.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package javax.security.auth.callback; import java.io.IOException; +import java.io.InvalidObjectException; import java.io.ObjectInputStream; /** @@ -189,25 +190,10 @@ */ public ConfirmationCallback(int messageType, int optionType, int defaultOption) { - - if (messageType < INFORMATION || messageType > ERROR || - optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION) - throw new IllegalArgumentException(); - - switch (optionType) { - case YES_NO_OPTION: - if (defaultOption != YES && defaultOption != NO) - throw new IllegalArgumentException(); - break; - case YES_NO_CANCEL_OPTION: - if (defaultOption != YES && defaultOption != NO && - defaultOption != CANCEL) - throw new IllegalArgumentException(); - break; - case OK_CANCEL_OPTION: - if (defaultOption != OK && defaultOption != CANCEL) - throw new IllegalArgumentException(); - break; + String errMsg = doSanityCheck(messageType, optionType, false, null, + defaultOption, null, false); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); } this.prompt = null; @@ -250,21 +236,20 @@ public ConfirmationCallback(int messageType, String[] options, int defaultOption) { - if (messageType < INFORMATION || messageType > ERROR || - options == null || options.length == 0 || - defaultOption < 0 || defaultOption >= options.length) - throw new IllegalArgumentException(); + if (options != null) { + options = options.clone(); + } + String errMsg = doSanityCheck(messageType, UNSPECIFIED_OPTION, true, + options, defaultOption, null, false); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); + } this.prompt = null; this.messageType = messageType; this.optionType = UNSPECIFIED_OPTION; this.defaultOption = defaultOption; - - this.options = options.clone(); - for (int i = 0; i < options.length; i++) { - if (options[i] == null || options[i].isEmpty()) - throw new IllegalArgumentException(); - } + this.options = options; } /** @@ -304,27 +289,11 @@ public ConfirmationCallback(String prompt, int messageType, int optionType, int defaultOption) { - if (prompt == null || prompt.isEmpty() || - messageType < INFORMATION || messageType > ERROR || - optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION) - throw new IllegalArgumentException(); - - switch (optionType) { - case YES_NO_OPTION: - if (defaultOption != YES && defaultOption != NO) - throw new IllegalArgumentException(); - break; - case YES_NO_CANCEL_OPTION: - if (defaultOption != YES && defaultOption != NO && - defaultOption != CANCEL) - throw new IllegalArgumentException(); - break; - case OK_CANCEL_OPTION: - if (defaultOption != OK && defaultOption != CANCEL) - throw new IllegalArgumentException(); - break; + String errMsg = doSanityCheck(messageType, optionType, false, null, + defaultOption, prompt, true); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); } - this.prompt = prompt; this.messageType = messageType; this.optionType = optionType; @@ -369,22 +338,20 @@ public ConfirmationCallback(String prompt, int messageType, String[] options, int defaultOption) { - if (prompt == null || prompt.isEmpty() || - messageType < INFORMATION || messageType > ERROR || - options == null || options.length == 0 || - defaultOption < 0 || defaultOption >= options.length) - throw new IllegalArgumentException(); + if (options != null) { + options = options.clone(); + } + String errMsg = doSanityCheck(messageType, UNSPECIFIED_OPTION, true, + options, defaultOption, prompt, true); + if (errMsg != null) { + throw new IllegalArgumentException(errMsg); + } this.prompt = prompt; this.messageType = messageType; this.optionType = UNSPECIFIED_OPTION; this.defaultOption = defaultOption; - - this.options = options.clone(); - for (int i = 0; i < options.length; i++) { - if (options[i] == null || options[i].isEmpty()) - throw new IllegalArgumentException(); - } + this.options = options; } /** @@ -491,6 +458,49 @@ return selection; } + private static String doSanityCheck(int msgType, int optionType, + boolean isUnspecifiedOption, String[] options, int defOption, + String prompt, boolean checkPrompt) { + // validate msgType + if (msgType < INFORMATION || msgType > ERROR) { + return "Invalid msgType"; + } + // validate prompt if checkPrompt == true + if (checkPrompt && (prompt == null || prompt.isEmpty())) { + return "Invalid prompt"; + } + // validate optionType + if (isUnspecifiedOption) { + if (optionType != UNSPECIFIED_OPTION) { + return "Invalid optionType"; + } + // check options + if (options == null || options.length == 0 || + defOption < 0 || defOption >= options.length) { + return "Invalid options and/or default option"; + } + for (String ov : options) { + if (ov == null || ov.isEmpty()) { + return "Invalid option value"; + } + } + } else { + if (optionType < YES_NO_OPTION || optionType > OK_CANCEL_OPTION) { + return "Invalid optionType"; + } + // validate defOption based on optionType + if ((optionType == YES_NO_OPTION && (defOption != YES && + defOption != NO)) || + (optionType == YES_NO_CANCEL_OPTION && (defOption != YES && + defOption != NO && defOption != CANCEL)) || + (optionType == OK_CANCEL_OPTION && (defOption != OK && + defOption != CANCEL))) { + return "Invalid default option"; + } + } + return null; + } + /** * Restores the state of this object from the stream. * @@ -502,8 +512,15 @@ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); + if (options != null) { options = options.clone(); } + String errMsg = doSanityCheck(messageType, optionType, + (optionType == UNSPECIFIED_OPTION), options, defaultOption, + prompt, false); + if (errMsg != null) { + throw new InvalidObjectException(errMsg); + } } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/javax/security/auth/callback/PasswordCallback.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -181,7 +181,9 @@ } if (inputPassword != null) { - inputPassword = inputPassword.clone(); + char[] temp = inputPassword; + inputPassword = temp.clone(); + Arrays.fill(temp, '0'); cleanable = CleanerFactory.cleaner().register( this, cleanerFor(inputPassword)); } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/action/GetPropertyAction.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/action/GetPropertyAction.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/action/GetPropertyAction.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/action/GetPropertyAction.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -162,6 +162,68 @@ } } + /** + * Convenience method for fetching System property values that are timeouts. + * Accepted timeout values may be purely numeric, a numeric value + * followed by "s" (both interpreted as seconds), or a numeric value + * followed by "ms" (interpreted as milliseconds). + * + * @param prop the name of the System property + * @param def a default value (in milliseconds) + * @param dbg a Debug object, if null no debug messages will be sent + * + * @return an integer value corresponding to the timeout value in the System + * property in milliseconds. If the property value is empty, negative, + * or contains non-numeric characters (besides a trailing "s" or "ms") + * then the default value will be returned. If a negative value for + * the "def" parameter is supplied, zero will be returned if the + * property's value does not conform to the allowed syntax. + */ + public static int privilegedGetTimeoutProp(String prop, int def, Debug dbg) { + if (def < 0) { + def = 0; + } + + String rawPropVal = privilegedGetProperty(prop, "").trim(); + if (rawPropVal.length() == 0) { + return def; + } + + // Determine if "ms" or just "s" is on the end of the string. + // We may do a little surgery on the value so we'll retain + // the original value in rawPropVal for debug messages. + boolean isMillis = false; + String propVal = rawPropVal; + if (rawPropVal.toLowerCase().endsWith("ms")) { + propVal = rawPropVal.substring(0, rawPropVal.length() - 2); + isMillis = true; + } else if (rawPropVal.toLowerCase().endsWith("s")) { + propVal = rawPropVal.substring(0, rawPropVal.length() - 1); + } + + // Next check to make sure the string is built only from digits + if (propVal.matches("^\\d+$")) { + try { + int timeout = Integer.parseInt(propVal); + return isMillis ? timeout : timeout * 1000; + } catch (NumberFormatException nfe) { + if (dbg != null) { + dbg.println("Warning: Unexpected " + nfe + + " for timeout value " + rawPropVal + + ". Using default value of " + def + " msec."); + } + return def; + } + } else { + if (dbg != null) { + dbg.println("Warning: Incorrect syntax for timeout value " + + rawPropVal + ". Using default value of " + def + + " msec."); + } + return def; + } + } + /** * Convenience method for fetching System property values that are booleans. * diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/DRBG.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/DRBG.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/DRBG.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/DRBG.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package sun.security.provider; import java.io.IOException; +import java.io.InvalidObjectException; import java.security.AccessController; import java.security.DrbgParameters; import java.security.PrivilegedAction; @@ -275,11 +276,18 @@ } } + /** + * Restores the state of this object from the stream. + * + * @param s the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ @java.io.Serial private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); - if (mdp.mech == null) { + if (mdp == null || mdp.mech == null) { throw new IllegalArgumentException("Input data is corrupted"); } createImpl(); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java 2025-04-09 19:45:33.000000000 +0000 @@ -26,10 +26,7 @@ import java.io.IOException; import java.io.OutputStream; -import java.net.URI; -import java.net.URL; -import java.net.HttpURLConnection; -import java.net.URLEncoder; +import java.net.*; import java.security.cert.CertificateException; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorException.BasicReason; @@ -74,11 +71,20 @@ private static final int DEFAULT_CONNECT_TIMEOUT = 15000; /** - * Integer value indicating the timeout length, in seconds, to be - * used for the OCSP check. A timeout of zero is interpreted as - * an infinite timeout. + * Integer value indicating the timeout length, in milliseconds, to be + * used for establishing a connection to an OCSP responder. A timeout of + * zero is interpreted as an infinite timeout. */ - private static final int CONNECT_TIMEOUT = initializeTimeout(); + private static final int CONNECT_TIMEOUT = initializeTimeout( + "com.sun.security.ocsp.timeout", DEFAULT_CONNECT_TIMEOUT); + + /** + * Integer value indicating the timeout length, in milliseconds, to be + * used for reading an OCSP response from the responder. A timeout of + * zero is interpreted as an infinite timeout. + */ + private static final int READ_TIMEOUT = initializeTimeout( + "com.sun.security.ocsp.readtimeout", CONNECT_TIMEOUT); /** * Boolean value indicating whether OCSP client can use GET for OCSP @@ -107,16 +113,13 @@ * system property. If the property has not been set, or if its * value is negative, set the timeout length to the default. */ - private static int initializeTimeout() { - @SuppressWarnings("removal") - Integer tmp = java.security.AccessController.doPrivileged( - new GetIntegerAction("com.sun.security.ocsp.timeout")); - if (tmp == null || tmp < 0) { - return DEFAULT_CONNECT_TIMEOUT; + private static int initializeTimeout(String prop, int def) { + int timeoutVal = + GetPropertyAction.privilegedGetTimeoutProp(prop, def, debug); + if (debug != null) { + debug.println(prop + " set to " + timeoutVal + " milliseconds"); } - // Convert to milliseconds, as the system property will be - // specified in seconds - return tmp * 1000; + return timeoutVal; } private static boolean initializeBoolean(String prop, boolean def) { @@ -277,8 +280,10 @@ Base64.getEncoder().encodeToString(bytes), "UTF-8")); if (USE_GET && encodedGetReq.length() <= 255) { - url = new URL(encodedGetReq.toString()); + url = new URI(encodedGetReq.toString()).toURL(); con = (HttpURLConnection)url.openConnection(); + con.setConnectTimeout(CONNECT_TIMEOUT); + con.setReadTimeout(READ_TIMEOUT); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("GET"); @@ -286,7 +291,7 @@ url = responderURI.toURL(); con = (HttpURLConnection)url.openConnection(); con.setConnectTimeout(CONNECT_TIMEOUT); - con.setReadTimeout(CONNECT_TIMEOUT); + con.setReadTimeout(READ_TIMEOUT); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); @@ -316,6 +321,8 @@ return (contentLength == -1) ? con.getInputStream().readAllBytes() : IOUtils.readExactlyNBytes(con.getInputStream(), contentLength); + } catch (URISyntaxException urise) { + throw new IOException(urise); } finally { if (con != null) { con.disconnect(); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,7 +50,8 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import sun.security.action.GetIntegerAction; + +import sun.security.action.GetPropertyAction; import sun.security.x509.AccessDescription; import sun.security.x509.GeneralNameInterface; import sun.security.x509.URIName; @@ -127,8 +128,12 @@ // allowed when downloading CRLs private static final int DEFAULT_CRL_READ_TIMEOUT = 15000; + // Default connect and read timeouts for CA certificate fetching (15 sec) + private static final int DEFAULT_CACERT_CONNECT_TIMEOUT = 15000; + private static final int DEFAULT_CACERT_READ_TIMEOUT = 15000; + /** - * Integer value indicating the connect timeout, in seconds, to be + * Integer value indicating the connect timeout, in milliseconds, to be * used for the CRL download. A timeout of zero is interpreted as * an infinite timeout. */ @@ -137,7 +142,7 @@ DEFAULT_CRL_CONNECT_TIMEOUT); /** - * Integer value indicating the read timeout, in seconds, to be + * Integer value indicating the read timeout, in milliseconds, to be * used for the CRL download. A timeout of zero is interpreted as * an infinite timeout. */ @@ -146,21 +151,35 @@ DEFAULT_CRL_READ_TIMEOUT); /** + * Integer value indicating the connect timeout, in milliseconds, to be + * used for the CA certificate download. A timeout of zero is interpreted + * as an infinite timeout. + */ + private static final int CACERT_CONNECT_TIMEOUT = + initializeTimeout("com.sun.security.cert.timeout", + DEFAULT_CACERT_CONNECT_TIMEOUT); + + /** + * Integer value indicating the read timeout, in milliseconds, to be + * used for the CA certificate download. A timeout of zero is interpreted + * as an infinite timeout. + */ + private static final int CACERT_READ_TIMEOUT = + initializeTimeout("com.sun.security.cert.readtimeout", + DEFAULT_CACERT_READ_TIMEOUT); + + /** * Initialize the timeout length by getting the specified CRL timeout * system property. If the property has not been set, or if its * value is negative, set the timeout length to the specified default. */ private static int initializeTimeout(String prop, int def) { - Integer tmp = GetIntegerAction.privilegedGetProperty(prop); - if (tmp == null || tmp < 0) { - return def; - } + int timeoutVal = + GetPropertyAction.privilegedGetTimeoutProp(prop, def, debug); if (debug != null) { - debug.println(prop + " set to " + tmp + " seconds"); + debug.println(prop + " set to " + timeoutVal + " milliseconds"); } - // Convert to milliseconds, as the system property will be - // specified in seconds - return tmp * 1000; + return timeoutVal; } /** @@ -276,6 +295,8 @@ connection.setIfModifiedSince(lastModified); } long oldLastModified = lastModified; + connection.setConnectTimeout(CACERT_CONNECT_TIMEOUT); + connection.setReadTimeout(CACERT_READ_TIMEOUT); try (InputStream in = connection.getInputStream()) { lastModified = connection.getLastModified(); if (oldLastModified != 0) { diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/rsa/RSAPadding.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/rsa/RSAPadding.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/rsa/RSAPadding.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/rsa/RSAPadding.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -322,48 +322,103 @@ * Note that we want to make it a constant-time operation */ private byte[] unpadV15(byte[] padded) { - int k = 0; - boolean bp = false; + int paddedLength = padded.length; - if (padded[k++] != 0) { - bp = true; - } - if (padded[k++] != type) { - bp = true; + if (paddedLength < 2) { + return null; } - int p = 0; - while (k < padded.length) { + + // The following check ensures that the lead byte is zero and + // the second byte is equivalent to the padding type. The + // bp (bad padding) variable throughout this unpadding process will + // be updated and remain 0 if good padding, 1 if bad. + int p0 = padded[0]; + int p1 = padded[1]; + int bp = (-(p0 & 0xff) | ((p1 - type) | (type - p1))) >>> 31; + + int padLen = 0; + int k = 2; + // Walk through the random, nonzero padding bytes. For each padding + // byte bp and padLen will remain zero. When the end-of-padding + // byte (0x00) is reached then padLen will be set to the index of the + // first byte of the message content. + while (k < paddedLength) { int b = padded[k++] & 0xff; - if ((b == 0) && (p == 0)) { - p = k; - } - if ((k == padded.length) && (p == 0)) { - bp = true; - } - if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) && - (p == 0)) { - bp = true; + padLen += (k * (1 - ((-(b | padLen)) >>> 31))); + if (k == paddedLength) { + bp = bp | (1 - ((-padLen) >>> 31)); } + bp = bp | (1 - (-(((type - PAD_BLOCKTYPE_1) & 0xff) | + padLen | (1 - ((b - 0xff) >>> 31))) >>> 31)); } - int n = padded.length - p; - if (n > maxDataSize) { - bp = true; - } + int n = paddedLength - padLen; + // So long as n <= maxDataSize, bp will remain zero + bp = bp | ((maxDataSize - n) >>> 31); // copy useless padding array for a constant-time method - byte[] padding = new byte[p]; - System.arraycopy(padded, 0, padding, 0, p); + byte[] padding = new byte[padLen + 2]; + for (int i = 0; i < padLen; i++) { + padding[i] = padded[i]; + } byte[] data = new byte[n]; - System.arraycopy(padded, p, data, 0, n); + for (int i = 0; i < n; i++) { + data[i] = padded[padLen + i]; + } - if (bp) { + if ((bp | padding[bp]) != 0) { + // using the array padding here hoping that this way + // the compiler does not eliminate the above useless copy return null; } else { return data; } } + public byte[] unpadForTls(byte[] padded, int clientVersion, + int serverVersion) { + int paddedLength = padded.length; + + // bp is positive if the padding is bad and 0 if it is good so far + int bp = (((int) padded[0] | ((int)padded[1] - PAD_BLOCKTYPE_2)) & + 0xFFF); + + int k = 2; + while (k < paddedLength - 49) { + int b = padded[k++] & 0xFF; + bp = bp | (1 - (-b >>> 31)); // if (padded[k] == 0) bp |= 1; + } + bp |= ((int)padded[k++] & 0xFF); + int encodedVersion = ((padded[k] & 0xFF) << 8) | (padded[k + 1] & 0xFF); + + int bv1 = clientVersion - encodedVersion; + bv1 |= -bv1; + int bv3 = serverVersion - encodedVersion; + bv3 |= -bv3; + int bv2 = (0x301 - clientVersion); + + bp |= ((bv1 & (bv2 | bv3)) >>> 28); + + byte[] data = Arrays.copyOfRange(padded, paddedLength - 48, + paddedLength); + if (random == null) { + random = JCAUtil.getSecureRandom(); + } + + byte[] fake = new byte[48]; + random.nextBytes(fake); + + bp = (-bp >> 24); + + // Now bp is 0 if the padding and version number were good and + // -1 otherwise. + for (int i = 0; i < 48; i++) { + data[i] = (byte)((~bp & data[i]) | (bp & fake[i])); + } + + return data; + } + /** * PKCS#1 v2.0 OAEP padding (MGF1). * Paragraph references refer to PKCS#1 v2.1 (June 14, 2002) diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/tools/keytool/Main.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/tools/keytool/Main.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/tools/keytool/Main.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/tools/keytool/Main.java 2025-04-09 19:45:33.000000000 +0000 @@ -1287,6 +1287,7 @@ kssave = true; } else if (command == LIST) { if (storePass == null + && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) && !isPasswordlessKeyStore) { printNoIntegrityWarning(); @@ -1686,6 +1687,7 @@ throws Exception { if (storePass == null + && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) && !isPasswordlessKeyStore) { printNoIntegrityWarning(); diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/KeyUtil.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/KeyUtil.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/KeyUtil.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/KeyUtil.java 2025-04-09 19:45:33.000000000 +0000 @@ -322,19 +322,31 @@ tmp = encoded; } + // At this point tmp.length is 48 int encodedVersion = ((tmp[0] & 0xFF) << 8) | (tmp[1] & 0xFF); - int check1 = 0; - int check2 = 0; - int check3 = 0; - if (clientVersion != encodedVersion) check1 = 1; - if (clientVersion > 0x0301) check2 = 1; - if (serverVersion != encodedVersion) check3 = 1; - if ((check1 & (check2 | check3)) == 1) { - return replacer; - } else { - return tmp; + + // The following code is a time-constant version of + // if ((clientVersion != encodedVersion) || + // ((clientVersion > 0x301) && (serverVersion != encodedVersion))) { + // return replacer; + // } else { return tmp; } + int check1 = (clientVersion - encodedVersion) | + (encodedVersion - clientVersion); + int check2 = 0x0301 - clientVersion; + int check3 = (serverVersion - encodedVersion) | + (encodedVersion - serverVersion); + + check1 = (check1 & (check2 | check3)) >> 24; + + // Now check1 is either 0 or -1 + check2 = ~check1; + + for (int i = 0; i < 48; i++) { + tmp[i] = (byte) ((tmp[i] & check2) | (replacer[i] & check1)); } + + return tmp; } /** diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/ObjectIdentifier.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,13 +127,24 @@ // Is the components field calculated? private transient boolean componentsCalculated = false; + /** + * Restores the state of this object from the stream. + * + * @param is the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ @java.io.Serial private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { is.defaultReadObject(); if (encoding == null) { // from an old version - int[] comp = (int[])components; + if (components == null) { + throw new InvalidObjectException("OID components is null"); + } + + int[] comp = ((int[]) components).clone(); if (componentLen > comp.length) { componentLen = comp.length; } @@ -142,7 +153,9 @@ // will be performed again in init(). checkOidSize(componentLen); init(comp, componentLen); + components = comp; } else { + encoding = encoding.clone(); // defensive copying checkOidSize(encoding.length); check(encoding); } @@ -261,6 +274,7 @@ encoding = in.getDerValue().getOID().encoding; } + // set 'encoding' field based on the specified 'components' and 'length' private void init(int[] components, int length) throws IOException { int pos = 0; byte[] tmp = new byte[length * 5 + 1]; // +1 for empty input diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -525,6 +525,8 @@ boolean attrsVerified = true; // If only weak algorithms are used. boolean weakAlgs = true; + // If only unsupported algorithms are used. + boolean unsupportedAlgs = true; // If a ATTR_DIGEST entry is found. boolean validEntry = false; @@ -549,6 +551,7 @@ MessageDigest digest = getDigest(algorithm); if (digest != null) { + unsupportedAlgs = false; ManifestDigester.Entry mde = md.getMainAttsEntry(false); if (mde == null) { throw new SignatureException("Manifest Main Attribute check " + @@ -591,12 +594,22 @@ } } - // If there were only weak algorithms entries used, throw an exception. - if (validEntry && weakAlgs) { - throw new SignatureException("Manifest Main Attribute check " + - "failed (" + ATTR_DIGEST + "). " + - "Disabled algorithm(s) used: " + - getWeakAlgorithms(ATTR_DIGEST)); + if (validEntry) { + // If there were only weak algorithms entries used, throw an exception. + if (weakAlgs) { + throw new SignatureException( + "Manifest Main Attribute check " + + "failed (" + ATTR_DIGEST + "). " + + "Disabled algorithm(s) used: " + + getWeakAlgorithms(ATTR_DIGEST)); + } + + // If there were only unsupported algorithms entries used, throw an exception. + if (unsupportedAlgs) { + throw new SignatureException( + "Manifest Main Attribute check failed (" + + ATTR_DIGEST + "). Unsupported algorithm(s) used"); + } } // this method returns 'true' if either: diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CADistrustPolicy.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,6 +69,22 @@ } EntrustTLSPolicy.checkDistrust(chain); } + }, + + /** + * Distrust TLS Server certificates anchored by a CAMERFIRMA root CA and + * issued after April 15, 2025. If enabled, this policy is currently + * enforced by the PKIX and SunX509 TrustManager implementations + * of the SunJSSE provider implementation. + */ + CAMERFIRMA_TLS { + void checkDistrust(String variant, X509Certificate[] chain) + throws ValidatorException { + if (!variant.equals(Validator.VAR_TLS_SERVER)) { + return; + } + CamerfirmaTLSPolicy.checkDistrust(chain); + } }; /** diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/validator/CamerfirmaTLSPolicy.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CamerfirmaTLSPolicy.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/validator/CamerfirmaTLSPolicy.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/validator/CamerfirmaTLSPolicy.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.security.validator; + +import java.security.cert.X509Certificate; +import java.time.LocalDate; +import java.time.Month; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.Map; +import java.util.Set; + +import sun.security.util.Debug; +import sun.security.x509.X509CertImpl; + +/** + * This class checks if Camerfirma issued TLS Server certificates should be + * restricted. + */ +final class CamerfirmaTLSPolicy { + + private static final Debug debug = Debug.getInstance("certpath"); + + // SHA-256 certificate fingerprints of distrusted roots + private static final Set FINGERPRINTS = Set.of( + // cacerts alias: camerfirmachamberscommerceca + // DN: CN=Chambers of Commerce Root, + // OU=http://www.chambersign.org, + // O=AC Camerfirma SA CIF A82743287, C=EU + "0C258A12A5674AEF25F28BA7DCFAECEEA348E541E6F5CC4EE63B71B361606AC3", + // cacerts alias: camerfirmachambersca + // DN: CN=Chambers of Commerce Root - 2008, + // O=AC Camerfirma S.A., SERIALNUMBER=A82743287, + // L=Madrid (see current address at www.camerfirma.com/address), + // C=EU + "063E4AFAC491DFD332F3089B8542E94617D893D7FE944E10A7937EE29D9693C0", + // cacerts alias: camerfirmachambersignca + // DN: CN=Global Chambersign Root - 2008, + // O=AC Camerfirma S.A., SERIALNUMBER=A82743287, + // L=Madrid (see current address at www.camerfirma.com/address), + // C=EU + "136335439334A7698016A0D324DE72284E079D7B5220BB8FBD747816EEBEBACA" + ); + + // Any TLS Server certificate that is anchored by one of the Camerfirma + // roots above and is issued after this date will be distrusted. + private static final LocalDate APRIL_15_2025 = + LocalDate.of(2025, Month.APRIL, 15); + + /** + * This method assumes the eeCert is a TLS Server Cert and chains back to + * the anchor. + * + * @param chain the end-entity's certificate chain. The end entity cert + * is at index 0, the trust anchor at index n-1. + * @throws ValidatorException if the certificate is distrusted + */ + static void checkDistrust(X509Certificate[] chain) + throws ValidatorException { + X509Certificate anchor = chain[chain.length-1]; + String fp = fingerprint(anchor); + if (fp == null) { + throw new ValidatorException("Cannot generate fingerprint for " + + "trust anchor of TLS server certificate"); + } + if (FINGERPRINTS.contains(fp)) { + Date notBefore = chain[0].getNotBefore(); + LocalDate ldNotBefore = LocalDate.ofInstant(notBefore.toInstant(), + ZoneOffset.UTC); + // reject if certificate is issued after April 15, 2025 + checkNotBefore(ldNotBefore, APRIL_15_2025, anchor); + } + } + + private static String fingerprint(X509Certificate cert) { + return X509CertImpl.getFingerprint("SHA-256", cert, debug); + } + + private static void checkNotBefore(LocalDate notBeforeDate, + LocalDate distrustDate, X509Certificate anchor) + throws ValidatorException { + if (notBeforeDate.isAfter(distrustDate)) { + throw new ValidatorException + ("TLS Server certificate issued after " + distrustDate + + " and anchored by a distrusted legacy Camerfirma root CA: " + + anchor.getSubjectX500Principal(), + ValidatorException.T_UNTRUSTED_CERT, anchor); + } + } + + private CamerfirmaTLSPolicy() {} +} diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/AlgIdDSA.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,13 @@ package sun.security.x509; +import java.io.ObjectInputStream; import java.io.IOException; +import java.io.InvalidObjectException; import java.math.BigInteger; import java.security.*; import java.security.interfaces.DSAParams; - +import java.util.Arrays; import sun.security.util.*; @@ -72,33 +74,42 @@ * * @author David Brownell */ -public final -class AlgIdDSA extends AlgorithmId implements DSAParams -{ +public final class AlgIdDSA extends AlgorithmId implements DSAParams { @java.io.Serial private static final long serialVersionUID = 3437177836797504046L; + private static class DSAComponents { + private final BigInteger p; + private final BigInteger q; + private final BigInteger g; + DSAComponents(BigInteger p, BigInteger q, BigInteger g) { + this.p = p; + this.q = q; + this.g = g; + } + } + /* * The three unsigned integer parameters. */ - private BigInteger p , q, g; + private BigInteger p, q, g; /** Returns the DSS/DSA parameter "P" */ - public BigInteger getP () { return p; } + public BigInteger getP() { return p; } /** Returns the DSS/DSA parameter "Q" */ - public BigInteger getQ () { return q; } + public BigInteger getQ() { return q; } /** Returns the DSS/DSA parameter "G" */ - public BigInteger getG () { return g; } + public BigInteger getG() { return g; } /** * Default constructor. The OID and parameters must be * deserialized before this algorithm ID is used. */ @Deprecated - public AlgIdDSA () {} + public AlgIdDSA() {} /** * Constructs a DSS/DSA Algorithm ID from numeric parameters. @@ -109,7 +120,7 @@ * @param q the DSS/DSA parameter "Q" * @param g the DSS/DSA parameter "G" */ - public AlgIdDSA (BigInteger p, BigInteger q, BigInteger g) { + public AlgIdDSA(BigInteger p, BigInteger q, BigInteger g) { super (DSA_oid); if (p != null || q != null || g != null) { @@ -120,8 +131,10 @@ this.p = p; this.q = q; this.g = g; - initializeParams (); - + // For algorithm IDs which haven't been created from a DER + // encoded value, need to create DER encoding and store it + // into "encodedParams" + encodedParams = encode(p, q, g); } catch (IOException e) { /* this should not happen */ throw new ProviderException ("Construct DSS/DSA Algorithm ID"); @@ -133,50 +146,10 @@ * Returns "DSA", indicating the Digital Signature Algorithm (DSA) as * defined by the Digital Signature Standard (DSS), FIPS 186. */ - public String getName () - { return "DSA"; } - - - /* - * For algorithm IDs which haven't been created from a DER encoded - * value, "params" must be created. - */ - private void initializeParams () throws IOException { - DerOutputStream out = new DerOutputStream(); - out.putInteger(p); - out.putInteger(q); - out.putInteger(g); - DerOutputStream result = new DerOutputStream(); - result.write(DerValue.tag_Sequence, out); - encodedParams = result.toByteArray(); + public String getName() { + return "DSA"; } - /** - * Parses algorithm parameters P, Q, and G. They're found - * in the "params" member, which never needs to be changed. - */ - protected void decodeParams () throws IOException { - if (encodedParams == null) { - throw new IOException("DSA alg params are null"); - } - - DerValue params = new DerValue(encodedParams); - if (params.tag != DerValue.tag_Sequence) { - throw new IOException("DSA alg parsing error"); - } - - params.data.reset (); - - this.p = params.data.getBigInteger(); - this.q = params.data.getBigInteger(); - this.g = params.data.getBigInteger(); - - if (params.data.available () != 0) - throw new IOException ("AlgIdDSA params, extra="+ - params.data.available ()); - } - - /* * Returns a formatted string describing the parameters. */ @@ -197,4 +170,44 @@ "\n"; } } + + /** + * Restores the state of this object from the stream. Override to check + * on the 'p', 'q', 'g', and 'encodedParams'. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) throws IOException { + try { + stream.defaultReadObject(); + // if any of the 'p', 'q', 'g', 'encodedParams' is non-null, + // then they must be all non-null w/ matching encoding + if ((p != null || q != null || g != null || encodedParams != null) + && !Arrays.equals(encodedParams, encode(p, q, g))) { + throw new InvalidObjectException("Invalid DSA alg params"); + } + } catch (ClassNotFoundException e) { + throw new IOException(e); + } + } + + /* + * Create the DER encoding w/ the specified 'p', 'q', 'g' + */ + private static byte[] encode(BigInteger p, BigInteger q, + BigInteger g) throws IOException { + if (p == null || q == null || g == null) { + throw new InvalidObjectException("invalid null value"); + } + DerOutputStream out = new DerOutputStream(); + out.putInteger(p); + out.putInteger(q); + out.putInteger(g); + DerOutputStream result = new DerOutputStream(); + result.write(DerValue.tag_Sequence, out); + return result.toByteArray(); + } } diff -Nru openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/x509/DNSName.java openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/DNSName.java --- openjdk-17-17.0.14+7/src/java.base/share/classes/sun/security/x509/DNSName.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/classes/sun/security/x509/DNSName.java 2025-04-09 19:45:33.000000000 +0000 @@ -202,18 +202,12 @@ * . These results are used in checking NameConstraints during * certification path verification. *

- * RFC5280: DNS name restrictions are expressed as host.example.com. + * RFC5280: For DNS names, restrictions MUST use the DNSName syntax in Section 4.2.1.6. * Any DNS name that can be constructed by simply adding zero or more * labels to the left-hand side of the name satisfies the name constraint. * For example, www.host.example.com would satisfy the constraint but * host1.example.com would not. *

- * RFC 5280: DNSName restrictions are expressed as foo.bar.com. - * Any DNSName that - * can be constructed by simply adding to the left hand side of the name - * satisfies the name constraint. For example, www.foo.bar.com would - * satisfy the constraint but foo1.bar.com would not. - *

* RFC1034: By convention, domain names can be stored with arbitrary case, but * domain name comparisons for all present domain functions are done in a * case-insensitive manner, assuming an ASCII character set, and a high @@ -238,13 +232,13 @@ constraintType = NAME_MATCH; else if (thisName.endsWith(inName)) { int inNdx = thisName.lastIndexOf(inName); - if (thisName.charAt(inNdx-1) == '.' ) + if (thisName.charAt(inNdx-1) == '.' ^ inName.charAt(0) == '.') constraintType = NAME_WIDENS; else constraintType = NAME_SAME_TYPE; } else if (inName.endsWith(thisName)) { int ndx = inName.lastIndexOf(thisName); - if (inName.charAt(ndx-1) == '.' ) + if (inName.charAt(ndx-1) == '.' ^ thisName.charAt(0) == '.') constraintType = NAME_NARROWS; else constraintType = NAME_SAME_TYPE; diff -Nru openjdk-17-17.0.14+7/src/java.base/share/conf/security/java.security openjdk-17-17.0.15+6/src/java.base/share/conf/security/java.security --- openjdk-17-17.0.14+7/src/java.base/share/conf/security/java.security 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/share/conf/security/java.security 2025-04-09 19:45:33.000000000 +0000 @@ -1284,6 +1284,9 @@ # ENTRUST_TLS : Distrust TLS Server certificates anchored by # an Entrust root CA and issued after November 11, 2024. # +# CAMERFIRMA_TLS : Distrust TLS Server certificates anchored by +# a Camerfirma root CA and issued after April 15, 2025. +# # Leading and trailing whitespace surrounding each value are ignored. # Unknown values are ignored. If the property is commented out or set to the # empty String, no policies are enforced. @@ -1295,7 +1298,7 @@ # jdk.certpath.disabledAlgorithms; those restrictions are still enforced even # if this property is not enabled. # -jdk.security.caDistrustPolicies=SYMANTEC_TLS,ENTRUST_TLS +jdk.security.caDistrustPolicies=SYMANTEC_TLS,ENTRUST_TLS,CAMERFIRMA_TLS # # FilePermission path canonicalization diff -Nru openjdk-17-17.0.14+7/src/java.base/unix/native/libjsig/jsig.c openjdk-17-17.0.15+6/src/java.base/unix/native/libjsig/jsig.c --- openjdk-17-17.0.14+7/src/java.base/unix/native/libjsig/jsig.c 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.base/unix/native/libjsig/jsig.c 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -102,9 +102,9 @@ if (os_signal == NULL) { // Deprecation warning first time through - printf(HOTSPOT_VM_DISTRO " VM warning: the use of signal() and sigset() " - "for signal chaining was deprecated in version 16.0 and will " - "be removed in a future release. Use sigaction() instead.\n"); + fprintf(stderr, HOTSPOT_VM_DISTRO " VM warning: the use of signal() and sigset() " + "for signal chaining was deprecated in version 16.0 and will " + "be removed in a future release. Use sigaction() instead.\n"); if (!is_sigset) { os_signal = (signal_function_t)dlsym(RTLD_NEXT, "signal"); } else { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m --- openjdk-17-17.0.14+7/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1695,6 +1695,7 @@ int shieldLevel = CGShieldingWindowLevel(); window.preFullScreenLevel = [nsWindow level]; [nsWindow setLevel: shieldLevel]; + [nsWindow makeKeyAndOrderFront: nil]; NSRect screenRect = [[nsWindow screen] frame]; [nsWindow setFrame:screenRect display:YES]; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m --- openjdk-17-17.0.14+7/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m 2025-04-09 19:45:33.000000000 +0000 @@ -32,9 +32,13 @@ @implementation MenuAccessibility - (NSAccessibilityRole _Nonnull)accessibilityRole { - return [[[self parent] javaRole] isEqualToString:@"combobox"] - ? NSAccessibilityPopUpButtonRole - : NSAccessibilityMenuRole; + if ([[[self parent] javaRole] isEqualToString:@"combobox"]) { + return NSAccessibilityPopUpButtonRole; + } else if ([[[self parent] javaRole] isEqualToString:@"menubar"]) { + return NSAccessibilityMenuBarItemRole; + } else { + return NSAccessibilityMenuRole; + } } - (BOOL)isAccessibilityElement diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/AdobeMarkerSegment.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/AdobeMarkerSegment.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/AdobeMarkerSegment.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/jpeg/AdobeMarkerSegment.java 2025-04-09 19:45:33.000000000 +0000 @@ -55,15 +55,17 @@ AdobeMarkerSegment(JPEGBuffer buffer) throws IOException { super(buffer); - buffer.bufPtr += ID_SIZE; // Skip the id - version = (buffer.buf[buffer.bufPtr++] & 0xff) << 8; - version |= buffer.buf[buffer.bufPtr++] & 0xff; - flags0 = (buffer.buf[buffer.bufPtr++] & 0xff) << 8; - flags0 |= buffer.buf[buffer.bufPtr++] & 0xff; - flags1 = (buffer.buf[buffer.bufPtr++] & 0xff) << 8; - flags1 |= buffer.buf[buffer.bufPtr++] & 0xff; - transform = buffer.buf[buffer.bufPtr++] & 0xff; + int markPtr = buffer.bufPtr; + markPtr += ID_SIZE; // Skip the id + version = (buffer.buf[markPtr++] & 0xff) << 8; + version |= buffer.buf[markPtr++] & 0xff; + flags0 = (buffer.buf[markPtr++] & 0xff) << 8; + flags0 |= buffer.buf[markPtr++] & 0xff; + flags1 = (buffer.buf[markPtr++] & 0xff) << 8; + flags1 |= buffer.buf[markPtr++] & 0xff; + transform = buffer.buf[markPtr++] & 0xff; buffer.bufAvail -= length; + buffer.bufPtr += length; } AdobeMarkerSegment(Node node) throws IIOInvalidTreeException { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/png/PNGImageReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -668,18 +668,9 @@ private static byte[] inflate(byte[] b) throws IOException { InputStream bais = new ByteArrayInputStream(b); - InputStream iis = new InflaterInputStream(bais); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - int c; - try { - while ((c = iis.read()) != -1) { - baos.write(c); - } - } finally { - iis.close(); + try (InputStream iis = new InflaterInputStream(bais)) { + return iis.readAllBytes(); } - return baos.toByteArray(); } private void parse_zTXt_chunk(int chunkLength) throws IOException { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/imageio/plugins/wbmp/WBMPImageReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -244,8 +244,8 @@ } // If noTransform is necessary, read the data. - iis.read(((DataBufferByte)tile.getDataBuffer()).getData(), - 0, height*sm.getScanlineStride()); + iis.readFully(((DataBufferByte)tile.getDataBuffer()).getData(), + 0, height*sm.getScanlineStride()); processImageUpdate(bi, 0, 0, width, height, 1, 1, @@ -280,7 +280,7 @@ if (abortRequested()) break; - iis.read(buf, 0, len); + iis.readFully(buf, 0, len); for (int i = 0; i < destinationRegion.width; i++) { //get the bit and assign to the data buffer of the raster int v = (buf[srcPos[i]] >> srcOff[i]) & 1; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java 2025-04-09 19:45:33.000000000 +0000 @@ -583,15 +583,16 @@ URL url = new URL(new File(userHome).toURI().toURL(), ".gconf/apps/metacity/general/%25gconf.xml"); // Pending: verify character encoding spec for gconf - Reader reader = new InputStreamReader(url.openStream(), - ISO_8859_1); - char[] buf = new char[1024]; StringBuilder sb = new StringBuilder(); - int n; - while ((n = reader.read(buf)) >= 0) { - sb.append(buf, 0, n); + try (InputStream in = url.openStream(); + Reader reader = new InputStreamReader(in, ISO_8859_1)) + { + char[] buf = new char[1024]; + int n; + while ((n = reader.read(buf)) >= 0) { + sb.append(buf, 0, n); + } } - reader.close(); String str = sb.toString(); if (str != null) { String strLowerCase = str.toLowerCase(); diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/AudioFileSoundbankReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -48,10 +48,8 @@ @Override public Soundbank getSoundbank(URL url) throws InvalidMidiDataException, IOException { - try { - AudioInputStream ais = AudioSystem.getAudioInputStream(url); + try (AudioInputStream ais = AudioSystem.getAudioInputStream(url)) { Soundbank sbk = getSoundbank(ais); - ais.close(); return sbk; } catch (UnsupportedAudioFileException e) { return null; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/DLSSoundbank.java 2025-04-09 19:45:33.000000000 +0000 @@ -191,22 +191,16 @@ } public DLSSoundbank(URL url) throws IOException { - InputStream is = url.openStream(); - try { + try (InputStream is = url.openStream()) { readSoundbank(is); - } finally { - is.close(); } } public DLSSoundbank(File file) throws IOException { largeFormat = true; sampleFile = file; - InputStream is = new FileInputStream(file); - try { + try (InputStream is = new FileInputStream(file)) { readSoundbank(is); - } finally { - is.close(); } } @@ -875,15 +869,21 @@ } public void save(String name) throws IOException { - writeSoundbank(new RIFFWriter(name, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(name, "DLS ")) { + writeSoundbank(writer); + } } public void save(File file) throws IOException { - writeSoundbank(new RIFFWriter(file, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(file, "DLS ")) { + writeSoundbank(writer); + } } public void save(OutputStream out) throws IOException { - writeSoundbank(new RIFFWriter(out, "DLS ")); + try (RIFFWriter writer = new RIFFWriter(out, "DLS ")) { + writeSoundbank(writer); + } } private void writeSoundbank(RIFFWriter writer) throws IOException { @@ -923,8 +923,6 @@ writer.seek(bak); writeInfo(writer.writeList("INFO"), info); - - writer.close(); } private void writeSample(RIFFWriter writer, DLSSample sample) diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -63,8 +63,7 @@ private static boolean isZIP(URL url) { boolean ok = false; try { - InputStream stream = url.openStream(); - try { + try (InputStream stream = url.openStream()) { byte[] buff = new byte[4]; ok = stream.read(buff) == 4; if (ok) { @@ -73,8 +72,6 @@ && buff[2] == 0x03 && buff[3] == 0x04); } - } finally { - stream.close(); } } catch (IOException e) { } @@ -95,8 +92,7 @@ "META-INF/services/javax.sound.midi.Soundbank"); if (stream == null) return null; - try - { + try (stream) { BufferedReader r = new BufferedReader(new InputStreamReader(stream)); String line = r.readLine(); while (line != null) { @@ -114,10 +110,6 @@ line = r.readLine(); } } - finally - { - stream.close(); - } if (soundbanks.size() == 0) return null; if (soundbanks.size() == 1) diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBuffer.java 2025-04-09 19:45:33.000000000 +0000 @@ -315,11 +315,13 @@ "No file associated with this ByteBuffer!"); } - DataInputStream is = new DataInputStream(getInputStream()); - buffer = new byte[(int) capacity()]; - offset = 0; - is.readFully(buffer); - is.close(); + try (InputStream is = getInputStream(); + DataInputStream dis = new DataInputStream(is)) + { + buffer = new byte[(int) capacity()]; + offset = 0; + dis.readFully(buffer); + } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/ModelByteBufferWavetable.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -182,18 +182,12 @@ if (format == null) { if (buffer == null) return null; - InputStream is = buffer.getInputStream(); AudioFormat format = null; - try { + try (InputStream is = buffer.getInputStream()) { format = AudioSystem.getAudioFileFormat(is).getFormat(); } catch (Exception e) { //e.printStackTrace(); } - try { - is.close(); - } catch (IOException e) { - //e.printStackTrace(); - } return format; } return format; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SF2Soundbank.java 2025-04-09 19:45:33.000000000 +0000 @@ -92,23 +92,16 @@ } public SF2Soundbank(URL url) throws IOException { - - InputStream is = url.openStream(); - try { + try (InputStream is = url.openStream()) { readSoundbank(is); - } finally { - is.close(); } } public SF2Soundbank(File file) throws IOException { largeFormat = true; sampleFile = file; - InputStream is = new FileInputStream(file); - try { + try (InputStream is = new FileInputStream(file)) { readSoundbank(is); - } finally { - is.close(); } } @@ -517,22 +510,27 @@ } public void save(String name) throws IOException { - writeSoundbank(new RIFFWriter(name, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(name, "sfbk")) { + writeSoundbank(writer); + } } public void save(File file) throws IOException { - writeSoundbank(new RIFFWriter(file, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(file, "sfbk")) { + writeSoundbank(writer); + } } public void save(OutputStream out) throws IOException { - writeSoundbank(new RIFFWriter(out, "sfbk")); + try (RIFFWriter writer = new RIFFWriter(out, "sfbk")) { + writeSoundbank(writer); + } } private void writeSoundbank(RIFFWriter writer) throws IOException { writeInfo(writer.writeList("INFO")); writeSdtaChunk(writer.writeList("sdta")); writePdtaChunk(writer.writeList("pdta")); - writer.close(); } private void writeInfoStringChunk(RIFFWriter writer, String name, diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/SoftSynthesizer.java 2025-04-09 19:45:33.000000000 +0000 @@ -755,10 +755,8 @@ InputStream is = AccessController.doPrivileged(action); if(is == null) continue; Soundbank sbk; - try { + try (is) { sbk = MidiSystem.getSoundbank(new BufferedInputStream(is)); - } finally { - is.close(); } if (sbk != null) { defaultSoundBank = sbk; @@ -802,9 +800,8 @@ return null; }); if (out != null) { - try { + try (out) { ((SF2Soundbank) defaultSoundBank).save(out); - out.close(); } catch (final IOException ignored) { } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -146,34 +146,27 @@ @Override public MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException { - InputStream urlStream = url.openStream(); // throws IOException - BufferedInputStream bis = new BufferedInputStream( urlStream, bisBufferSize ); - MidiFileFormat fileFormat = null; - try { - fileFormat = getMidiFileFormat( bis ); // throws InvalidMidiDataException - } finally { - bis.close(); + try (InputStream urlStream = url.openStream(); // throws IOException + BufferedInputStream bis = new BufferedInputStream(urlStream, bisBufferSize)) + { + MidiFileFormat fileFormat = getMidiFileFormat(bis); // throws InvalidMidiDataException + return fileFormat; } - return fileFormat; } @Override public MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException { - FileInputStream fis = new FileInputStream(file); // throws IOException - BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize); - - // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length - long length = file.length(); - if (length > Integer.MAX_VALUE) { - length = MidiFileFormat.UNKNOWN_LENGTH; - } - MidiFileFormat fileFormat = null; - try { - fileFormat = getMidiFileFormatFromStream(bis, (int) length, null); - } finally { - bis.close(); + try (FileInputStream fis = new FileInputStream(file); // throws IOException + BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize)) + { + // $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length + long length = file.length(); + if (length > Integer.MAX_VALUE) { + length = MidiFileFormat.UNKNOWN_LENGTH; + } + MidiFileFormat fileFormat = getMidiFileFormatFromStream(bis, (int) length, null); + return fileFormat; } - return fileFormat; } @Override @@ -204,28 +197,22 @@ @Override public Sequence getSequence(URL url) throws InvalidMidiDataException, IOException { - InputStream is = url.openStream(); // throws IOException - is = new BufferedInputStream(is, bisBufferSize); - Sequence seq = null; - try { - seq = getSequence(is); - } finally { - is.close(); + try (InputStream is = url.openStream(); // throws IOException + BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize)) + { + Sequence seq = getSequence(bis); + return seq; } - return seq; } @Override public Sequence getSequence(File file) throws InvalidMidiDataException, IOException { - InputStream is = new FileInputStream(file); // throws IOException - is = new BufferedInputStream(is, bisBufferSize); - Sequence seq = null; - try { - seq = getSequence(is); - } finally { - is.close(); + try (InputStream is = new FileInputStream(file); // throws IOException + BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize)) + { + Sequence seq = getSequence(bis); + return seq; } - return seq; } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/com/sun/media/sound/StandardMidiFileWriter.java 2025-04-09 19:45:33.000000000 +0000 @@ -129,10 +129,10 @@ @Override public int write(Sequence in, int type, File out) throws IOException { Objects.requireNonNull(in); - FileOutputStream fos = new FileOutputStream(out); // throws IOException - int bytesWritten = write( in, type, fos ); - fos.close(); - return bytesWritten; + try (FileOutputStream fos = new FileOutputStream(out)) { // throws IOException + int bytesWritten = write(in, type, fos); + return bytesWritten; + } } //================================================================================= diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/awt/Font.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Font.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/awt/Font.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Font.java 2025-04-09 19:45:33.000000000 +0000 @@ -1131,7 +1131,7 @@ if (tracker != null) { tracker.set(tFile, outStream); } - try { + try (outStream) { /* don't close the input stream */ byte[] buf = new byte[8192]; for (;;) { int bytesRead = fontStream.read(buf); @@ -1152,9 +1152,6 @@ } outStream.write(buf, 0, bytesRead); } - /* don't close the input stream */ - } finally { - outStream.close(); } /* After all references to a Font2D are dropped, the file * will be removed. To support long-lived AppContexts, diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/awt/Toolkit.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Toolkit.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/awt/Toolkit.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/awt/Toolkit.java 2025-04-09 19:45:33.000000000 +0000 @@ -413,12 +413,10 @@ File propsFile = new File( System.getProperty("user.home") + sep + ".accessibility.properties"); - FileInputStream in = - new FileInputStream(propsFile); - - // Inputstream has been buffered in Properties class - properties.load(in); - in.close(); + try (FileInputStream in = new FileInputStream(propsFile)) { + // Inputstream has been buffered in Properties class + properties.load(in); + } } catch (Exception e) { // Per-user accessibility properties file does not exist } @@ -431,12 +429,10 @@ File propsFile = new File( System.getProperty("java.home") + sep + "conf" + sep + "accessibility.properties"); - FileInputStream in = - new FileInputStream(propsFile); - - // Inputstream has been buffered in Properties class - properties.load(in); - in.close(); + try (FileInputStream in = new FileInputStream(propsFile)) { + // Inputstream has been buffered in Properties class + properties.load(in); + } } catch (Exception e) { // System-wide accessibility properties file does // not exist; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/beans/Beans.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/beans/Beans.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/java/beans/Beans.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/java/beans/Beans.java 2025-04-09 19:45:33.000000000 +0000 @@ -201,7 +201,7 @@ else ins = cls.getResourceAsStream(serName); if (ins != null) { - try { + try (ins) { if (cls == null) { oins = new ObjectInputStream(ins); } else { @@ -211,13 +211,9 @@ serialized = true; oins.close(); } catch (IOException ex) { - ins.close(); // Drop through and try opening the class. But remember // the exception in case we can't find the class either. serex = ex; - } catch (ClassNotFoundException ex) { - ins.close(); - throw ex; } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/imageio/ImageIO.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/imageio/ImageIO.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/imageio/ImageIO.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/imageio/ImageIO.java 2025-04-09 19:45:33.000000000 +0000 @@ -39,8 +39,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Set; import javax.imageio.spi.IIORegistry; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageReaderWriterSpi; @@ -1402,7 +1400,7 @@ throw new IllegalArgumentException("input == null!"); } - InputStream istream = null; + InputStream istream; try { istream = input.openStream(); } catch (IOException e) { @@ -1418,13 +1416,11 @@ throw new IIOException("Can't create an ImageInputStream!"); } BufferedImage bi; - try { + try (istream) { bi = read(stream); if (bi == null) { stream.close(); } - } finally { - istream.close(); } return bi; } @@ -1466,13 +1462,12 @@ ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(stream, true, true); BufferedImage bi; - try { + try (stream) { bi = reader.read(0, param); } catch (RuntimeException e) { throw new IIOException(e.toString(), e); } finally { reader.dispose(); - stream.close(); } return bi; } @@ -1554,10 +1549,8 @@ if (stream == null) { throw new IIOException("Can't create an ImageOutputStream!"); } - try { + try (stream) { return doWrite(im, writer, stream); - } finally { - stream.close(); } } @@ -1594,10 +1587,8 @@ if (stream == null) { throw new IIOException("Can't create an ImageOutputStream!"); } - try { + try (stream) { return doWrite(im, getWriter(im, formatName), stream); - } finally { - stream.close(); } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/JEditorPane.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JEditorPane.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/JEditorPane.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JEditorPane.java 2025-04-09 19:45:33.000000000 +0000 @@ -41,6 +41,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; +import java.io.OutputStream; import java.io.Reader; import java.io.Serial; import java.io.StringReader; @@ -854,16 +855,12 @@ private void handlePostData(HttpURLConnection conn, Object postData) throws IOException { conn.setDoOutput(true); - DataOutputStream os = null; - try { - conn.setRequestProperty("Content-Type", - "application/x-www-form-urlencoded"); - os = new DataOutputStream(conn.getOutputStream()); - os.writeBytes((String) postData); - } finally { - if (os != null) { - os.close(); - } + conn.setRequestProperty("Content-Type", + "application/x-www-form-urlencoded"); + try (OutputStream os = conn.getOutputStream(); + DataOutputStream dos = new DataOutputStream(os)) + { + dos.writeBytes((String)postData); } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/JTabbedPane.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JTabbedPane.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/JTabbedPane.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/JTabbedPane.java 2025-04-09 19:45:33.000000000 +0000 @@ -55,6 +55,7 @@ import javax.accessibility.AccessibleSelection; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; +import javax.accessibility.AccessibleValue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.TabbedPaneUI; @@ -2074,7 +2075,7 @@ } private class Page extends AccessibleContext - implements Serializable, Accessible, AccessibleComponent { + implements Serializable, Accessible, AccessibleComponent, AccessibleValue { String title; Color background; Color foreground; @@ -2168,7 +2169,6 @@ return this; } - // AccessibleContext methods public String getAccessibleName() { @@ -2202,6 +2202,43 @@ return states; } + @Override + public AccessibleValue getAccessibleValue() { + return this; + } + + @Override + public Number getCurrentAccessibleValue() { + return (getPageIndex() == parent.getSelectedIndex() ? + Integer.valueOf(1) : Integer.valueOf(0)); + } + + @Override + public boolean setCurrentAccessibleValue(Number n) { + if (getPageIndex() != parent.getSelectedIndex()) { + if (n.intValue() != 0) { + // Set current page selected + parent.setSelectedIndex(getPageIndex()); + } + } else { + if (n.intValue() == 0) { + // Can not "deselect" because what page should i select instead? + return false; + } + } + return true; + } + + @Override + public Number getMinimumAccessibleValue() { + return Integer.valueOf(0); + } + + @Override + public Number getMaximumAccessibleValue() { + return Integer.valueOf(1); + } + public int getAccessibleIndexInParent() { return getPageIndex(); } @@ -2368,7 +2405,7 @@ * one exists and the page is disabled. Otherwise, null * is returned. */ - public AccessibleIcon [] getAccessibleIcon() { + public AccessibleIcon[] getAccessibleIcon() { AccessibleIcon accessibleIcon = null; if (enabled && icon instanceof ImageIcon) { AccessibleContext ac = diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/UIManager.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/UIManager.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/UIManager.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/UIManager.java 2025-04-09 19:45:33.000000000 +0000 @@ -57,7 +57,6 @@ import sun.awt.OSInfo; import sun.security.action.GetPropertyAction; import sun.swing.SwingUtilities2; -import java.lang.reflect.Method; import java.util.HashMap; import java.util.Objects; import sun.awt.AppContext; @@ -1301,9 +1300,9 @@ if (file.exists()) { // InputStream has been buffered in Properties // class - FileInputStream ins = new FileInputStream(file); - props.load(ins); - ins.close(); + try (FileInputStream ins = new FileInputStream(file)) { + props.load(ins); + } } } catch (Exception e) { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -366,6 +366,8 @@ } } + private int savedBlinkRate = 0; + private boolean isBlinkRateSaved = false; // --- FocusListener methods -------------------------- /** @@ -379,8 +381,21 @@ public void focusGained(FocusEvent e) { if (component.isEnabled()) { if (component.isEditable()) { - setVisible(true); + if (isBlinkRateSaved) { + setBlinkRate(savedBlinkRate); + savedBlinkRate = 0; + isBlinkRateSaved = false; + } + } else { + if (getBlinkRate() != 0) { + if (!isBlinkRateSaved) { + savedBlinkRate = getBlinkRate(); + isBlinkRateSaved = true; + } + setBlinkRate(0); + } } + setVisible(true); setSelectionVisible(true); updateSystemSelection(); } @@ -1031,17 +1046,29 @@ * @see Caret#setBlinkRate */ public void setBlinkRate(int rate) { + if (rate < 0) { + throw new IllegalArgumentException("Invalid blink rate: " + rate); + } if (rate != 0) { - if (flasher == null) { - flasher = new Timer(rate, handler); + if (component != null && component.isEditable()) { + if (flasher == null) { + flasher = new Timer(rate, handler); + } + flasher.setDelay(rate); + } else { + savedBlinkRate = rate; + isBlinkRateSaved = true; } - flasher.setDelay(rate); } else { if (flasher != null) { flasher.stop(); flasher.removeActionListener(handler); flasher = null; } + if ((component == null || component.isEditable()) && isBlinkRateSaved) { + savedBlinkRate = 0; + isBlinkRateSaved = false; + } } } @@ -1053,6 +1080,9 @@ * @see Caret#getBlinkRate */ public int getBlinkRate() { + if (isBlinkRateSaved) { + return savedBlinkRate; + } return (flasher == null) ? 0 : flasher.getDelay(); } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java 2025-04-09 19:45:33.000000000 +0000 @@ -456,12 +456,11 @@ if (defaultStyles == null) { defaultStyles = new StyleSheet(); appContext.put(DEFAULT_STYLES_KEY, defaultStyles); - try { - InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS); - Reader r = new BufferedReader( - new InputStreamReader(is, ISO_8859_1)); + try (InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS); + InputStreamReader isr = new InputStreamReader(is, ISO_8859_1); + Reader r = new BufferedReader(isr)) + { defaultStyles.loadRules(r, null); - r.close(); } catch (Throwable e) { // on error we simply have no styles... the html // will look mighty wrong but still function. diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/javax/swing/text/html/StyleSheet.java 2025-04-09 19:45:33.000000000 +0000 @@ -514,15 +514,12 @@ * @since 1.3 */ public void importStyleSheet(URL url) { - try { - InputStream is; - - is = url.openStream(); - Reader r = new BufferedReader(new InputStreamReader(is)); + try (InputStream is = url.openStream(); + InputStreamReader isr = new InputStreamReader(is); + Reader r = new BufferedReader(isr)) + { CssParser parser = new CssParser(); parser.parse(url, r, false, true); - r.close(); - is.close(); } catch (Throwable e) { // on error we simply have no styles... the html // will look mighty wrong but still function. diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/awt/DebugSettings.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/DebugSettings.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/awt/DebugSettings.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/DebugSettings.java 2025-04-09 19:45:33.000000000 +0000 @@ -173,9 +173,9 @@ File propFile = new File(propPath); try { println("Reading debug settings from '" + propFile.getCanonicalPath() + "'..."); - FileInputStream fin = new FileInputStream(propFile); - props.load(fin); - fin.close(); + try (FileInputStream fin = new FileInputStream(propFile)) { + props.load(fin); + } } catch ( FileNotFoundException fne ) { println("Did not find settings file."); } catch ( IOException ioe ) { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/awt/FontConfiguration.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/FontConfiguration.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/awt/FontConfiguration.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/awt/FontConfiguration.java 2025-04-09 19:45:33.000000000 +0000 @@ -48,7 +48,6 @@ import java.util.Vector; import sun.font.CompositeFontDescriptor; import sun.font.SunFontManager; -import sun.font.FontManagerFactory; import sun.font.FontUtilities; import sun.util.logging.PlatformLogger; @@ -204,14 +203,12 @@ getInstalledFallbackFonts(javaLib); if (f != null) { - try { - FileInputStream in = new FileInputStream(f.getPath()); + try (FileInputStream in = new FileInputStream(f.getPath())) { if (isProperties) { loadProperties(in); } else { loadBinary(in); } - in.close(); if (FontUtilities.debugFonts()) { logger.config("Read logical font configuration from " + f); } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/print/PSPrinterJob.java openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/print/PSPrinterJob.java --- openjdk-17-17.0.14+7/src/java.desktop/share/classes/sun/print/PSPrinterJob.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/classes/sun/print/PSPrinterJob.java 2025-04-09 19:45:33.000000000 +0000 @@ -393,11 +393,12 @@ } // Load property file - InputStream in = - new BufferedInputStream(new FileInputStream(f.getPath())); Properties props = new Properties(); - props.load(in); - in.close(); + try (FileInputStream is = new FileInputStream(f.getPath()); + BufferedInputStream bis = new BufferedInputStream(is)) + { + props.load(bis); + } return props; } catch (Exception e){ return (Properties)null; diff -Nru openjdk-17-17.0.14+7/src/java.desktop/share/native/libawt/java2d/loops/Blit.c openjdk-17-17.0.15+6/src/java.desktop/share/native/libawt/java2d/loops/Blit.c --- openjdk-17-17.0.14+7/src/java.desktop/share/native/libawt/java2d/loops/Blit.c 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/share/native/libawt/java2d/loops/Blit.c 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,14 +68,30 @@ return; } + if (width <= 0 || height <= 0) { + return; + } + srcInfo.bounds.x1 = srcx; srcInfo.bounds.y1 = srcy; + if (UNSAFE_TO_ADD(srcx, width) || + UNSAFE_TO_ADD(srcy, height) || + UNSAFE_TO_ADD(dstx, width) || + UNSAFE_TO_ADD(dsty, height)) { + return; + } + srcInfo.bounds.x2 = srcx + width; srcInfo.bounds.y2 = srcy + height; dstInfo.bounds.x1 = dstx; dstInfo.bounds.y1 = dsty; dstInfo.bounds.x2 = dstx + width; dstInfo.bounds.y2 = dsty + height; + if (UNSAFE_TO_SUB(srcx, dstx) || + UNSAFE_TO_SUB(srcy, dsty)) { + return; + } + srcx -= dstx; srcy -= dsty; SurfaceData_IntersectBounds(&dstInfo.bounds, &clipInfo.bounds); diff -Nru openjdk-17-17.0.14+7/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java --- openjdk-17-17.0.14+7/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/FcFontConfiguration.java 2025-04-09 19:45:33.000000000 +0000 @@ -320,7 +320,9 @@ * For Ubuntu the ID is "Ubuntu". */ Properties props = new Properties(); - props.load(new FileInputStream(f)); + try (FileInputStream fis = new FileInputStream(f)) { + props.load(fis); + } osName = props.getProperty("DISTRIB_ID"); osVersion = props.getProperty("DISTRIB_RELEASE"); } else if ((f = new File("/etc/redhat-release")).canRead()) { @@ -417,10 +419,9 @@ File dir = fcInfoFile.getParentFile(); dir.mkdirs(); File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile(); - FileOutputStream fos = new FileOutputStream(tempFile); - props.store(fos, - "JDK Font Configuration Generated File: *Do Not Edit*"); - fos.close(); + try (FileOutputStream fos = new FileOutputStream(tempFile)) { + props.store(fos, "JDK Font Configuration Generated File: *Do Not Edit*"); + } boolean renamed = tempFile.renameTo(fcInfoFile); if (!renamed && FontUtilities.debugFonts()) { System.out.println("rename failed"); diff -Nru openjdk-17-17.0.14+7/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java --- openjdk-17-17.0.14+7/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/unix/classes/sun/font/MFontConfiguration.java 2025-04-09 19:45:33.000000000 +0000 @@ -27,8 +27,6 @@ import sun.awt.FontConfiguration; import sun.awt.X11FontManager; -import sun.font.FontUtilities; -import sun.font.SunFontManager; import sun.util.logging.PlatformLogger; import java.io.File; @@ -109,7 +107,9 @@ * For Ubuntu the ID is "Ubuntu". */ Properties props = new Properties(); - props.load(new FileInputStream(f)); + try (FileInputStream fis = new FileInputStream(f)) { + props.load(fis); + } osName = props.getProperty("DISTRIB_ID"); osVersion = props.getProperty("DISTRIB_RELEASE"); } else if ((f = new File("/etc/os-release")).canRead()) { diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/classes/sun/awt/PlatformGraphicsInfo.java openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/PlatformGraphicsInfo.java --- openjdk-17-17.0.14+7/src/java.desktop/windows/classes/sun/awt/PlatformGraphicsInfo.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/PlatformGraphicsInfo.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,41 +28,20 @@ import java.awt.GraphicsEnvironment; import java.awt.Toolkit; -import sun.awt.windows.WToolkit; - public class PlatformGraphicsInfo { - private static final boolean hasDisplays; - - static { - loadAWTLibrary(); - hasDisplays = hasDisplays0(); - } - - @SuppressWarnings("removal") - private static void loadAWTLibrary() { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - System.loadLibrary("awt"); - return null; - } - }); - } - - private static native boolean hasDisplays0(); - public static GraphicsEnvironment createGE() { return new Win32GraphicsEnvironment(); } public static Toolkit createToolkit() { - return new WToolkit(); + return new sun.awt.windows.WToolkit(); } public static boolean getDefaultHeadlessProperty() { - // If we don't find usable displays, we run headless. - return !hasDisplays; + // On Windows, we assume we can always create headful apps. + // Here is where we can add code that would actually check. + return false; } /* diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/classes/sun/awt/Win32GraphicsEnvironment.java openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/Win32GraphicsEnvironment.java --- openjdk-17-17.0.14+7/src/java.desktop/windows/classes/sun/awt/Win32GraphicsEnvironment.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/classes/sun/awt/Win32GraphicsEnvironment.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -60,8 +60,7 @@ WToolkit.loadLibraries(); // setup flags before initializing native layer WindowsFlags.initFlags(); - - initDisplay(); + initDisplayWrapper(); // Install correct surface manager factory. SurfaceManagerFactory.setInstance(new WindowsSurfaceManagerFactory()); @@ -89,6 +88,14 @@ */ private static native void initDisplay(); + private static boolean displayInitialized; // = false; + public static void initDisplayWrapper() { + if (!displayInitialized) { + displayInitialized = true; + initDisplay(); + } + } + public Win32GraphicsEnvironment() { } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/Devices.cpp openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.cpp --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/Devices.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -85,75 +85,60 @@ #include "Trace.h" #include "D3DPipelineManager.h" -typedef struct { - int monitorCounter; - int monitorLimit; - HMONITOR* hmpMonitors; -} MonitorData; +/* Some helper functions (from awt_MMStub.h/cpp) */ -// Only monitors where CreateDC does not fail are valid -static BOOL IsValidMonitor(HMONITOR hMon) -{ - MONITORINFOEX mieInfo; - memset((void*)(&mieInfo), 0, sizeof(MONITORINFOEX)); - mieInfo.cbSize = sizeof(MONITORINFOEX); - if (!::GetMonitorInfo(hMon, (LPMONITORINFOEX)(&mieInfo))) { - J2dTraceLn1(J2D_TRACE_INFO, "Devices::IsValidMonitor: GetMonitorInfo failed for monitor with handle %p", hMon); - return FALSE; - } - - HDC hDC = CreateDC(mieInfo.szDevice, NULL, NULL, NULL); - if (NULL == hDC) { - J2dTraceLn2(J2D_TRACE_INFO, "Devices::IsValidMonitor: CreateDC failed for monitor with handle %p, device: %S", hMon, mieInfo.szDevice); - return FALSE; - } - - ::DeleteDC(hDC); - return TRUE; -} +int g_nMonitorCounter; +int g_nMonitorLimit; +HMONITOR* g_hmpMonitors; // Callback for CountMonitors below -static BOOL WINAPI clb_fCountMonitors(HMONITOR hMon, HDC hDC, LPRECT rRect, LPARAM lpMonitorCounter) +BOOL WINAPI clb_fCountMonitors(HMONITOR hMon, HDC hDC, LPRECT rRect, LPARAM lP) { - if (IsValidMonitor(hMon)) { - (*((int *)lpMonitorCounter))++; - } - + g_nMonitorCounter ++; return TRUE; } int WINAPI CountMonitors(void) { - int monitorCounter = 0; - ::EnumDisplayMonitors(NULL, NULL, clb_fCountMonitors, (LPARAM)&monitorCounter); - return monitorCounter; + g_nMonitorCounter = 0; + ::EnumDisplayMonitors(NULL, NULL, clb_fCountMonitors, 0L); + return g_nMonitorCounter; + } // Callback for CollectMonitors below -static BOOL WINAPI clb_fCollectMonitors(HMONITOR hMon, HDC hDC, LPRECT rRect, LPARAM lpMonitorData) +BOOL WINAPI clb_fCollectMonitors(HMONITOR hMon, HDC hDC, LPRECT rRect, LPARAM lP) { - MonitorData* pMonitorData = (MonitorData *)lpMonitorData; - if ((pMonitorData->monitorCounter < pMonitorData->monitorLimit) && (IsValidMonitor(hMon))) { - pMonitorData->hmpMonitors[pMonitorData->monitorCounter] = hMon; - pMonitorData->monitorCounter++; + + if ((g_nMonitorCounter < g_nMonitorLimit) && (NULL != g_hmpMonitors)) { + g_hmpMonitors[g_nMonitorCounter] = hMon; + g_nMonitorCounter ++; } return TRUE; } -static int WINAPI CollectMonitors(HMONITOR* hmpMonitors, int nNum) +int WINAPI CollectMonitors(HMONITOR* hmpMonitors, int nNum) { + int retCode = 0; + if (NULL != hmpMonitors) { - MonitorData monitorData; - monitorData.monitorCounter = 0; - monitorData.monitorLimit = nNum; - monitorData.hmpMonitors = hmpMonitors; - ::EnumDisplayMonitors(NULL, NULL, clb_fCollectMonitors, (LPARAM)&monitorData); - return monitorData.monitorCounter; - } else { - return 0; + + g_nMonitorCounter = 0; + g_nMonitorLimit = nNum; + g_hmpMonitors = hmpMonitors; + + ::EnumDisplayMonitors(NULL, NULL, clb_fCollectMonitors, 0L); + + retCode = g_nMonitorCounter; + + g_nMonitorCounter = 0; + g_nMonitorLimit = 0; + g_hmpMonitors = NULL; + } + return retCode; } BOOL WINAPI MonitorBounds(HMONITOR hmMonitor, RECT* rpBounds) diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/Devices.h openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.h --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/Devices.h 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/Devices.h 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,6 +74,4 @@ BOOL WINAPI MonitorBounds (HMONITOR, RECT*); -int WINAPI CountMonitors (void); - #endif // _DEVICES_H_ diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -242,7 +242,7 @@ RECT focusRect; VERIFY(::CopyRect(&focusRect, &rect)); VERIFY(::InflateRect(&focusRect,-inf,-inf)); - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -290,13 +290,13 @@ if ((drawInfo.itemState & ODS_FOCUS) && ((drawInfo.itemAction & ODA_FOCUS)|| (drawInfo.itemAction &ODA_DRAWENTIRE))) { - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } /* erase focus rect */ else if (!(drawInfo.itemState & ODS_FOCUS) && (drawInfo.itemAction & ODA_FOCUS)) { - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -4499,7 +4499,7 @@ if ((drawInfo.itemState & ODS_FOCUS) && (drawInfo.itemAction & (ODA_FOCUS | ODA_DRAWENTIRE))) { if (!unfocusableChoice){ - if(::DrawFocusRect(hDC, &rect) == 0) + if (!::IsRectEmpty(&rect) && (::DrawFocusRect(hDC, &rect) == 0)) VERIFY(::GetLastError() == 0); } } diff -Nru openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_PlatformGraphicsInfo.cpp openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_PlatformGraphicsInfo.cpp --- openjdk-17-17.0.14+7/src/java.desktop/windows/native/libawt/windows/awt_PlatformGraphicsInfo.cpp 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.desktop/windows/native/libawt/windows/awt_PlatformGraphicsInfo.cpp 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2024 SAP SE. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#include -#include "Devices.h" - -/* - * Class: sun_awt_PlatformGraphicsInfo - * Method: hasDisplays0 - * Signature: ()Z - */ -JNIEXPORT jboolean JNICALL -Java_sun_awt_PlatformGraphicsInfo_hasDisplays0(JNIEnv *env, jclass thisClass) { - return CountMonitors() > 0 ? JNI_TRUE : JNI_FALSE; -} diff -Nru openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java --- openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5Context.java 2025-04-09 19:45:33.000000000 +0000 @@ -33,8 +33,10 @@ import sun.security.jgss.TokenTracker; import sun.security.krb5.*; import java.io.InputStream; -import java.io.OutputStream; +import java.io.InvalidObjectException; import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.OutputStream; import java.security.Provider; import java.security.AccessController; import java.security.AccessControlContext; @@ -1416,6 +1418,20 @@ return "Kerberos session key: etype=" + key.getEType() + ", " + Krb5Util.keyInfo(key.getBytes()); } + + /** + * Restores the state of this object from the stream. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) + throws IOException, ClassNotFoundException { + throw new InvalidObjectException + ("KerberosSessionKey not directly deserializable"); + } } /** @@ -1485,5 +1501,4 @@ public void setAuthzData(AuthorizationData authzData) { this.authzData = authzData; } - } diff -Nru openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java --- openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,9 @@ import javax.security.auth.kerberos.KerberosTicket; import javax.security.auth.kerberos.KerberosPrincipal; import java.net.InetAddress; +import java.io.InvalidObjectException; import java.io.IOException; +import java.io.ObjectInputStream; import java.util.Date; import java.security.AccessController; import java.security.AccessControlContext; @@ -405,4 +407,17 @@ throw ge; } } + + /** + * Restores the state of this object from the stream. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) + throws IOException, ClassNotFoundException { + throw new InvalidObjectException("Krb5InitCredential not deserializable"); + } } diff -Nru openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBError.java openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBError.java --- openjdk-17-17.0.14+7/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBError.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/java.security.jgss/share/classes/sun/security/krb5/internal/KRBError.java 2025-04-09 19:45:33.000000000 +0000 @@ -79,30 +79,38 @@ * * http://www.ietf.org/rfc/rfc4120.txt. */ -// The instance fields not statically typed as Serializable are ASN.1 -// encoded and written by the writeObject method. -@SuppressWarnings("serial") + public class KRBError implements java.io.Serializable { static final long serialVersionUID = 3643809337475284503L; - private int pvno; - private int msgType; - private KerberosTime cTime; //optional - private Integer cuSec; //optional - private KerberosTime sTime; - private Integer suSec; - private int errorCode; - private Realm crealm; //optional - private PrincipalName cname; //optional - private PrincipalName sname; - private String eText; //optional - private byte[] eData; //optional - private Checksum eCksum; //optional + private transient int pvno; + private transient int msgType; + private transient KerberosTime cTime; //optional + private transient Integer cuSec; //optional + private transient KerberosTime sTime; + private transient Integer suSec; + private transient int errorCode; + private transient Realm crealm; //optional + private transient PrincipalName cname; //optional + private transient PrincipalName sname; + private transient String eText; //optional + private transient byte[] eData; //optional + private transient Checksum eCksum; //optional + + private transient PAData[] pa; // PA-DATA in eData + - private PAData[] pa; // PA-DATA in eData private static boolean DEBUG = Krb5.DEBUG; + /** + * Restores the state of this object from the stream. + * + * @param is the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException { try { diff -Nru openjdk-17-17.0.14+7/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java openjdk-17-17.0.15+6/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java --- openjdk-17-17.0.14+7/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.accessibility/windows/classes/com/sun/java/accessibility/internal/AccessBridge.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -3851,6 +3851,8 @@ return 0; int code = keyStroke.getKeyCode(); switch (code) { + case KeyEvent.VK_TAB: + case KeyEvent.VK_SPACE: case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_DOWN: @@ -3893,15 +3895,10 @@ debugString("[INFO]: Shortcut is control character: " + Integer.toHexString(keyCode)); return (char)keyCode; } - String keyText = KeyEvent.getKeyText(keyStroke.getKeyCode()); - debugString("[INFO]: Shortcut is: " + keyText); - if (keyText != null || keyText.length() > 0) { - CharSequence seq = keyText.subSequence(0, 1); - if (seq != null || seq.length() > 0) { - return seq.charAt(0); - } - } - return 0; + + keyCode = keyStroke.getKeyCode(); + debugString("[INFO]: Shortcut is: " + Integer.toHexString(keyCode)); + return (char)keyCode; } /* diff -Nru openjdk-17-17.0.14+7/src/jdk.accessibility/windows/native/include/bridge/AccessBridgePackages.h openjdk-17-17.0.15+6/src/jdk.accessibility/windows/native/include/bridge/AccessBridgePackages.h --- openjdk-17-17.0.14+7/src/jdk.accessibility/windows/native/include/bridge/AccessBridgePackages.h 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.accessibility/windows/native/include/bridge/AccessBridgePackages.h 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1108,6 +1108,8 @@ #define ACCESSIBLE_CONTROLCODE_KEYSTROKE 512 // Control code key pressed, character contains control code. // The supported control code keys are: +#define ACCESSIBLE_VK_TAB 9 +#define ACCESSIBLE_VK_SPACE 32 #define ACCESSIBLE_VK_BACK_SPACE 8 #define ACCESSIBLE_VK_DELETE 127 #define ACCESSIBLE_VK_DOWN 40 diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java --- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -127,6 +127,9 @@ // whether to print debug info during startup private boolean showInfo = false; + // whether to allow legacy mechanisms + private boolean allowLegacy = false; + // template manager, initialized from parsed attributes private TemplateManager templateManager; @@ -257,6 +260,10 @@ return (SunPKCS11.debug != null) || showInfo; } + boolean getAllowLegacy() { + return allowLegacy; + } + TemplateManager getTemplateManager() { if (templateManager == null) { templateManager = new TemplateManager(); @@ -450,6 +457,8 @@ destroyTokenAfterLogout = parseBooleanEntry(word); } else if (word.equals("showInfo")) { showInfo = parseBooleanEntry(word); + } else if (word.equals("allowLegacy")) { + allowLegacy = parseBooleanEntry(word); } else if (word.equals("keyStoreCompatibilityMode")) { keyStoreCompatibilityMode = parseBooleanEntry(word); } else if (word.equals("explicitCancel")) { diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java --- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java 2025-04-09 19:45:33.000000000 +0000 @@ -245,6 +245,19 @@ return new KeyRep(type, getAlgorithm(), format, getEncodedInternal()); } + /** + * Restores the state of this object from the stream. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) + throws IOException, ClassNotFoundException { + throw new InvalidObjectException("P11Key not directly deserializable"); + } + public String toString() { token.ensureValid(); String s1 = token.provider.getName() + " " + algorithm + " " + type diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11SecureRandom.java openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11SecureRandom.java --- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11SecureRandom.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11SecureRandom.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -189,9 +189,23 @@ } } + /** + * Restores the state of this object from the stream. + * + * @param in the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); + if (token == null) { + throw new InvalidObjectException("token is null"); + } + if (mixBuffer != null) { + mixBuffer = mixBuffer.clone(); + } // assign default values to non-null transient fields iBuffer = new byte[IBUFFER_SIZE]; ibuffered = 0; diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java --- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java 2025-04-09 19:45:33.000000000 +0000 @@ -1055,25 +1055,6 @@ } } - private static boolean isLegacy(CK_MECHANISM_INFO mechInfo) - throws PKCS11Exception { - // assume full support if no mech info available - // For vendor-specific mechanisms, often no mech info is provided - boolean partialSupport = false; - - if (mechInfo != null) { - if ((mechInfo.flags & CKF_DECRYPT) != 0) { - // non-legacy cipher mechs should support encryption - partialSupport |= ((mechInfo.flags & CKF_ENCRYPT) == 0); - } - if ((mechInfo.flags & CKF_VERIFY) != 0) { - // non-legacy signature mechs should support signing - partialSupport |= ((mechInfo.flags & CKF_SIGN) == 0); - } - } - return partialSupport; - } - // test if a token is present and initialize this provider for it if so. // does nothing if no token is found // called from constructor and by poller @@ -1124,12 +1105,6 @@ } continue; } - if (isLegacy(mechInfo)) { - if (showInfo) { - System.out.println("DISABLED due to legacy"); - } - continue; - } // we do not know of mechs with the upper 32 bits set if (longMech >>> 32 != 0) { @@ -1144,9 +1119,25 @@ if (ds == null) { continue; } + boolean allowLegacy = config.getAllowLegacy(); for (Descriptor d : ds) { Integer oldMech = supportedAlgs.get(d); if (oldMech == null) { + + // assume full support if no mech info available + if (!allowLegacy && mechInfo != null) { + if ((d.type == CIP && + (mechInfo.flags & CKF_ENCRYPT) == 0) || + (d.type == SIG && + (mechInfo.flags & CKF_SIGN) == 0)) { + if (showInfo) { + System.out.println("DISABLED " + d.type + + " " + d.algorithm + + " due to partial support"); + } + continue; + } + } supportedAlgs.put(d, integerMech); continue; } @@ -1724,6 +1715,19 @@ } /** + * Restores the state of this object from the stream. + * + * @param stream the {@code ObjectInputStream} from which data is read + * @throws IOException if an I/O error occurs + * @throws ClassNotFoundException if a serialized class cannot be loaded + */ + @java.io.Serial + private void readObject(ObjectInputStream stream) + throws IOException, ClassNotFoundException { + throw new InvalidObjectException("SunPKCS11 not directly deserializable"); + } + + /** * Serialized representation of the SunPKCS11 provider. */ private static class SunPKCS11Rep implements Serializable { diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md --- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md 2025-04-09 19:45:33.000000000 +0000 @@ -1,16 +1,16 @@ -## OASIS PKCS #11 Cryptographic Token Interface v3.0 +## OASIS PKCS #11 Cryptographic Token Interface v3.1 ### OASIS PKCS #11 Cryptographic Token Interface License

 
-Copyright © OASIS Open 2020. All Rights Reserved.
+Copyright © OASIS Open 2023. All Rights Reserved.
 
-    All capitalized terms in the following text have the meanings
+All capitalized terms in the following text have the meanings
 assigned to them in the OASIS Intellectual Property Rights Policy (the
 "OASIS IPR Policy"). The full Policy may be found at the OASIS website:
-[http://www.oasis-open.org/policies-guidelines/ipr]
+[https://www.oasis-open.org/policies-guidelines/ipr/].
 
-    This document and translations of it may be copied and furnished to
+This document and translations of it may be copied and furnished to
 others, and derivative works that comment on or otherwise explain it or
 assist in its implementation may be prepared, copied, published, and
 distributed, in whole or in part, without restriction of any kind,
@@ -23,10 +23,10 @@
 forth in the OASIS IPR Policy, must be followed) or as required to
 translate it into languages other than English.
 
-    The limited permissions granted above are perpetual and will not be
+The limited permissions granted above are perpetual and will not be
 revoked by OASIS or its successors or assigns.
 
-    This document and the information contained herein is provided on an
+This document and the information contained herein is provided on an
 "AS IS" basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
 INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED
@@ -35,7 +35,11 @@
 CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THIS DOCUMENT OR ANY
 PART THEREOF.
 
-    [OASIS requests that any OASIS Party or any other party that
+As stated in the OASIS IPR Policy, the following three paragraphs in
+brackets apply to OASIS Standards Final Deliverable documents (Committee
+Specifications, OASIS Standards, or Approved Errata).
+
+[OASIS requests that any OASIS Party or any other party that
 believes it has patent claims that would necessarily be infringed by
 implementations of this OASIS Standards Final Deliverable, to notify
 OASIS TC Administrator and provide an indication of its willingness to
@@ -43,7 +47,7 @@
 the IPR Mode of the OASIS Technical Committee that produced this
 deliverable.]
 
-    [OASIS invites any party to contact the OASIS TC Administrator if it
+[OASIS invites any party to contact the OASIS TC Administrator if it
 is aware of a claim of ownership of any patent claims that would
 necessarily be infringed by implementations of this OASIS Standards
 Final Deliverable by a patent holder that is not willing to provide a
@@ -52,7 +56,7 @@
 Final Deliverable. OASIS may include such claims on its website, but
 disclaims any obligation to do so.]
 
-    [OASIS takes no position regarding the validity or scope of any
+[OASIS takes no position regarding the validity or scope of any
 intellectual property or other rights that might be claimed to pertain
 to the implementation or use of the technology described in this OASIS
 Standards Final Deliverable or the extent to which any license under
diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h
--- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h	2025-04-09 19:45:33.000000000 +0000
@@ -1,8 +1,11 @@
-/* Copyright (c) OASIS Open 2016-2019. All Rights Reserved.
- * Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 #ifndef _PKCS11_H_
@@ -47,7 +50,7 @@
  *
  * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
  *
- * If you're using windows, it might be defined by:
+ * If you're using Windows, it might be defined by:
  *
  * #define CK_PTR *
  *
@@ -65,7 +68,7 @@
  *   CK_VOID_PTR pReserved
  * );
  *
- * If you're using Windows to declare a function in a Win32 cryptoki .dll,
+ * If you're using Windows to declare a function in a Win32 Cryptoki .dll,
  * it might be defined by:
  *
  * #define CK_DECLARE_FUNCTION(returnType, name) \
@@ -241,4 +244,3 @@
 
 #endif /* _PKCS11_H_ */
 
-
diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h
--- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h	2025-04-09 19:45:33.000000000 +0000
@@ -1,12 +1,11 @@
-/* Copyright (c) OASIS Open 2016, 2019. All Rights Reserved./
- * /Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
- */
-
-/* Latest version of the specification:
- * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 /* This header file contains pretty much everything about all the
diff -Nru openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h
--- openjdk-17-17.0.14+7/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h	2025-04-09 19:45:33.000000000 +0000
@@ -1,12 +1,11 @@
-/* Copyright (c) OASIS Open 2016, 2019. All Rights Reserved./
- * /Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
- */
-
-/* Latest version of the specification:
- * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 /* See top of pkcs11.h for information about the macros that
@@ -18,7 +17,7 @@
 #define _PKCS11T_H_ 1
 
 #define CRYPTOKI_VERSION_MAJOR          3
-#define CRYPTOKI_VERSION_MINOR          0
+#define CRYPTOKI_VERSION_MINOR          1
 #define CRYPTOKI_VERSION_AMENDMENT      0
 
 #define CK_TRUE         1
@@ -329,8 +328,11 @@
 #define CKP_EXTENDED_PROVIDER         0x00000002UL
 #define CKP_AUTHENTICATION_TOKEN      0x00000003UL
 #define CKP_PUBLIC_CERTIFICATES_TOKEN 0x00000004UL
+#define CKP_COMPLETE_PROVIDER         0x00000005UL
+#define CKP_HKDF_TLS_TOKEN            0x00000006UL
 #define CKP_VENDOR_DEFINED            0x80000000UL
 
+
 /* CK_HW_FEATURE_TYPE is a value that identifies the hardware feature type
  * of an object with CK_OBJECT_CLASS equal to CKO_HW_FEATURE.
  */
@@ -409,9 +411,11 @@
 #define CKK_EC_EDWARDS          0x00000040UL
 #define CKK_EC_MONTGOMERY       0x00000041UL
 #define CKK_HKDF                0x00000042UL
+
 #define CKK_SHA512_224_HMAC     0x00000043UL
 #define CKK_SHA512_256_HMAC     0x00000044UL
 #define CKK_SHA512_T_HMAC       0x00000045UL
+#define CKK_HSS                 0x00000046UL
 
 #define CKK_VENDOR_DEFINED      0x80000000UL
 
@@ -481,9 +485,9 @@
 #define CKA_CERTIFICATE_CATEGORY        0x00000087UL
 #define CKA_JAVA_MIDP_SECURITY_DOMAIN   0x00000088UL
 #define CKA_URL                         0x00000089UL
-#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008AUL
-#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008BUL
-#define CKA_NAME_HASH_ALGORITHM         0x0000008CUL
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008aUL
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008bUL
+#define CKA_NAME_HASH_ALGORITHM         0x0000008cUL
 #define CKA_CHECK_VALUE                 0x00000090UL
 
 #define CKA_KEY_TYPE           0x00000100UL
@@ -496,9 +500,9 @@
 #define CKA_UNWRAP             0x00000107UL
 #define CKA_SIGN               0x00000108UL
 #define CKA_SIGN_RECOVER       0x00000109UL
-#define CKA_VERIFY             0x0000010AUL
-#define CKA_VERIFY_RECOVER     0x0000010BUL
-#define CKA_DERIVE             0x0000010CUL
+#define CKA_VERIFY             0x0000010aUL
+#define CKA_VERIFY_RECOVER     0x0000010bUL
+#define CKA_DERIVE             0x0000010cUL
 #define CKA_START_DATE         0x00000110UL
 #define CKA_END_DATE           0x00000111UL
 #define CKA_MODULUS            0x00000120UL
@@ -555,12 +559,12 @@
 #define CKA_OTP_TIME_REQUIREMENT      0x00000225UL
 #define CKA_OTP_COUNTER_REQUIREMENT   0x00000226UL
 #define CKA_OTP_PIN_REQUIREMENT       0x00000227UL
-#define CKA_OTP_COUNTER               0x0000022EUL
-#define CKA_OTP_TIME                  0x0000022FUL
-#define CKA_OTP_USER_IDENTIFIER       0x0000022AUL
-#define CKA_OTP_SERVICE_IDENTIFIER    0x0000022BUL
-#define CKA_OTP_SERVICE_LOGO          0x0000022CUL
-#define CKA_OTP_SERVICE_LOGO_TYPE     0x0000022DUL
+#define CKA_OTP_COUNTER               0x0000022eUL
+#define CKA_OTP_TIME                  0x0000022fUL
+#define CKA_OTP_USER_IDENTIFIER       0x0000022aUL
+#define CKA_OTP_SERVICE_IDENTIFIER    0x0000022bUL
+#define CKA_OTP_SERVICE_LOGO          0x0000022cUL
+#define CKA_OTP_SERVICE_LOGO_TYPE     0x0000022dUL
 
 #define CKA_GOSTR3410_PARAMS            0x00000250UL
 #define CKA_GOSTR3411_PARAMS            0x00000251UL
@@ -586,6 +590,7 @@
 #define CKA_SUPPORTED_CMS_ATTRIBUTES    0x00000503UL
 #define CKA_ALLOWED_MECHANISMS          (CKF_ARRAY_ATTRIBUTE|0x00000600UL)
 #define CKA_PROFILE_ID                  0x00000601UL
+
 #define CKA_X2RATCHET_BAG               0x00000602UL
 #define CKA_X2RATCHET_BAGSIZE           0x00000603UL
 #define CKA_X2RATCHET_BOBS1STMSG        0x00000604UL
@@ -603,6 +608,13 @@
 #define CKA_X2RATCHET_NS                0x00000610UL
 #define CKA_X2RATCHET_PNS               0x00000611UL
 #define CKA_X2RATCHET_RK                0x00000612UL
+/* HSS */
+#define CKA_HSS_LEVELS                  0x00000617UL
+#define CKA_HSS_LMS_TYPE                0x00000618UL
+#define CKA_HSS_LMOTS_TYPE              0x00000619UL
+#define CKA_HSS_LMS_TYPES               0x0000061aUL
+#define CKA_HSS_LMOTS_TYPES             0x0000061bUL
+#define CKA_HSS_KEYS_REMAINING          0x0000061cUL
 
 #define CKA_VENDOR_DEFINED              0x80000000UL
 
@@ -644,11 +656,11 @@
 #define CKM_RIPEMD160_RSA_PKCS         0x00000008UL
 #define CKM_RSA_PKCS_OAEP              0x00000009UL
 
-#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000AUL
-#define CKM_RSA_X9_31                  0x0000000BUL
-#define CKM_SHA1_RSA_X9_31             0x0000000CUL
-#define CKM_RSA_PKCS_PSS               0x0000000DUL
-#define CKM_SHA1_RSA_PKCS_PSS          0x0000000EUL
+#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000aUL
+#define CKM_RSA_X9_31                  0x0000000bUL
+#define CKM_SHA1_RSA_X9_31             0x0000000cUL
+#define CKM_RSA_PKCS_PSS               0x0000000dUL
+#define CKM_SHA1_RSA_PKCS_PSS          0x0000000eUL
 
 #define CKM_DSA_KEY_PAIR_GEN           0x00000010UL
 #define CKM_DSA                        0x00000011UL
@@ -659,8 +671,8 @@
 #define CKM_DSA_SHA512                 0x00000016UL
 #define CKM_DSA_SHA3_224               0x00000018UL
 #define CKM_DSA_SHA3_256               0x00000019UL
-#define CKM_DSA_SHA3_384               0x0000001AUL
-#define CKM_DSA_SHA3_512               0x0000001BUL
+#define CKM_DSA_SHA3_384               0x0000001aUL
+#define CKM_DSA_SHA3_512               0x0000001bUL
 
 #define CKM_DH_PKCS_KEY_PAIR_GEN       0x00000020UL
 #define CKM_DH_PKCS_DERIVE             0x00000021UL
@@ -682,12 +694,12 @@
 
 #define CKM_SHA512_224                 0x00000048UL
 #define CKM_SHA512_224_HMAC            0x00000049UL
-#define CKM_SHA512_224_HMAC_GENERAL    0x0000004AUL
-#define CKM_SHA512_224_KEY_DERIVATION  0x0000004BUL
-#define CKM_SHA512_256                 0x0000004CUL
-#define CKM_SHA512_256_HMAC            0x0000004DUL
-#define CKM_SHA512_256_HMAC_GENERAL    0x0000004EUL
-#define CKM_SHA512_256_KEY_DERIVATION  0x0000004FUL
+#define CKM_SHA512_224_HMAC_GENERAL    0x0000004aUL
+#define CKM_SHA512_224_KEY_DERIVATION  0x0000004bUL
+#define CKM_SHA512_256                 0x0000004cUL
+#define CKM_SHA512_256_HMAC            0x0000004dUL
+#define CKM_SHA512_256_HMAC_GENERAL    0x0000004eUL
+#define CKM_SHA512_256_KEY_DERIVATION  0x0000004fUL
 
 #define CKM_SHA512_T                   0x00000050UL
 #define CKM_SHA512_T_HMAC              0x00000051UL
@@ -781,25 +793,25 @@
 #define CKM_SECURID                    0x00000282UL
 #define CKM_HOTP_KEY_GEN               0x00000290UL
 #define CKM_HOTP                       0x00000291UL
-#define CKM_ACTI                       0x000002A0UL
-#define CKM_ACTI_KEY_GEN               0x000002A1UL
+#define CKM_ACTI                       0x000002a0UL
+#define CKM_ACTI_KEY_GEN               0x000002a1UL
 
-#define CKM_SHA3_256                   0x000002B0UL
-#define CKM_SHA3_256_HMAC              0x000002B1UL
-#define CKM_SHA3_256_HMAC_GENERAL      0x000002B2UL
-#define CKM_SHA3_256_KEY_GEN           0x000002B3UL
-#define CKM_SHA3_224                   0x000002B5UL
-#define CKM_SHA3_224_HMAC              0x000002B6UL
-#define CKM_SHA3_224_HMAC_GENERAL      0x000002B7UL
-#define CKM_SHA3_224_KEY_GEN           0x000002B8UL
-#define CKM_SHA3_384                   0x000002C0UL
-#define CKM_SHA3_384_HMAC              0x000002C1UL
-#define CKM_SHA3_384_HMAC_GENERAL      0x000002C2UL
-#define CKM_SHA3_384_KEY_GEN           0x000002C3UL
-#define CKM_SHA3_512                   0x000002D0UL
-#define CKM_SHA3_512_HMAC              0x000002D1UL
-#define CKM_SHA3_512_HMAC_GENERAL      0x000002D2UL
-#define CKM_SHA3_512_KEY_GEN           0x000002D3UL
+#define CKM_SHA3_256                   0x000002b0UL
+#define CKM_SHA3_256_HMAC              0x000002b1UL
+#define CKM_SHA3_256_HMAC_GENERAL      0x000002b2UL
+#define CKM_SHA3_256_KEY_GEN           0x000002b3UL
+#define CKM_SHA3_224                   0x000002b5UL
+#define CKM_SHA3_224_HMAC              0x000002b6UL
+#define CKM_SHA3_224_HMAC_GENERAL      0x000002b7UL
+#define CKM_SHA3_224_KEY_GEN           0x000002b8UL
+#define CKM_SHA3_384                   0x000002c0UL
+#define CKM_SHA3_384_HMAC              0x000002c1UL
+#define CKM_SHA3_384_HMAC_GENERAL      0x000002c2UL
+#define CKM_SHA3_384_KEY_GEN           0x000002c3UL
+#define CKM_SHA3_512                   0x000002d0UL
+#define CKM_SHA3_512_HMAC              0x000002d1UL
+#define CKM_SHA3_512_HMAC_GENERAL      0x000002d2UL
+#define CKM_SHA3_512_KEY_GEN           0x000002d3UL
 
 
 #define CKM_CAST_KEY_GEN               0x00000300UL
@@ -870,9 +882,9 @@
 #define CKM_SHA3_256_KEY_DERIVATION    0x00000397UL
 #define CKM_SHA3_224_KEY_DERIVATION    0x00000398UL
 #define CKM_SHA3_384_KEY_DERIVATION    0x00000399UL
-#define CKM_SHA3_512_KEY_DERIVATION    0x0000039AUL
-#define CKM_SHAKE_128_KEY_DERIVATION   0x0000039BUL
-#define CKM_SHAKE_256_KEY_DERIVATION   0x0000039CUL
+#define CKM_SHA3_512_KEY_DERIVATION    0x0000039aUL
+#define CKM_SHAKE_128_KEY_DERIVATION   0x0000039bUL
+#define CKM_SHAKE_256_KEY_DERIVATION   0x0000039cUL
 #define CKM_SHA3_256_KEY_DERIVE  CKM_SHA3_256_KEY_DERIVATION
 #define CKM_SHA3_224_KEY_DERIVE  CKM_SHA3_224_KEY_DERIVATION
 #define CKM_SHA3_384_KEY_DERIVE  CKM_SHA3_384_KEY_DERIVATION
@@ -880,40 +892,42 @@
 #define CKM_SHAKE_128_KEY_DERIVE CKM_SHAKE_128_KEY_DERIVATION
 #define CKM_SHAKE_256_KEY_DERIVE CKM_SHAKE_256_KEY_DERIVATION
 
-#define CKM_PBE_MD2_DES_CBC            0x000003A0UL
-#define CKM_PBE_MD5_DES_CBC            0x000003A1UL
-#define CKM_PBE_MD5_CAST_CBC           0x000003A2UL
-#define CKM_PBE_MD5_CAST3_CBC          0x000003A3UL
-#define CKM_PBE_MD5_CAST5_CBC          0x000003A4UL /* Deprecated */
-#define CKM_PBE_MD5_CAST128_CBC        0x000003A4UL
-#define CKM_PBE_SHA1_CAST5_CBC         0x000003A5UL /* Deprecated */
-#define CKM_PBE_SHA1_CAST128_CBC       0x000003A5UL
-#define CKM_PBE_SHA1_RC4_128           0x000003A6UL
-#define CKM_PBE_SHA1_RC4_40            0x000003A7UL
-#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003A8UL
-#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003A9UL
-#define CKM_PBE_SHA1_RC2_128_CBC       0x000003AAUL
-#define CKM_PBE_SHA1_RC2_40_CBC        0x000003ABUL
-
-#define CKM_PKCS5_PBKD2                0x000003B0UL
-
-#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003C0UL
-
-#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003D0UL
-#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003D1UL
-#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003D2UL
-#define CKM_WTLS_PRF                        0x000003D3UL
-#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4UL
-#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5UL
-
-#define CKM_TLS12_MAC                       0x000003D8UL
-#define CKM_TLS12_KDF                       0x000003D9UL
-#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003E0UL
-#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003E1UL
-#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003E2UL
-#define CKM_TLS12_KEY_SAFE_DERIVE           0x000003E3UL
-#define CKM_TLS_MAC                         0x000003E4UL
-#define CKM_TLS_KDF                         0x000003E5UL
+#define CKM_PBE_MD2_DES_CBC            0x000003a0UL
+#define CKM_PBE_MD5_DES_CBC            0x000003a1UL
+#define CKM_PBE_MD5_CAST_CBC           0x000003a2UL
+#define CKM_PBE_MD5_CAST3_CBC          0x000003a3UL
+#define CKM_PBE_MD5_CAST5_CBC          0x000003a4UL /* Deprecated */
+#define CKM_PBE_MD5_CAST128_CBC        0x000003a4UL
+#define CKM_PBE_SHA1_CAST5_CBC         0x000003a5UL /* Deprecated */
+#define CKM_PBE_SHA1_CAST128_CBC       0x000003a5UL
+#define CKM_PBE_SHA1_RC4_128           0x000003a6UL
+#define CKM_PBE_SHA1_RC4_40            0x000003a7UL
+#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003a8UL
+#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003a9UL
+#define CKM_PBE_SHA1_RC2_128_CBC       0x000003aaUL
+#define CKM_PBE_SHA1_RC2_40_CBC        0x000003abUL
+
+#define CKM_PKCS5_PBKD2                0x000003b0UL
+
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003c0UL
+
+#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003d0UL
+#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003d1UL
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003d2UL
+#define CKM_WTLS_PRF                        0x000003d3UL
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003d4UL
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003d5UL
+
+#define CKM_TLS10_MAC_SERVER                0x000003d6UL
+#define CKM_TLS10_MAC_CLIENT                0x000003d7UL
+#define CKM_TLS12_MAC                       0x000003d8UL
+#define CKM_TLS12_KDF                       0x000003d9UL
+#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003e0UL
+#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003e1UL
+#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003e2UL
+#define CKM_TLS12_KEY_SAFE_DERIVE           0x000003e3UL
+#define CKM_TLS_MAC                         0x000003e4UL
+#define CKM_TLS_KDF                         0x000003e5UL
 
 #define CKM_KEY_WRAP_LYNKS             0x00000400UL
 #define CKM_KEY_WRAP_SET_OAEP          0x00000401UL
@@ -983,7 +997,7 @@
 #define CKM_ECDSA_SHA256               0x00001044UL
 #define CKM_ECDSA_SHA384               0x00001045UL
 #define CKM_ECDSA_SHA512               0x00001046UL
-#define CKM_EC_KEY_PAIR_GEN_W_EXTRA_BITS 0x0000140BUL
+#define CKM_EC_KEY_PAIR_GEN_W_EXTRA_BITS 0x0000140bUL
 
 #define CKM_ECDH1_DERIVE               0x00001050UL
 #define CKM_ECDH1_COFACTOR_DERIVE      0x00001051UL
@@ -1012,12 +1026,12 @@
 #define CKM_AES_GCM                    0x00001087UL
 #define CKM_AES_CCM                    0x00001088UL
 #define CKM_AES_CTS                    0x00001089UL
-#define CKM_AES_CMAC                   0x0000108AUL
-#define CKM_AES_CMAC_GENERAL           0x0000108BUL
+#define CKM_AES_CMAC                   0x0000108aUL
+#define CKM_AES_CMAC_GENERAL           0x0000108bUL
 
-#define CKM_AES_XCBC_MAC               0x0000108CUL
-#define CKM_AES_XCBC_MAC_96            0x0000108DUL
-#define CKM_AES_GMAC                   0x0000108EUL
+#define CKM_AES_XCBC_MAC               0x0000108cUL
+#define CKM_AES_XCBC_MAC_96            0x0000108dUL
+#define CKM_AES_GMAC                   0x0000108eUL
 
 #define CKM_BLOWFISH_KEY_GEN           0x00001090UL
 #define CKM_BLOWFISH_CBC               0x00001091UL
@@ -1066,6 +1080,7 @@
 #define CKM_AES_KEY_WRAP               0x00002109UL     /* WAS: 0x00001090 */
 #define CKM_AES_KEY_WRAP_PAD           0x0000210AUL     /* WAS: 0x00001091 */
 #define CKM_AES_KEY_WRAP_KWP           0x0000210BUL
+#define CKM_AES_KEY_WRAP_PKCS7         0x0000210CUL
 
 #define CKM_RSA_PKCS_TPM_1_1           0x00004001UL
 #define CKM_RSA_PKCS_OAEP_TPM_1_1      0x00004002UL
@@ -1125,6 +1140,14 @@
 #define CKM_SP800_108_FEEDBACK_KDF     0x000003adUL
 #define CKM_SP800_108_DOUBLE_PIPELINE_KDF 0x000003aeUL
 
+#define CKM_IKE2_PRF_PLUS_DERIVE       0x0000402eUL
+#define CKM_IKE_PRF_DERIVE             0x0000402fUL
+#define CKM_IKE1_PRF_DERIVE            0x00004030UL
+#define CKM_IKE1_EXTENDED_DERIVE       0x00004031UL
+#define CKM_HSS_KEY_PAIR_GEN           0x00004032UL
+#define CKM_HSS                        0x00004033UL
+
+
 #define CKM_VENDOR_DEFINED             0x80000000UL
 
 typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;
@@ -1320,6 +1343,7 @@
 #define CKR_FUNCTION_REJECTED                 0x00000200UL
 #define CKR_TOKEN_RESOURCE_EXCEEDED           0x00000201UL
 #define CKR_OPERATION_CANCEL_FAILED           0x00000202UL
+#define CKR_KEY_EXHAUSTED                     0x00000203UL
 
 #define CKR_VENDOR_DEFINED                    0x80000000UL
 
@@ -1436,6 +1460,7 @@
 #define CKG_MGF1_SHA3_384     0x00000008UL
 #define CKG_MGF1_SHA3_512     0x00000009UL
 
+
 /* CK_RSA_PKCS_OAEP_SOURCE_TYPE  is used to indicate the source
  * of the encoding parameter when formatting a message block
  * for the PKCS #1 OAEP encryption scheme.
@@ -1701,8 +1726,7 @@
     CK_ULONG    length;
 } CK_DES_CBC_ENCRYPT_DATA_PARAMS;
 
-typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
-        CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
 
 typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS {
     CK_BYTE     iv[16];
@@ -1710,8 +1734,7 @@
     CK_ULONG    length;
 } CK_AES_CBC_ENCRYPT_DATA_PARAMS;
 
-typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
-        CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
 
 /* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the
  * CKM_SKIPJACK_PRIVATE_WRAP mechanism
@@ -2051,6 +2074,7 @@
 #define CKG_GENERATE         0x00000001UL
 #define CKG_GENERATE_COUNTER 0x00000002UL
 #define CKG_GENERATE_RANDOM  0x00000003UL
+#define CKG_GENERATE_COUNTER_XOR 0x00000004UL
 
 typedef struct CK_GCM_MESSAGE_PARAMS {
     CK_BYTE_PTR           pIv;
@@ -2061,7 +2085,7 @@
     CK_ULONG              ulTagBits;
 } CK_GCM_MESSAGE_PARAMS;
 
-typedef CK_GCM_MESSAGE_PARAMS CK_GCM_MESSAGE_PARAMS_PTR;
+typedef CK_GCM_MESSAGE_PARAMS CK_PTR CK_GCM_MESSAGE_PARAMS_PTR;
 
 typedef struct CK_CCM_PARAMS {
     CK_ULONG    ulDataLen;
@@ -2084,7 +2108,7 @@
     CK_ULONG              ulMACLen;
 } CK_CCM_MESSAGE_PARAMS;
 
-typedef CK_CCM_MESSAGE_PARAMS CK_CCM_MESSAGE_PARAMS_PTR;
+typedef CK_CCM_MESSAGE_PARAMS CK_PTR CK_CCM_MESSAGE_PARAMS_PTR;
 
 /* Deprecated. Use CK_GCM_PARAMS */
 typedef struct CK_AES_GCM_PARAMS {
@@ -2339,7 +2363,6 @@
     CK_BYTE_PTR pNonce;
     CK_ULONG    ulNonceBits;
 } CK_SALSA20_PARAMS;
-
 typedef CK_SALSA20_PARAMS CK_PTR CK_SALSA20_PARAMS_PTR;
 
 typedef struct CK_SALSA20_CHACHA20_POLY1305_PARAMS {
@@ -2423,6 +2446,7 @@
 } CK_XEDDSA_PARAMS;
 typedef CK_XEDDSA_PARAMS CK_PTR CK_XEDDSA_PARAMS_PTR;
 
+/* HKDF params */
 typedef struct CK_HKDF_PARAMS {
     CK_BBOOL          bExtract;
     CK_BBOOL          bExpand;
@@ -2440,5 +2464,60 @@
 #define CKF_HKDF_SALT_DATA   0x00000002UL
 #define CKF_HKDF_SALT_KEY    0x00000004UL
 
+/* HSS */
+typedef CK_ULONG                   CK_HSS_LEVELS;
+typedef CK_ULONG                   CK_LMS_TYPE;
+typedef CK_ULONG                   CK_LMOTS_TYPE;
+
+typedef struct specifiedParams {
+    CK_HSS_LEVELS levels;
+    CK_LMS_TYPE   lm_type[8];
+    CK_LMOTS_TYPE lm_ots_type[8];
+} specifiedParams;
+
+/* IKE Params */
+typedef struct CK_IKE2_PRF_PLUS_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasSeedKey;
+    CK_OBJECT_HANDLE  hSeedKey;
+    CK_BYTE_PTR       pSeedData;
+    CK_ULONG          ulSeedDataLen;
+} CK_IKE2_PRF_PLUS_DERIVE_PARAMS;
+typedef CK_IKE2_PRF_PLUS_DERIVE_PARAMS CK_PTR CK_IKE2_PRF_PLUS_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE_PRF_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bDataAsKey;
+    CK_BBOOL          bRekey;
+    CK_BYTE_PTR       pNi;
+    CK_ULONG          ulNiLen;
+    CK_BYTE_PTR       pNr;
+    CK_ULONG          ulNrLen;
+    CK_OBJECT_HANDLE  hNewKey;
+} CK_IKE_PRF_DERIVE_PARAMS;
+typedef CK_IKE_PRF_DERIVE_PARAMS CK_PTR CK_IKE_PRF_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE1_PRF_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasPrevKey;
+    CK_OBJECT_HANDLE  hKeygxy;
+    CK_OBJECT_HANDLE  hPrevKey;
+    CK_BYTE_PTR       pCKYi;
+    CK_ULONG          ulCKYiLen;
+    CK_BYTE_PTR       pCKYr;
+    CK_ULONG          ulCKYrLen;
+    CK_BYTE           keyNumber;
+} CK_IKE1_PRF_DERIVE_PARAMS;
+typedef CK_IKE1_PRF_DERIVE_PARAMS CK_PTR CK_IKE1_PRF_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE1_EXTENDED_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasKeygxy;
+    CK_OBJECT_HANDLE  hKeygxy;
+    CK_BYTE_PTR       pExtraData;
+    CK_ULONG          ulExtraDataLen;
+} CK_IKE1_EXTENDED_DERIVE_PARAMS;
+typedef CK_IKE1_EXTENDED_DERIVE_PARAMS CK_PTR CK_IKE1_EXTENDED_DERIVE_PARAMS_PTR;
+
 #endif /* _PKCS11T_H_ */
 
diff -Nru openjdk-17-17.0.14+7/src/jdk.hotspot.agent/linux/native/libsaproc/LinuxDebuggerLocal.cpp openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/LinuxDebuggerLocal.cpp
--- openjdk-17-17.0.14+7/src/jdk.hotspot.agent/linux/native/libsaproc/LinuxDebuggerLocal.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/LinuxDebuggerLocal.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -421,7 +421,6 @@
   jboolean isCopy;
   jlongArray array;
   jlong *regs;
-  int i;
 
   struct ps_prochandle* ph = get_proc_handle(env, this_obj);
   if (get_lwp_regs(ph, lwp_id, &gregs) != true) {
diff -Nru openjdk-17-17.0.14+7/src/jdk.hotspot.agent/linux/native/libsaproc/symtab.c openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/symtab.c
--- openjdk-17-17.0.14+7/src/jdk.hotspot.agent/linux/native/libsaproc/symtab.c	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.hotspot.agent/linux/native/libsaproc/symtab.c	2025-04-09 19:45:33.000000000 +0000
@@ -359,7 +359,6 @@
 
     if (shdr->sh_type == sym_section) {
       ELF_SYM  *syms;
-      int rslt;
       size_t size, n, j, htab_sz;
 
       // FIXME: there could be multiple data buffers associated with the
@@ -393,7 +392,8 @@
         goto bad;
       }
 
-      rslt = hcreate_r(n, symtab->hash_table);
+      // int rslt =
+      hcreate_r(n, symtab->hash_table);
       // guarantee(rslt, "unexpected failure: hcreate_r");
 
       // shdr->sh_link points to the section that contains the actual strings
diff -Nru openjdk-17-17.0.14+7/src/jdk.hotspot.agent/macosx/native/libsaproc/ps_core.c openjdk-17-17.0.15+6/src/jdk.hotspot.agent/macosx/native/libsaproc/ps_core.c
--- openjdk-17-17.0.14+7/src/jdk.hotspot.agent/macosx/native/libsaproc/ps_core.c	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.hotspot.agent/macosx/native/libsaproc/ps_core.c	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -297,11 +297,16 @@
         print_debug("failed to read LC_SEGMENT_64 i = %d!\n", i);
         goto err;
       }
-      if (add_map_info(ph, fd, segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize, segcmd.flags) == NULL) {
-        print_debug("Failed to add map_info at i = %d\n", i);
-        goto err;
+      // The base of the library is offset by a random amount which ends up as a load command with a
+      // filesize of 0.  This must be ignored otherwise the base address of the library is wrong.
+      if (segcmd.filesize != 0) {
+        if (add_map_info(ph, fd, segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize, segcmd.flags) == NULL) {
+          print_debug("Failed to add map_info at i = %d\n", i);
+          goto err;
+        }
       }
-      print_debug("LC_SEGMENT_64 added: nsects=%d fileoff=0x%llx vmaddr=0x%llx vmsize=0x%llx filesize=0x%llx %s\n",
+      print_debug("LC_SEGMENT_64 %s: nsects=%d fileoff=0x%llx vmaddr=0x%llx vmsize=0x%llx filesize=0x%llx %s\n",
+                  segcmd.filesize == 0 ? "with filesize == 0 ignored" : "added",
                   segcmd.nsects, segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize,
                   segcmd.filesize, &segcmd.segname[0]);
     } else if (lcmd.cmd == LC_THREAD || lcmd.cmd == LC_UNIXTHREAD) {
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/BindingReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/BindingReader.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/BindingReader.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/BindingReader.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2018, the original author or authors.
+ * Copyright (c) 2002-2018, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -66,7 +66,7 @@
         T o = null;
         int[] remaining = new int[1];
         boolean hasRead = false;
-        for (;;) {
+        for (; ; ) {
             if (local != null) {
                 o = local.getBound(opBuffer, remaining);
             }
@@ -78,8 +78,7 @@
                 if (remaining[0] >= 0) {
                     runMacro(opBuffer.substring(opBuffer.length() - remaining[0]));
                     opBuffer.setLength(opBuffer.length() - remaining[0]);
-                }
-                else {
+                } else {
                     long ambiguousTimeout = keys.getAmbiguousTimeout();
                     if (ambiguousTimeout > 0 && peekCharacter(ambiguousTimeout) != NonBlockingReader.READ_EXPIRED) {
                         o = null;
@@ -234,5 +233,4 @@
     public String getLastBinding() {
         return lastBinding;
     }
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/KeyMap.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/KeyMap.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/KeyMap.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/keymap/KeyMap.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2016, the original author or authors.
+ * Copyright (c) 2002-2016, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -8,8 +8,6 @@
  */
 package jdk.internal.org.jline.keymap;
 
-import java.io.IOException;
-import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Comparator;
@@ -218,7 +216,6 @@
         return seqs;
     }
 
-
     public static String esc() {
         return "\033";
     }
@@ -264,7 +261,6 @@
     // Methods
     //
 
-
     public T getUnicode() {
         return unicode;
     }
@@ -306,9 +302,7 @@
         }
         for (int c = 0; c < keyMap.mapping.length; c++) {
             if (keyMap.mapping[c] instanceof KeyMap) {
-                doGetBoundKeys((KeyMap) keyMap.mapping[c],
-                        prefix + (char) (c),
-                        bound);
+                doGetBoundKeys((KeyMap) keyMap.mapping[c], prefix + (char) (c), bound);
             } else if (keyMap.mapping[c] != null) {
                 bound.put(prefix + (char) (c), (T) keyMap.mapping[c]);
             }
@@ -456,5 +450,4 @@
             }
         }
     }
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Binding.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Binding.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Binding.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Binding.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2016, the original author or authors.
+ * Copyright (c) 2002-2016, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -14,9 +14,8 @@
  * @see Macro
  * @see Reference
  * @see Widget
- * @see jdk.internal.org.jline.keymap.KeyMap
+ * @see org.jline.keymap.KeyMap
  *
  * @author Guillaume Nodet
  */
-public interface Binding {
-}
+public interface Binding {}
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Buffer.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Buffer.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Buffer.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Buffer.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2017, the original author or authors.
+ * Copyright (c) 2002-2017, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -84,4 +84,8 @@
 
     void copyFrom(Buffer buffer);
 
+    /**
+     * Clear any internal buffer.
+     */
+    void zeroOut();
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Candidate.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Candidate.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Candidate.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Candidate.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2019, the original author or authors.
+ * Copyright (c) 2002-2019, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -47,7 +47,15 @@
      * @param complete the complete flag
      * @param sort the sort flag
      */
-    public Candidate(String value, String displ, String group, String descr, String suffix, String key, boolean complete, int sort) {
+    public Candidate(
+            String value,
+            String displ,
+            String group,
+            String descr,
+            String suffix,
+            String key,
+            boolean complete,
+            int sort) {
         this.value = Objects.requireNonNull(value);
         this.displ = Objects.requireNonNull(displ);
         this.group = group;
@@ -69,7 +77,8 @@
      * @param key the key
      * @param complete the complete flag
      */
-    public Candidate(String value, String displ, String group, String descr, String suffix, String key, boolean complete) {
+    public Candidate(
+            String value, String displ, String group, String descr, String suffix, String key, boolean complete) {
         this(value, displ, group, descr, suffix, key, complete, 0);
     }
 
@@ -159,11 +168,10 @@
         return sort;
     }
 
-
     @Override
     public int compareTo(Candidate o) {
         // If both candidates have same sort, use default behavior
-        if( sort == o.sort() ) {
+        if (sort == o.sort()) {
             return value.compareTo(o.value);
         } else {
             return Integer.compare(sort, o.sort());
@@ -180,7 +188,7 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(value);
+        return Objects.hashCode(value);
     }
 
     @Override
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Completer.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Completer.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Completer.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Completer.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2018, the original author or authors.
+ * Copyright (c) 2002-2018, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -18,8 +18,7 @@
  * @author Guillaume Nodet
  * @since 2.3
  */
-public interface Completer
-{
+public interface Completer {
     /**
      * Populates candidates with a list of possible completions for the command line.
      *
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletingParsedLine.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletingParsedLine.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletingParsedLine.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletingParsedLine.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2018, the original author or authors.
+ * Copyright (c) 2002-2018, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -10,7 +10,7 @@
 
 /**
  * An extension of {@link ParsedLine} that, being aware of the quoting and escaping rules
- * of the {@link jdk.internal.org.jline.reader.Parser} that produced it, knows if and how a completion candidate
+ * of the {@link org.jline.reader.Parser} that produced it, knows if and how a completion candidate
  * should be escaped/quoted.
  *
  * @author Eric Bottard
@@ -22,5 +22,4 @@
     int rawWordCursor();
 
     int rawWordLength();
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletionMatcher.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletionMatcher.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletionMatcher.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/CompletionMatcher.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2020, the original author or authors.
+ * Copyright (c) 2002-2020, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -23,8 +23,13 @@
      * @param errors number of errors accepted in matching
      * @param originalGroupName value of JLineReader variable original-group-name
      */
-    void compile(Map options, boolean prefix, CompletingParsedLine line
-            , boolean caseInsensitive, int errors, String originalGroupName);
+    void compile(
+            Map options,
+            boolean prefix,
+            CompletingParsedLine line,
+            boolean caseInsensitive,
+            int errors,
+            String originalGroupName);
 
     /**
      *
@@ -44,5 +49,4 @@
      * @return a common prefix of matched candidates
      */
     String getCommonPrefix();
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EOFError.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EOFError.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EOFError.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EOFError.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,20 +1,10 @@
 /*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
+ * Copyright (c) 2023, the original author(s).
  *
- *   http://www.apache.org/licenses/LICENSE-2.0
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
  *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * https://opensource.org/licenses/BSD-3-Clause
  */
 package jdk.internal.org.jline.reader;
 
@@ -45,7 +35,7 @@
         return missing;
     }
 
-    public int getOpenBrackets(){
+    public int getOpenBrackets() {
         return openBrackets;
     }
 
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Editor.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Editor.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Editor.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Editor.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2019, the original author or authors.
+ * Copyright (c) 2002-2019, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -13,6 +13,8 @@
 
 public interface Editor {
     public void open(List files) throws IOException;
+
     public void run() throws IOException;
+
     public void setRestricted(boolean restricted);
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EndOfFileException.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EndOfFileException.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EndOfFileException.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/EndOfFileException.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2020, the original author or authors.
+ * Copyright (c) 2002-2020, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -17,8 +17,7 @@
     private static final long serialVersionUID = 528485360925144689L;
     private String partialLine;
 
-    public EndOfFileException() {
-    }
+    public EndOfFileException() {}
 
     public EndOfFileException(String message) {
         super(message);
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Expander.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Expander.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Expander.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Expander.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2016, the original author or authors.
+ * Copyright (c) 2002-2016, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -13,5 +13,4 @@
     String expandHistory(History history, String line);
 
     String expandVar(String word);
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Highlighter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Highlighter.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Highlighter.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Highlighter.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2021, the original author or authors.
+ * Copyright (c) 2002-2021, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/History.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/History.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/History.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/History.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2018, the original author or authors.
+ * Copyright (c) 2002-2018, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -21,8 +21,7 @@
  * @author Jason Dillon
  * @since 2.3
  */
-public interface History extends Iterable
-{
+public interface History extends Iterable {
 
     /**
      * Initialize the history for the given reader.
@@ -75,7 +74,6 @@
      */
     void purge() throws IOException;
 
-
     int size();
 
     default boolean isEmpty() {
@@ -110,8 +108,7 @@
     // Entries
     //
 
-    interface Entry
-    {
+    interface Entry {
         int index();
 
         Instant time();
@@ -132,14 +129,17 @@
     default Iterator reverseIterator(int index) {
         return new Iterator() {
             private final ListIterator it = iterator(index + 1);
+
             @Override
             public boolean hasNext() {
                 return it.hasPrevious();
             }
+
             @Override
             public Entry next() {
                 return it.previous();
             }
+
             @Override
             public void remove() {
                 it.remove();
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReader.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReader.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReader.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2021, the original author or authors.
+ * Copyright (c) 2002-2023, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -21,7 +21,7 @@
 
 /** Read lines from the console, with input editing.
  *
- * 

Thread safety

+ *

Thread safety

* The LineReader implementations are not thread safe, * thus you should not attempt to use a single reader in several threads. * Any attempt to call one of the readLine call while one is @@ -31,7 +31,7 @@ * {@link #printAbove(String)} or {@link #printAbove(AttributedString)} at * any time to allow text to be printed above the current prompt. * - *

Prompt strings

+ *

Prompt strings

* It is traditional for an interactive console-based program * to print a short prompt string to signal that the user is expected * to type a command. JLine supports 3 kinds of prompt string: @@ -81,7 +81,6 @@ * * */ - public interface LineReader { /** @@ -284,6 +283,7 @@ String MAIN = "main"; String EMACS = "emacs"; String SAFE = ".safe"; + String DUMB = "dumb"; String MENU = "menu"; // @@ -301,6 +301,7 @@ * they are displayed in a list below the field to be completed */ String MENU_LIST_MAX = "menu-list-max"; + String DISABLE_HISTORY = "disable-history"; String DISABLE_COMPLETION = "disable-completion"; String EDITING_MODE = "editing-mode"; @@ -317,18 +318,23 @@ String ORIGINAL_GROUP_NAME = "ORIGINAL_GROUP_NAME"; /** Completion style for displaying groups name */ String COMPLETION_STYLE_GROUP = "COMPLETION_STYLE_GROUP"; + String COMPLETION_STYLE_LIST_GROUP = "COMPLETION_STYLE_LIST_GROUP"; /** Completion style for displaying the current selected item */ String COMPLETION_STYLE_SELECTION = "COMPLETION_STYLE_SELECTION"; + String COMPLETION_STYLE_LIST_SELECTION = "COMPLETION_STYLE_LIST_SELECTION"; /** Completion style for displaying the candidate description */ String COMPLETION_STYLE_DESCRIPTION = "COMPLETION_STYLE_DESCRIPTION"; + String COMPLETION_STYLE_LIST_DESCRIPTION = "COMPLETION_STYLE_LIST_DESCRIPTION"; /** Completion style for displaying the matching part of candidates */ String COMPLETION_STYLE_STARTING = "COMPLETION_STYLE_STARTING"; + String COMPLETION_STYLE_LIST_STARTING = "COMPLETION_STYLE_LIST_STARTING"; /** Completion style for displaying the list */ String COMPLETION_STYLE_BACKGROUND = "COMPLETION_STYLE_BACKGROUND"; + String COMPLETION_STYLE_LIST_BACKGROUND = "COMPLETION_STYLE_LIST_BACKGROUND"; /** * Set the template for prompts for secondary (continuation) lines. @@ -390,6 +396,26 @@ */ String SUGGESTIONS_MIN_BUFFER_SIZE = "suggestions-min-buffer-size"; + /** + * Max number of times a command can be repeated. + */ + String MAX_REPEAT_COUNT = "max-repeat-count"; + + /** + * Number of spaces to display a tabulation, the default is 4. + */ + String TAB_WIDTH = "tab-width"; + + /** + * Name of inputrc to read at line reader creation time. + */ + String INPUT_RC_FILE_NAME = "input-rc-file-name"; + + /** + * Prefix to automatically delegate variables to system properties + */ + String SYSTEM_PROPERTY_PREFIX = "system-property-prefix"; + Map> defaultKeyMaps(); enum Option { @@ -469,8 +495,7 @@ EMPTY_WORD_OPTIONS(true), /** Disable the undo feature */ - DISABLE_UNDO - ; + DISABLE_UNDO; private final boolean def; @@ -611,7 +636,8 @@ * @throws EndOfFileException if an EOF has been found (using Ctrl-D for example) * @throws java.io.IOError in case of other i/o errors */ - String readLine(String prompt, String rightPrompt, Character mask, String buffer) throws UserInterruptException, EndOfFileException; + String readLine(String prompt, String rightPrompt, Character mask, String buffer) + throws UserInterruptException, EndOfFileException; /** * Read a line from the in {@link InputStream}, and return the line @@ -631,7 +657,8 @@ * @throws EndOfFileException if an EOF has been found (using Ctrl-D for example) * @throws java.io.IOError in case of other i/o errors */ - String readLine(String prompt, String rightPrompt, MaskingCallback maskingCallback, String buffer) throws UserInterruptException, EndOfFileException; + String readLine(String prompt, String rightPrompt, MaskingCallback maskingCallback, String buffer) + throws UserInterruptException, EndOfFileException; /** * Prints a line above the prompt and redraw everything. @@ -702,7 +729,7 @@ void runMacro(String macro); /** - * Read a mouse event when the {@link jdk.internal.org.jline.utils.InfoCmp.Capability#key_mouse} sequence + * Read a mouse event when the {@link org.jline.utils.InfoCmp.Capability#key_mouse} sequence * has just been read on the input stream. * Compared to {@link Terminal#readMouseEvent()}, this method takes into account keys * that have been pushed back using {@link #runMacro(String)}. @@ -750,4 +777,9 @@ void setAutosuggestion(SuggestionType type); SuggestionType getAutosuggestion(); + + /** + * Clear any internal buffers. + */ + void zeroOut(); } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReaderBuilder.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReaderBuilder.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReaderBuilder.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/LineReaderBuilder.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -38,8 +38,7 @@ Expander expander; CompletionMatcher completionMatcher; - private LineReaderBuilder() { - } + private LineReaderBuilder() {} public LineReaderBuilder terminal(Terminal terminal) { this.terminal = terminal; @@ -88,8 +87,9 @@ try { if (!Boolean.getBoolean(LineReader.PROP_SUPPORT_PARSEDLINE) && !(parser.parse("", 0) instanceof CompletingParsedLine)) { - Log.warn("The Parser of class " + parser.getClass().getName() + " does not support the CompletingParsedLine interface. " + - "Completion with escaped or quoted words won't work correctly."); + Log.warn("The Parser of class " + parser.getClass().getName() + + " does not support the CompletingParsedLine interface. " + + "Completion with escaped or quoted words won't work correctly."); } } catch (Throwable t) { // Ignore @@ -153,5 +153,4 @@ } return reader; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Macro.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Macro.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Macro.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Macro.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -35,7 +35,6 @@ @Override public String toString() { - return "Macro[" + - sequence + ']'; + return "Macro[" + sequence + ']'; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/MaskingCallback.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/MaskingCallback.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/MaskingCallback.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/MaskingCallback.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -31,5 +31,4 @@ * @return the modified line */ String history(String line); - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/ParsedLine.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/ParsedLine.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/ParsedLine.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/ParsedLine.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -64,5 +64,4 @@ * @return the cursor position within the line */ int cursor(); - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Parser.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Parser.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Parser.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Parser.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -35,7 +35,7 @@ default String getCommand(final String line) { String out; - Pattern patternCommand = Pattern.compile("^\\s*" + REGEX_VARIABLE + "=(" + REGEX_COMMAND + ")(\\s+|$)"); + Pattern patternCommand = Pattern.compile("^\\s*" + REGEX_VARIABLE + "=(" + REGEX_COMMAND + ")(\\s+|$)"); Matcher matcher = patternCommand.matcher(line); if (matcher.find()) { out = matcher.group(1); @@ -50,7 +50,7 @@ default String getVariable(final String line) { String out = null; - Pattern patternCommand = Pattern.compile("^\\s*(" + REGEX_VARIABLE + ")\\s*=[^=~].*"); + Pattern patternCommand = Pattern.compile("^\\s*(" + REGEX_VARIABLE + ")\\s*=[^=~].*"); Matcher matcher = patternCommand.matcher(line); if (matcher.find()) { out = matcher.group(1); diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/PrintAboveWriter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/PrintAboveWriter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/PrintAboveWriter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/PrintAboveWriter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Reference.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Reference.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Reference.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Reference.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -38,7 +38,6 @@ @Override public String toString() { - return "Reference[" + - name + ']'; + return "Reference[" + name + ']'; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/SyntaxError.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/SyntaxError.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/SyntaxError.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/SyntaxError.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,20 +1,10 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * Copyright (c) 2023, the original author(s). * - * http://www.apache.org/licenses/LICENSE-2.0 + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * https://opensource.org/licenses/BSD-3-Clause */ package jdk.internal.org.jline.reader; diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/UserInterruptException.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/UserInterruptException.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/UserInterruptException.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/UserInterruptException.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -14,23 +14,19 @@ * interrupt character (ctrl-C). The partially entered line is * available via the {@link #getPartialLine()} method. */ -public class UserInterruptException - extends RuntimeException -{ +public class UserInterruptException extends RuntimeException { private static final long serialVersionUID = 6172232572140736750L; private final String partialLine; - public UserInterruptException(String partialLine) - { + public UserInterruptException(String partialLine) { this.partialLine = partialLine; } /** * @return the partially entered line when ctrl-C was pressed */ - public String getPartialLine() - { + public String getPartialLine() { return partialLine; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Widget.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Widget.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Widget.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/Widget.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -15,5 +15,4 @@ public interface Widget extends Binding { boolean apply(); - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/BufferImpl.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/BufferImpl.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/BufferImpl.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/BufferImpl.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,6 +8,7 @@ */ package jdk.internal.org.jline.reader.impl; +import java.util.Arrays; import java.util.Objects; import jdk.internal.org.jline.reader.Buffer; @@ -19,8 +20,7 @@ * @author Jason Dillon * @since 2.0 */ -public class BufferImpl implements Buffer -{ +public class BufferImpl implements Buffer { private int cursor = 0; private int cursorCol = -1; private int[] buffer; @@ -45,7 +45,7 @@ this.g1 = buffer.g1; } - public BufferImpl copy () { + public BufferImpl copy() { return new BufferImpl(this); } @@ -106,7 +106,7 @@ * @param c the character to insert */ public void write(int c) { - write(new int[] { c }); + write(new int[] {c}); } /** @@ -120,7 +120,7 @@ if (overTyping) { delete(1); } - write(new int[] { c }); + write(new int[] {c}); } /** @@ -223,8 +223,7 @@ if ((cursor + where) < 0) { where = -cursor; - } - else if ((cursor + where) > length()) { + } else if ((cursor + where) > length()) { where = length() - cursor; } @@ -369,4 +368,9 @@ g1 += l; } } + + @Override + public void zeroOut() { + Arrays.fill(buffer, 0); + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/CompletionMatcherImpl.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/CompletionMatcherImpl.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/CompletionMatcherImpl.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/CompletionMatcherImpl.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,26 +8,25 @@ */ package jdk.internal.org.jline.reader.impl; -import jdk.internal.org.jline.reader.Candidate; -import jdk.internal.org.jline.reader.CompletingParsedLine; -import jdk.internal.org.jline.reader.CompletionMatcher; -import jdk.internal.org.jline.reader.LineReader; -import jdk.internal.org.jline.utils.AttributedString; - import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; +import jdk.internal.org.jline.reader.Candidate; +import jdk.internal.org.jline.reader.CompletingParsedLine; +import jdk.internal.org.jline.reader.CompletionMatcher; +import jdk.internal.org.jline.reader.LineReader; +import jdk.internal.org.jline.utils.AttributedString; + public class CompletionMatcherImpl implements CompletionMatcher { protected Predicate exact; protected List>, Map>>> matchers; private Map> matching; private boolean caseInsensitive; - public CompletionMatcherImpl() { - } + public CompletionMatcherImpl() {} protected void reset(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; @@ -37,8 +36,13 @@ } @Override - public void compile(Map options, boolean prefix, CompletingParsedLine line - , boolean caseInsensitive, int errors, String originalGroupName) { + public void compile( + Map options, + boolean prefix, + CompletingParsedLine line, + boolean caseInsensitive, + int errors, + String originalGroupName) { reset(caseInsensitive); defaultMatchers(options, prefix, line, caseInsensitive, errors, originalGroupName); } @@ -47,15 +51,18 @@ public List matches(List candidates) { matching = Collections.emptyMap(); Map> sortedCandidates = sort(candidates); - for (Function>, - Map>> matcher : matchers) { + for (Function>, Map>> matcher : matchers) { matching = matcher.apply(sortedCandidates); if (!matching.isEmpty()) { break; } } - return !matching.isEmpty() ? matching.entrySet().stream().flatMap(e -> e.getValue().stream()).distinct().collect(Collectors.toList()) - : new ArrayList<>(); + return !matching.isEmpty() + ? matching.entrySet().stream() + .flatMap(e -> e.getValue().stream()) + .distinct() + .collect(Collectors.toList()) + : new ArrayList<>(); } @Override @@ -63,10 +70,12 @@ if (matching == null) { throw new IllegalStateException(); } - return matching.values().stream().flatMap(Collection::stream) + return matching.values().stream() + .flatMap(Collection::stream) .filter(Candidate::complete) .filter(c -> exact.test(c.value())) - .findFirst().orElse(null); + .findFirst() + .orElse(null); } @Override @@ -84,8 +93,13 @@ /** * Default JLine matchers */ - protected void defaultMatchers(Map options, boolean prefix, CompletingParsedLine line - , boolean caseInsensitive, int errors, String originalGroupName) { + protected void defaultMatchers( + Map options, + boolean prefix, + CompletingParsedLine line, + boolean caseInsensitive, + int errors, + String originalGroupName) { // Find matchers // TODO: glob completion String wd = line.word(); @@ -94,8 +108,7 @@ if (prefix) { matchers = new ArrayList<>(Arrays.asList( simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).startsWith(wp)), - simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).contains(wp)) - )); + simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).contains(wp)))); if (LineReader.Option.COMPLETE_MATCHER_TYPO.isSet(options)) { matchers.add(typoMatcher(wp, errors, caseInsensitive, originalGroupName)); } @@ -109,14 +122,14 @@ Pattern p1 = Pattern.compile(Pattern.quote(wp) + ".*" + Pattern.quote(ws) + ".*"); Pattern p2 = Pattern.compile(".*" + Pattern.quote(wp) + ".*" + Pattern.quote(ws) + ".*"); matchers = new ArrayList<>(Arrays.asList( - simpleMatcher(s -> p1.matcher(caseInsensitive ? s.toLowerCase() : s).matches()), - simpleMatcher(s -> p2.matcher(caseInsensitive ? s.toLowerCase() : s).matches()) - )); + simpleMatcher(s -> p1.matcher(caseInsensitive ? s.toLowerCase() : s) + .matches()), + simpleMatcher(s -> p2.matcher(caseInsensitive ? s.toLowerCase() : s) + .matches()))); } else { matchers = new ArrayList<>(Arrays.asList( simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).startsWith(wdi)), - simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).contains(wdi)) - )); + simpleMatcher(s -> (caseInsensitive ? s.toLowerCase() : s).contains(wdi)))); } if (LineReader.Option.COMPLETE_MATCHER_CAMELCASE.isSet(options)) { matchers.add(simpleMatcher(s -> camelMatch(wd, 0, s, 0))); @@ -128,18 +141,20 @@ } } - protected Function>, - Map>> simpleMatcher(Predicate predicate) { + protected Function>, Map>> simpleMatcher( + Predicate predicate) { return m -> m.entrySet().stream() .filter(e -> predicate.test(e.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } - protected Function>, - Map>> typoMatcher(String word, int errors, boolean caseInsensitive, String originalGroupName) { + protected Function>, Map>> typoMatcher( + String word, int errors, boolean caseInsensitive, String originalGroupName) { return m -> { Map> map = m.entrySet().stream() - .filter(e -> ReaderUtils.distance(word, caseInsensitive ? e.getKey().toLowerCase() : e.getKey()) < errors) + .filter(e -> ReaderUtils.distance( + word, caseInsensitive ? e.getKey().toLowerCase() : e.getKey()) + < errors) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); if (map.size() > 1) { map.computeIfAbsent(word, w -> new ArrayList<>()) @@ -178,7 +193,8 @@ Map> sortedCandidates = new HashMap<>(); for (Candidate candidate : candidates) { sortedCandidates - .computeIfAbsent(AttributedString.fromAnsi(candidate.value()).toString(), s -> new ArrayList<>()) + .computeIfAbsent( + AttributedString.fromAnsi(candidate.value()).toString(), s -> new ArrayList<>()) .add(candidate); } return sortedCandidates; @@ -206,5 +222,4 @@ } return new String(s1, 0, len); } - -} \ No newline at end of file +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultExpander.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultExpander.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultExpander.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultExpander.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -32,27 +32,25 @@ if (unicode > 0) { escaped = (--unicode >= 0); sb.append(c); - } - else if (escaped) { + } else if (escaped) { if (c == 'u') { unicode = 4; } else { escaped = false; } sb.append(c); - } - else if (c == '\'') { + } else if (c == '\'') { inQuote = !inQuote; sb.append(c); - } - else if (inQuote) { + } else if (inQuote) { sb.append(c); - } - else { + } else { switch (c) { case '\\': - // any '\!' should be considered an expansion escape, so skip expansion and strip the escape character - // a leading '\^' should be considered an expansion escape, so skip expansion and strip the escape character + // any '\!' should be considered an expansion escape, so skip expansion and strip the escape + // character + // a leading '\^' should be considered an expansion escape, so skip expansion and strip the + // escape character // otherwise, add the escape escaped = true; sb.append(c); @@ -91,7 +89,8 @@ if (history.size() == 0) { throw new IllegalArgumentException("!$: event not found"); } - String previous = history.get(history.index() - 1).trim(); + String previous = + history.get(history.index() - 1).trim(); int lastSpace = previous.lastIndexOf(' '); if (lastSpace != -1) { rep = previous.substring(lastSpace + 1); @@ -128,14 +127,18 @@ try { idx = Integer.parseInt(line.substring(i1, i)); } catch (NumberFormatException e) { - throw new IllegalArgumentException((neg ? "!-" : "!") + line.substring(i1, i) + ": event not found"); + throw new IllegalArgumentException( + (neg ? "!-" : "!") + line.substring(i1, i) + ": event not found"); } if (neg && idx > 0 && idx <= history.size()) { rep = history.get(history.index() - idx); - } else if (!neg && idx > history.index() - history.size() && idx <= history.index()) { + } else if (!neg + && idx > history.index() - history.size() + && idx <= history.index()) { rep = history.get(idx - 1); } else { - throw new IllegalArgumentException((neg ? "!-" : "!") + line.substring(i1, i) + ": event not found"); + throw new IllegalArgumentException( + (neg ? "!-" : "!") + line.substring(i1, i) + ": event not found"); } break; default: diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultHighlighter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultHighlighter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultHighlighter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultHighlighter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -10,9 +10,9 @@ import java.util.regex.Pattern; +import jdk.internal.org.jline.reader.Highlighter; import jdk.internal.org.jline.reader.LineReader; import jdk.internal.org.jline.reader.LineReader.RegionType; -import jdk.internal.org.jline.reader.Highlighter; import jdk.internal.org.jline.utils.AttributedString; import jdk.internal.org.jline.utils.AttributedStringBuilder; import jdk.internal.org.jline.utils.AttributedStyle; @@ -57,7 +57,8 @@ while (negativeStart > 0 && reader.getBuffer().atChar(negativeStart - 1) != '\n') { negativeStart--; } - while (negativeEnd < reader.getBuffer().length() - 1 && reader.getBuffer().atChar(negativeEnd + 1) != '\n') { + while (negativeEnd < reader.getBuffer().length() - 1 + && reader.getBuffer().atChar(negativeEnd + 1) != '\n') { negativeEnd++; } } @@ -104,5 +105,4 @@ } return sb.toAttributedString(); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultParser.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultParser.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultParser.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/DefaultParser.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -21,18 +21,18 @@ public class DefaultParser implements Parser { public enum Bracket { - ROUND, // () - CURLY, // {} - SQUARE, // [] - ANGLE // <> + ROUND, // () + CURLY, // {} + SQUARE, // [] + ANGLE // <> } public static class BlockCommentDelims { private final String start; private final String end; + public BlockCommentDelims(String start, String end) { - if (start == null || end == null - || start.isEmpty() || end.isEmpty() || start.equals(end)) { + if (start == null || end == null || start.isEmpty() || end.isEmpty() || start.equals(end)) { throw new IllegalArgumentException("Bad block comment delimiter!"); } this.start = start; @@ -185,22 +185,22 @@ int i = 0; for (Bracket b : bs) { switch (b) { - case ROUND: - openingBrackets[i] = '('; - closingBrackets[i] = ')'; - break; - case CURLY: - openingBrackets[i] = '{'; - closingBrackets[i] = '}'; - break; - case SQUARE: - openingBrackets[i] = '['; - closingBrackets[i] = ']'; - break; - case ANGLE: - openingBrackets[i] = '<'; - closingBrackets[i] = '>'; - break; + case ROUND: + openingBrackets[i] = '('; + closingBrackets[i] = ')'; + break; + case CURLY: + openingBrackets[i] = '{'; + closingBrackets[i] = '}'; + break; + case SQUARE: + openingBrackets[i] = '['; + closingBrackets[i] = ']'; + break; + case ANGLE: + openingBrackets[i] = '<'; + closingBrackets[i] = '>'; + break; } i++; } @@ -229,7 +229,6 @@ return name != null && regexVariable != null && name.matches(regexVariable); } - @Override public String getCommand(final String line) { String out = ""; @@ -296,7 +295,7 @@ if (quoteStart < 0 && isQuoteChar(line, i) && !lineCommented && !blockCommented) { // Start a quote block quoteStart = i; - if (current.length()==0) { + if (current.length() == 0) { quotedWord = true; if (context == ParseContext.SPLIT_LINE) { current.append(line.charAt(i)); @@ -324,13 +323,15 @@ } } else { // Delimiter - rawWordLength = handleDelimiterAndGetRawWordLength(current, words, rawWordStart, rawWordCursor, rawWordLength, i); + rawWordLength = handleDelimiterAndGetRawWordLength( + current, words, rawWordStart, rawWordCursor, rawWordLength, i); rawWordStart = i + 1; } } else { if (quoteStart < 0 && !blockCommented && (lineCommented || isLineCommentStarted(line, i))) { lineCommented = true; - } else if (quoteStart < 0 && !lineCommented + } else if (quoteStart < 0 + && !lineCommented && (blockCommented || isCommentDelim(line, i, blockCommentStart))) { if (blockCommented) { if (blockCommentEnd != null && isCommentDelim(line, i, blockCommentEnd)) { @@ -339,12 +340,12 @@ } } else { blockCommented = true; - rawWordLength = handleDelimiterAndGetRawWordLength(current, words, rawWordStart, rawWordCursor, rawWordLength, i); + rawWordLength = handleDelimiterAndGetRawWordLength( + current, words, rawWordStart, rawWordCursor, rawWordLength, i); i += blockCommentStart == null ? 0 : blockCommentStart.length() - 1; rawWordStart = i + 1; } - } else if (quoteStart < 0 && !lineCommented - && isCommentDelim(line, i, blockCommentEnd)) { + } else if (quoteStart < 0 && !lineCommented && isCommentDelim(line, i, blockCommentEnd)) { current.append(line.charAt(i)); blockCommentInRightOrder = false; } else if (!isEscapeChar(line, i)) { @@ -377,16 +378,14 @@ throw new EOFError(-1, -1, "Escaped new line", "newline"); } if (eofOnUnclosedQuote && quoteStart >= 0) { - throw new EOFError(-1, -1, "Missing closing quote", line.charAt(quoteStart) == '\'' - ? "quote" : "dquote"); + throw new EOFError( + -1, -1, "Missing closing quote", line.charAt(quoteStart) == '\'' ? "quote" : "dquote"); } if (blockCommented) { - throw new EOFError(-1, -1, "Missing closing block comment delimiter", - "add: " + blockCommentEnd); + throw new EOFError(-1, -1, "Missing closing block comment delimiter", "add: " + blockCommentEnd); } if (!blockCommentInRightOrder) { - throw new EOFError(-1, -1, "Missing opening block comment delimiter", - "missing: " + blockCommentStart); + throw new EOFError(-1, -1, "Missing opening block comment delimiter", "missing: " + blockCommentStart); } if (bracketChecker.isClosingBracketMissing() || bracketChecker.isOpeningBracketMissing()) { String message = null; @@ -398,8 +397,13 @@ message = "Missing opening bracket"; missing = "missing: " + bracketChecker.getMissingOpeningBracket(); } - throw new EOFError(-1, -1, message, missing, - bracketChecker.getOpenBrackets(), bracketChecker.getNextClosingBracket()); + throw new EOFError( + -1, + -1, + message, + missing, + bracketChecker.getOpenBrackets(), + bracketChecker.getNextClosingBracket()); } } @@ -420,7 +424,13 @@ return !isQuoted(buffer, pos) && !isEscaped(buffer, pos) && isDelimiterChar(buffer, pos); } - private int handleDelimiterAndGetRawWordLength(StringBuilder current, List words, int rawWordStart, int rawWordCursor, int rawWordLength, int pos) { + private int handleDelimiterAndGetRawWordLength( + StringBuilder current, + List words, + int rawWordStart, + int rawWordCursor, + int rawWordLength, + int pos) { if (current.length() > 0) { words.add(current.toString()); current.setLength(0); // reset the arg @@ -470,7 +480,7 @@ public boolean isLineCommentStarted(final CharSequence buffer, final int pos) { if (lineCommentDelims != null) { - for (String comment: lineCommentDelims) { + for (String comment : lineCommentDelims) { if (isCommentDelim(buffer, pos, comment)) { return true; } @@ -584,8 +594,8 @@ } else { bid = bracketId(closingBrackets, buffer, pos); if (bid >= 0) { - if (!nested.isEmpty() && bid == nested.get(nested.size()-1)) { - nested.remove(nested.size()-1); + if (!nested.isEmpty() && bid == nested.get(nested.size() - 1)) { + nested.remove(nested.size() - 1); } else { missingOpeningBracket = bid; } @@ -634,7 +644,7 @@ } private int bracketId(final char[] brackets, final CharSequence buffer, final int pos) { - for (int i=0; i < brackets.length; i++) { + for (int i = 0; i < brackets.length; i++) { if (buffer.charAt(pos) == brackets[i]) { return i; } @@ -648,8 +658,7 @@ * * @author Marc Prud'hommeaux */ - public class ArgumentList implements ParsedLine, CompletingParsedLine - { + public class ArgumentList implements ParsedLine, CompletingParsedLine { private final String line; private final List words; @@ -667,11 +676,21 @@ private final int rawWordLength; @Deprecated - public ArgumentList(final String line, final List words, - final int wordIndex, final int wordCursor, - final int cursor) { - this(line, words, wordIndex, wordCursor, cursor, - null, wordCursor, words.get(wordIndex).length()); + public ArgumentList( + final String line, + final List words, + final int wordIndex, + final int wordCursor, + final int cursor) { + this( + line, + words, + wordIndex, + wordCursor, + cursor, + null, + wordCursor, + words.get(wordIndex).length()); } /** @@ -685,10 +704,15 @@ * @param rawWordCursor the cursor position inside the raw word (i.e. including quotes and escape characters) * @param rawWordLength the raw word length, including quotes and escape characters */ - public ArgumentList(final String line, final List words, - final int wordIndex, final int wordCursor, - final int cursor, final String openingQuote, - final int rawWordCursor, final int rawWordLength) { + public ArgumentList( + final String line, + final List words, + final int wordIndex, + final int wordCursor, + final int cursor, + final String openingQuote, + final int rawWordCursor, + final int rawWordLength) { this.line = line; this.words = Collections.unmodifiableList(Objects.requireNonNull(words)); this.wordIndex = wordIndex; @@ -732,8 +756,8 @@ Predicate needToBeEscaped; String quote = openingQuote; boolean middleQuotes = false; - if (openingQuote==null) { - for (int i=0; i < sb.length(); i++) { + if (openingQuote == null) { + for (int i = 0; i < sb.length(); i++) { if (isQuoteChar(sb, i)) { middleQuotes = true; break; @@ -746,7 +770,8 @@ // Delimiters (spaces) don't need to be escaped, nor do other quotes, but everything else does. // Also, close the quote at the end if (openingQuote != null) { - needToBeEscaped = i -> isRawEscapeChar(sb.charAt(i)) || String.valueOf(sb.charAt(i)).equals(openingQuote); + needToBeEscaped = i -> isRawEscapeChar(sb.charAt(i)) + || String.valueOf(sb.charAt(i)).equals(openingQuote); } // Completion is protected by middle quotes: // Delimiters (spaces) don't need to be escaped, nor do quotes, but everything else does. @@ -756,8 +781,8 @@ // No quote protection, need to escape everything: delimiter chars (spaces), quote chars // and escapes themselves else { - needToBeEscaped = i -> isDelimiterChar(sb, i) || isRawEscapeChar(sb.charAt(i)) - || isRawQuoteChar(sb.charAt(i)); + needToBeEscaped = i -> + isDelimiterChar(sb, i) || isRawEscapeChar(sb.charAt(i)) || isRawQuoteChar(sb.charAt(i)); } for (int i = 0; i < sb.length(); i++) { if (needToBeEscaped.test(i)) { @@ -792,5 +817,4 @@ return rawWordLength; } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/InputRC.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/InputRC.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/InputRC.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/InputRC.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,394 @@ +/* + * Copyright (c) 2002-2023, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.reader.impl; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import jdk.internal.org.jline.reader.LineReader; +import jdk.internal.org.jline.reader.Macro; +import jdk.internal.org.jline.reader.Reference; +import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.utils.Log; + +public final class InputRC { + + public static void configure(LineReader reader, URL url) throws IOException { + try (InputStream is = url.openStream()) { + configure(reader, is); + } + } + + public static void configure(LineReader reader, InputStream is) throws IOException { + try (InputStreamReader r = new InputStreamReader(is)) { + configure(reader, r); + } + } + + public static void configure(LineReader reader, Reader r) throws IOException { + BufferedReader br; + if (r instanceof BufferedReader) { + br = (BufferedReader) r; + } else { + br = new BufferedReader(r); + } + + Terminal terminal = reader.getTerminal(); + + if (Terminal.TYPE_DUMB.equals(terminal.getType()) || Terminal.TYPE_DUMB_COLOR.equals(terminal.getType())) { + reader.getVariables().putIfAbsent(LineReader.EDITING_MODE, "dumb"); + } else { + reader.getVariables().putIfAbsent(LineReader.EDITING_MODE, "emacs"); + } + + reader.setKeyMap(LineReader.MAIN); + new InputRC(reader).parse(br); + if ("vi".equals(reader.getVariable(LineReader.EDITING_MODE))) { + reader.getKeyMaps().put(LineReader.MAIN, reader.getKeyMaps().get(LineReader.VIINS)); + } else if ("emacs".equals(reader.getVariable(LineReader.EDITING_MODE))) { + reader.getKeyMaps().put(LineReader.MAIN, reader.getKeyMaps().get(LineReader.EMACS)); + } else if ("dumb".equals(reader.getVariable(LineReader.EDITING_MODE))) { + reader.getKeyMaps().put(LineReader.MAIN, reader.getKeyMaps().get(LineReader.DUMB)); + } + } + + private final LineReader reader; + + private InputRC(LineReader reader) { + this.reader = reader; + } + + private void parse(BufferedReader br) throws IOException, IllegalArgumentException { + String line; + boolean parsing = true; + List ifsStack = new ArrayList<>(); + while ((line = br.readLine()) != null) { + try { + line = line.trim(); + if (line.length() == 0) { + continue; + } + if (line.charAt(0) == '#') { + continue; + } + int i = 0; + if (line.charAt(i) == '$') { + String cmd; + String args; + ++i; + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + int s = i; + while (i < line.length() && (line.charAt(i) != ' ' && line.charAt(i) != '\t')) { + i++; + } + cmd = line.substring(s, i); + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + s = i; + while (i < line.length() && (line.charAt(i) != ' ' && line.charAt(i) != '\t')) { + i++; + } + args = line.substring(s, i); + if ("if".equalsIgnoreCase(cmd)) { + ifsStack.add(parsing); + if (!parsing) { + continue; + } + if (args.startsWith("term=")) { + // TODO + } else if (args.startsWith("mode=")) { + String mode = (String) reader.getVariable(LineReader.EDITING_MODE); + parsing = args.substring("mode=".length()).equalsIgnoreCase(mode); + } else { + parsing = args.equalsIgnoreCase(reader.getAppName()); + } + } else if ("else".equalsIgnoreCase(cmd)) { + if (ifsStack.isEmpty()) { + throw new IllegalArgumentException("$else found without matching $if"); + } + boolean invert = true; + for (boolean b : ifsStack) { + if (!b) { + invert = false; + break; + } + } + if (invert) { + parsing = !parsing; + } + } else if ("endif".equalsIgnoreCase(cmd)) { + if (ifsStack.isEmpty()) { + throw new IllegalArgumentException("endif found without matching $if"); + } + parsing = ifsStack.remove(ifsStack.size() - 1); + } else if ("include".equalsIgnoreCase(cmd)) { + // TODO + } + continue; + } + if (!parsing) { + continue; + } + if (line.charAt(i++) == '"') { + boolean esc = false; + for (; ; i++) { + if (i >= line.length()) { + throw new IllegalArgumentException("Missing closing quote on line '" + line + "'"); + } + if (esc) { + esc = false; + } else if (line.charAt(i) == '\\') { + esc = true; + } else if (line.charAt(i) == '"') { + break; + } + } + } + while (i < line.length() && line.charAt(i) != ':' && line.charAt(i) != ' ' && line.charAt(i) != '\t') { + i++; + } + String keySeq = line.substring(0, i); + boolean equivalency = i + 1 < line.length() && line.charAt(i) == ':' && line.charAt(i + 1) == '='; + i++; + if (equivalency) { + i++; + } + if (keySeq.equalsIgnoreCase("set")) { + String key; + String val; + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + int s = i; + while (i < line.length() && (line.charAt(i) != ' ' && line.charAt(i) != '\t')) { + i++; + } + key = line.substring(s, i); + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + s = i; + while (i < line.length() && (line.charAt(i) != ' ' && line.charAt(i) != '\t')) { + i++; + } + val = line.substring(s, i); + setVar(reader, key, val); + } else { + while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) { + i++; + } + int start = i; + if (i < line.length() && (line.charAt(i) == '\'' || line.charAt(i) == '\"')) { + char delim = line.charAt(i++); + boolean esc = false; + for (; ; i++) { + if (i >= line.length()) { + break; + } + if (esc) { + esc = false; + } else if (line.charAt(i) == '\\') { + esc = true; + } else if (line.charAt(i) == delim) { + break; + } + } + } + for (; i < line.length() && line.charAt(i) != ' ' && line.charAt(i) != '\t'; i++) + ; + String val = line.substring(Math.min(start, line.length()), Math.min(i, line.length())); + if (keySeq.charAt(0) == '"') { + keySeq = translateQuoted(keySeq); + } else { + // Bind key name + String keyName = + keySeq.lastIndexOf('-') > 0 ? keySeq.substring(keySeq.lastIndexOf('-') + 1) : keySeq; + char key = getKeyFromName(keyName); + keyName = keySeq.toLowerCase(); + keySeq = ""; + if (keyName.contains("meta-") || keyName.contains("m-")) { + keySeq += "\u001b"; + } + if (keyName.contains("control-") || keyName.contains("c-") || keyName.contains("ctrl-")) { + key = (char) (Character.toUpperCase(key) & 0x1f); + } + keySeq += key; + } + if (val.length() > 0 && (val.charAt(0) == '\'' || val.charAt(0) == '\"')) { + reader.getKeys().bind(new Macro(translateQuoted(val)), keySeq); + } else { + reader.getKeys().bind(new Reference(val), keySeq); + } + } + } catch (IllegalArgumentException e) { + Log.warn("Unable to parse user configuration: ", e); + } + } + } + + private static String translateQuoted(String keySeq) { + int i; + String str = keySeq.substring(1, keySeq.length() - 1); + StringBuilder sb = new StringBuilder(); + for (i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (c == '\\') { + boolean ctrl = str.regionMatches(i, "\\C-", 0, 3) || str.regionMatches(i, "\\M-\\C-", 0, 6); + boolean meta = str.regionMatches(i, "\\M-", 0, 3) || str.regionMatches(i, "\\C-\\M-", 0, 6); + i += (meta ? 3 : 0) + (ctrl ? 3 : 0) + (!meta && !ctrl ? 1 : 0); + if (i >= str.length()) { + break; + } + c = str.charAt(i); + if (meta) { + sb.append("\u001b"); + } + if (ctrl) { + c = c == '?' ? 0x7f : (char) (Character.toUpperCase(c) & 0x1f); + } + if (!meta && !ctrl) { + switch (c) { + case 'a': + c = 0x07; + break; + case 'b': + c = '\b'; + break; + case 'd': + c = 0x7f; + break; + case 'e': + c = 0x1b; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'v': + c = 0x0b; + break; + case '\\': + c = '\\'; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + c = 0; + for (int j = 0; j < 3; j++, i++) { + if (i >= str.length()) { + break; + } + int k = Character.digit(str.charAt(i), 8); + if (k < 0) { + break; + } + c = (char) (c * 8 + k); + } + c &= 0xFF; + break; + case 'x': + i++; + c = 0; + for (int j = 0; j < 2; j++, i++) { + if (i >= str.length()) { + break; + } + int k = Character.digit(str.charAt(i), 16); + if (k < 0) { + break; + } + c = (char) (c * 16 + k); + } + c &= 0xFF; + break; + case 'u': + i++; + c = 0; + for (int j = 0; j < 4; j++, i++) { + if (i >= str.length()) { + break; + } + int k = Character.digit(str.charAt(i), 16); + if (k < 0) { + break; + } + c = (char) (c * 16 + k); + } + break; + } + } + sb.append(c); + } else { + sb.append(c); + } + } + return sb.toString(); + } + + private static char getKeyFromName(String name) { + if ("DEL".equalsIgnoreCase(name) || "Rubout".equalsIgnoreCase(name)) { + return 0x7f; + } else if ("ESC".equalsIgnoreCase(name) || "Escape".equalsIgnoreCase(name)) { + return '\033'; + } else if ("LFD".equalsIgnoreCase(name) || "NewLine".equalsIgnoreCase(name)) { + return '\n'; + } else if ("RET".equalsIgnoreCase(name) || "Return".equalsIgnoreCase(name)) { + return '\r'; + } else if ("SPC".equalsIgnoreCase(name) || "Space".equalsIgnoreCase(name)) { + return ' '; + } else if ("Tab".equalsIgnoreCase(name)) { + return '\t'; + } else { + return name.charAt(0); + } + } + + static void setVar(LineReader reader, String key, String val) { + if (LineReader.KEYMAP.equalsIgnoreCase(key)) { + reader.setKeyMap(val); + return; + } + + for (LineReader.Option option : LineReader.Option.values()) { + if (option.name().toLowerCase(Locale.ENGLISH).replace('_', '-').equals(val)) { + if ("on".equalsIgnoreCase(val)) { + reader.setOpt(option); + } else if ("off".equalsIgnoreCase(val)) { + reader.unsetOpt(option); + } + return; + } + } + + reader.setVariable(key, val); + } +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/KillRing.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/KillRing.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/KillRing.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/KillRing.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/LineReaderImpl.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/LineReaderImpl.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/LineReaderImpl.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/LineReaderImpl.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2022, the original author or authors. + * Copyright (c) 2002-2023, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -18,6 +18,9 @@ import java.io.InputStream; import java.io.InterruptedIOException; import java.lang.reflect.Constructor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.time.Instant; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; @@ -56,6 +59,7 @@ import static jdk.internal.org.jline.keymap.KeyMap.esc; import static jdk.internal.org.jline.keymap.KeyMap.range; import static jdk.internal.org.jline.keymap.KeyMap.translate; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_DISABLE_ALTERNATE_CHARSET; /** * A reader for terminal applications. It supports custom tab-completion, @@ -66,23 +70,27 @@ * @author Guillaume Nodet */ @SuppressWarnings("StatementWithEmptyBody") -public class LineReaderImpl implements LineReader, Flushable -{ +public class LineReaderImpl implements LineReader, Flushable { public static final char NULL_MASK = 0; + /** + * @deprecated use {@link #DEFAULT_TAB_WIDTH} and {@link #getTabWidth()} + */ + @Deprecated public static final int TAB_WIDTH = 4; + public static final int DEFAULT_TAB_WIDTH = 4; public static final String DEFAULT_WORDCHARS = "*?_-.[]~=/&;!#$%^(){}<>"; public static final String DEFAULT_REMOVE_SUFFIX_CHARS = " \t\n;&|"; public static final String DEFAULT_COMMENT_BEGIN = "#"; public static final String DEFAULT_SEARCH_TERMINATORS = "\033\012"; public static final String DEFAULT_BELL_STYLE = ""; - public static final int DEFAULT_LIST_MAX = 100; - public static final int DEFAULT_MENU_LIST_MAX = Integer.MAX_VALUE; - public static final int DEFAULT_ERRORS = 2; - public static final long DEFAULT_BLINK_MATCHING_PAREN = 500L; - public static final long DEFAULT_AMBIGUOUS_BINDING = 1000L; + public static final int DEFAULT_LIST_MAX = 100; + public static final int DEFAULT_MENU_LIST_MAX = Integer.MAX_VALUE; + public static final int DEFAULT_ERRORS = 2; + public static final long DEFAULT_BLINK_MATCHING_PAREN = 500L; + public static final long DEFAULT_AMBIGUOUS_BINDING = 1000L; public static final String DEFAULT_SECONDARY_PROMPT_PATTERN = "%M> "; public static final String DEFAULT_OTHERS_GROUP_NAME = "others"; public static final String DEFAULT_ORIGINAL_GROUP_NAME = "original"; @@ -96,9 +104,10 @@ public static final String DEFAULT_COMPLETION_STYLE_LIST_GROUP = "fg:black,bold"; public static final String DEFAULT_COMPLETION_STYLE_LIST_SELECTION = DEFAULT_COMPLETION_STYLE_SELECTION; public static final String DEFAULT_COMPLETION_STYLE_LIST_BACKGROUND = "bg:bright-magenta"; - public static final int DEFAULT_INDENTATION = 0; - public static final int DEFAULT_FEATURES_MAX_BUFFER_SIZE = 1000; - public static final int DEFAULT_SUGGESTIONS_MIN_BUFFER_SIZE = 1; + public static final int DEFAULT_INDENTATION = 0; + public static final int DEFAULT_FEATURES_MAX_BUFFER_SIZE = 1000; + public static final int DEFAULT_SUGGESTIONS_MIN_BUFFER_SIZE = 1; + public static final String DEFAULT_SYSTEM_PROPERTY_PREFIX = "org.jline.reader.props."; private static final int MIN_ROWS = 3; @@ -109,6 +118,7 @@ public static final String FOCUS_IN_SEQ = "\033[I"; public static final String FOCUS_OUT_SEQ = "\033[O"; + public static final int DEFAULT_MAX_REPEAT_COUNT = 9999; /** * Possible states in which the current readline operation may be in. @@ -197,27 +207,28 @@ protected int searchIndex = -1; protected boolean doAutosuggestion; - // Reading buffers protected final BindingReader bindingReader; - /** * VI character find */ protected int findChar; + protected int findDir; protected int findTailAdd; /** * VI history string search */ private int searchDir; + private String searchString; /** * Region state */ protected int regionMark; + protected RegionType regionActive; private boolean forceChar; @@ -232,7 +243,7 @@ protected KillRing killRing = new KillRing(); - protected UndoTree undo = new UndoTree<>(this::setBuffer); + protected UndoTree undo; protected boolean isUndo; /** @@ -242,7 +253,7 @@ /* * Current internal state of the line reader */ - protected State state = State.DONE; + protected State state = State.DONE; protected final AtomicBoolean startedReading = new AtomicBoolean(); protected boolean reading; @@ -278,7 +289,10 @@ */ protected List commandsBuffer = new ArrayList<>(); - int candidateStartPosition = 0; + protected int candidateStartPosition = 0; + + protected String alternateIn; + protected String alternateOut; public LineReaderImpl(Terminal terminal) throws IOException { this(terminal, terminal.getName(), null); @@ -288,6 +302,7 @@ this(terminal, appName, null); } + @SuppressWarnings("this-escape") public LineReaderImpl(Terminal terminal, String appName, Map variables) { Objects.requireNonNull(terminal, "terminal can not be null"); this.terminal = terminal; @@ -300,11 +315,40 @@ } else { this.variables = new HashMap<>(); } + String prefix = getString(SYSTEM_PROPERTY_PREFIX, DEFAULT_SYSTEM_PROPERTY_PREFIX); + if (prefix != null) { + Properties sysProps = System.getProperties(); + for (String s : sysProps.stringPropertyNames()) { + if (s.startsWith(prefix)) { + String key = s.substring(prefix.length()); + InputRC.setVar(this, key, sysProps.getProperty(s)); + } + } + } + this.keyMaps = defaultKeyMaps(); + if (!Boolean.getBoolean(PROP_DISABLE_ALTERNATE_CHARSET)) { + this.alternateIn = Curses.tputs(terminal.getStringCapability(Capability.enter_alt_charset_mode)); + this.alternateOut = Curses.tputs(terminal.getStringCapability(Capability.exit_alt_charset_mode)); + } + undo = new UndoTree<>(this::setBuffer); builtinWidgets = builtinWidgets(); widgets = new HashMap<>(builtinWidgets); bindingReader = new BindingReader(terminal.reader()); + + String inputRc = getString(INPUT_RC_FILE_NAME, null); + if (inputRc != null) { + Path inputRcPath = Paths.get(inputRc); + if (Files.exists(inputRcPath)) { + try (InputStream is = Files.newInputStream(inputRcPath)) { + InputRC.configure(this, is); + } catch (Exception e) { + Log.debug("Error reading inputRc config file: ", inputRc, e); + } + } + } + doDisplay(); } @@ -489,7 +533,8 @@ * @param buffer A string that will be set for editing. * @return A line that is read from the terminal, can never be null. */ - public String readLine(String prompt, Character mask, String buffer) throws UserInterruptException, EndOfFileException { + public String readLine(String prompt, Character mask, String buffer) + throws UserInterruptException, EndOfFileException { return readLine(prompt, null, mask, buffer); } @@ -503,7 +548,8 @@ * @param buffer A string that will be set for editing. * @return A line that is read from the terminal, can never be null. */ - public String readLine(String prompt, String rightPrompt, Character mask, String buffer) throws UserInterruptException, EndOfFileException { + public String readLine(String prompt, String rightPrompt, Character mask, String buffer) + throws UserInterruptException, EndOfFileException { return readLine(prompt, rightPrompt, mask != null ? new SimpleMaskingCallback(mask) : null, buffer); } @@ -517,7 +563,8 @@ * @param buffer A string that will be set for editing. * @return A line that is read from the terminal, can never be null. */ - public String readLine(String prompt, String rightPrompt, MaskingCallback maskingCallback, String buffer) throws UserInterruptException, EndOfFileException { + public String readLine(String prompt, String rightPrompt, MaskingCallback maskingCallback, String buffer) + throws UserInterruptException, EndOfFileException { // prompt may be null // maskingCallback may be null // buffer may be null @@ -618,23 +665,14 @@ // Move into application mode if (!dumb) { terminal.puts(Capability.keypad_xmit); - if (isSet(Option.AUTO_FRESH_LINE)) - callWidget(FRESH_LINE); - if (isSet(Option.MOUSE)) - terminal.trackMouse(Terminal.MouseTracking.Normal); - if (isSet(Option.BRACKETED_PASTE)) - terminal.writer().write(BRACKETED_PASTE_ON); - } else { - // For dumb terminals, we need to make sure that CR are ignored - Attributes attr = new Attributes(originalAttributes); - attr.setInputFlag(Attributes.InputFlag.IGNCR, true); - terminal.setAttributes(attr); + if (isSet(Option.AUTO_FRESH_LINE)) callWidget(FRESH_LINE); + if (isSet(Option.MOUSE)) terminal.trackMouse(Terminal.MouseTracking.Normal); + if (isSet(Option.BRACKETED_PASTE)) terminal.writer().write(BRACKETED_PASTE_ON); } callWidget(CALLBACK_INIT); - if (!isSet(Option.DISABLE_UNDO)) - undo.newState(buf.copy()); + if (!isSet(Option.DISABLE_UNDO)) undo.newState(buf.copy()); // Draw initial prompt redrawLine(); @@ -654,7 +692,8 @@ throw new EndOfFileException().partialLine(buf.length() > 0 ? buf.toString() : null); } Log.trace("Binding: ", o); - if (buf.length() == 0 && getLastBinding().charAt(0) == originalAttributes.getControlChar(ControlChar.VEOF)) { + if (buf.length() == 0 + && getLastBinding().charAt(0) == originalAttributes.getControlChar(ControlChar.VEOF)) { throw new EndOfFileException(); } @@ -675,12 +714,17 @@ try { lock.lock(); // Get executable widget - Buffer copy = buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE) ? buf.copy() : null; + Buffer copy = buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE) + ? buf.copy() + : null; Widget w = getWidget(o); if (!w.apply()) { beep(); } - if (!isSet(Option.DISABLE_UNDO) && !isUndo && copy != null && buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE) + if (!isSet(Option.DISABLE_UNDO) + && !isUndo + && copy != null + && buf.length() <= getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE) && !copy.toString().equals(buf.toString())) { undo.newState(buf.copy()); } @@ -718,13 +762,18 @@ } else { throw e; } - } - finally { + } finally { + AtomicBoolean interrupted = new AtomicBoolean(Thread.interrupted()); try { lock.lock(); this.reading = false; + Terminal.SignalHandler tmpHandler = terminal.handle(Signal.INT, s -> interrupted.set(true)); + if (previousIntrHandler == null) { + previousIntrHandler = tmpHandler; + } + cleanup(); if (originalAttributes != null) { terminal.setAttributes(originalAttributes); @@ -741,13 +790,15 @@ } finally { lock.unlock(); startedReading.set(false); + if (interrupted.get()) { + Thread.currentThread().interrupt(); + } } } } private boolean isTerminalDumb() { - return Terminal.TYPE_DUMB.equals(terminal.getType()) - || Terminal.TYPE_DUMB_COLOR.equals(terminal.getType()); + return Terminal.TYPE_DUMB.equals(terminal.getType()) || Terminal.TYPE_DUMB_COLOR.equals(terminal.getType()); } private void doDisplay() { @@ -757,8 +808,7 @@ display = new Display(terminal, false); display.resize(size.getRows(), size.getColumns()); - if (isSet(Option.DELAY_LINE_WRAP)) - display.setDelayLineWrap(true); + if (isSet(Option.DELAY_LINE_WRAP)) display.setDelayLineWrap(true); } @Override @@ -965,8 +1015,10 @@ if (!YANK_POP.equals(ref) && !YANK.equals(ref)) { killRing.resetLastYank(); } - if (!KILL_LINE.equals(ref) && !KILL_WHOLE_LINE.equals(ref) - && !BACKWARD_KILL_WORD.equals(ref) && !KILL_WORD.equals(ref)) { + if (!KILL_LINE.equals(ref) + && !KILL_WHOLE_LINE.equals(ref) + && !BACKWARD_KILL_WORD.equals(ref) + && !KILL_WORD.equals(ref)) { killRing.resetLastKill(); } } @@ -1083,7 +1135,7 @@ if (isSet(Option.BRACKETED_PASTE)) { terminal.writer().write(BRACKETED_PASTE_OFF); } - Constructor ctor = Class.forName("jdk.internal.org.jline.builtins.Nano").getConstructor(Terminal.class, File.class); + Constructor ctor = Class.forName("org.jline.builtins.Nano").getConstructor(Terminal.class, File.class); Editor editor = (Editor) ctor.newInstance(terminal, new File(file.getParent())); editor.setRestricted(true); editor.open(Collections.singletonList(file.getName())); @@ -1097,6 +1149,10 @@ } } + protected int getTabWidth() { + return getInt(LineReader.TAB_WIDTH, DEFAULT_TAB_WIDTH); + } + // // Widget implementation // @@ -1137,26 +1193,27 @@ } // we only add it to the history if the buffer is not empty - if (historyLine != null && historyLine.length() > 0 ) { + if (historyLine != null && historyLine.length() > 0) { history.add(Instant.now(), historyLine); } return str; } - protected void handleSignal(Signal signal) { + protected synchronized void handleSignal(Signal signal) { doAutosuggestion = false; if (signal == Signal.WINCH) { + size.copy(terminal.getBufferSize()); + display.resize(size.getRows(), size.getColumns()); Status status = Status.getStatus(terminal, false); if (status != null) { - status.hardReset(); + status.resize(size); + status.reset(); } - size.copy(terminal.getBufferSize()); - display.resize(size.getRows(), size.getColumns()); - // restores prompt but also prevents scrolling in consoleZ, see #492 - // redrawLine(); + terminal.puts(Capability.carriage_return); + terminal.puts(Capability.clr_eos); + redrawLine(); redisplay(); - } - else if (signal == Signal.CONT) { + } else if (signal == Signal.CONT) { terminal.enterRawMode(); size.copy(terminal.getBufferSize()); display.resize(size.getRows(), size.getColumns()); @@ -1200,13 +1257,11 @@ // public void setPrompt(final String prompt) { - this.prompt = (prompt == null ? AttributedString.EMPTY - : expandPromptPattern(prompt, 0, "", 0)); + this.prompt = (prompt == null ? AttributedString.EMPTY : expandPromptPattern(prompt, 0, "", 0)); } public void setRightPrompt(final String rightPrompt) { - this.rightPrompt = (rightPrompt == null ? AttributedString.EMPTY - : expandPromptPattern(rightPrompt, 0, "", 0)); + this.rightPrompt = (rightPrompt == null ? AttributedString.EMPTY : expandPromptPattern(rightPrompt, 0, "", 0)); } protected void setBuffer(Buffer buffer) { @@ -1233,7 +1288,7 @@ * @param op The incoming operation to remap * @return The remaped operation */ - protected String viDeleteChangeYankToRemap (String op) { + protected String viDeleteChangeYankToRemap(String op) { switch (op) { case SEND_BREAK: case BACKWARD_CHAR: @@ -1292,7 +1347,6 @@ return VICMD.equals(keyMap); } - // // Movement // @@ -1332,7 +1386,6 @@ return true; } - // // Word movement // @@ -1365,9 +1418,7 @@ buf.move(1); } } else { - while (buf.cursor() < buf.length() - && !isViAlphaNum(buf.currChar()) - && !isWhitespace(buf.currChar())) { + while (buf.cursor() < buf.length() && !isViAlphaNum(buf.currChar()) && !isWhitespace(buf.currChar())) { buf.move(1); } } @@ -1375,9 +1426,7 @@ return true; } int nl = buf.currChar() == '\n' ? 1 : 0; - while (buf.cursor() < buf.length() - && nl < 2 - && isWhitespace(buf.currChar())) { + while (buf.cursor() < buf.length() && nl < 2 && isWhitespace(buf.currChar())) { buf.move(1); nl += buf.currChar() == '\n' ? 1 : 0; } @@ -1397,9 +1446,7 @@ return true; } int nl = buf.currChar() == '\n' ? 1 : 0; - while (buf.cursor() < buf.length() - && nl < 2 - && isWhitespace(buf.currChar())) { + while (buf.cursor() < buf.length() && nl < 2 && isWhitespace(buf.currChar())) { buf.move(1); nl += buf.currChar() == '\n' ? 1 : 0; } @@ -1451,7 +1498,9 @@ } } else { buf.move(1); - while (buf.cursor() < buf.length() && !isViAlphaNum(buf.nextChar()) && !isWhitespace(buf.nextChar())) { + while (buf.cursor() < buf.length() + && !isViAlphaNum(buf.nextChar()) + && !isWhitespace(buf.nextChar())) { buf.move(1); } } @@ -1720,9 +1769,7 @@ buf.move(1); } while (buf.cursor() < buf.length() && isWord(buf.currChar())) { - buf.currChar(first - ? Character.toUpperCase(buf.currChar()) - : Character.toLowerCase(buf.currChar())); + buf.currChar(first ? Character.toUpperCase(buf.currChar()) : Character.toLowerCase(buf.currChar())); buf.move(1); first = false; } @@ -1810,7 +1857,8 @@ sta1--; } end1 = sta1; - while (end1 < lend && !isDelimiter(buf.atChar(++end1))); + while (end1 < lend && !isDelimiter(buf.atChar(++end1))) + ; if (neg) { end2 = sta1 - 1; while (end2 > lstart && isDelimiter(buf.atChar(end2 - 1))) { @@ -1819,9 +1867,11 @@ if (end2 < lstart) { // No word before, use the word after sta2 = end1; - while (isDelimiter(buf.atChar(++sta2))); + while (isDelimiter(buf.atChar(++sta2))) + ; end2 = sta2; - while (end2 < lend && !isDelimiter(buf.atChar(++end2))); + while (end2 < lend && !isDelimiter(buf.atChar(++end2))) + ; } else { sta2 = end2; while (sta2 > lstart && !isDelimiter(buf.atChar(sta2 - 1))) { @@ -1830,7 +1880,8 @@ } } else { sta2 = end1; - while (sta2 < lend && isDelimiter(buf.atChar(++sta2))); + while (sta2 < lend && isDelimiter(buf.atChar(++sta2))) + ; if (sta2 == lend) { // No word after, use the word before end2 = sta1; @@ -1843,19 +1894,24 @@ } } else { end2 = sta2; - while (end2 < lend && !isDelimiter(buf.atChar(++end2))) ; + while (end2 < lend && !isDelimiter(buf.atChar(++end2))) + ; } } if (sta1 < sta2) { - String res = buf.substring(0, sta1) + buf.substring(sta2, end2) - + buf.substring(end1, sta2) + buf.substring(sta1, end1) + String res = buf.substring(0, sta1) + + buf.substring(sta2, end2) + + buf.substring(end1, sta2) + + buf.substring(sta1, end1) + buf.substring(end2); buf.clear(); buf.write(res); buf.cursor(neg ? end1 : end2); } else { - String res = buf.substring(0, sta2) + buf.substring(sta1, end1) - + buf.substring(end2, sta1) + buf.substring(sta2, end2) + String res = buf.substring(0, sta2) + + buf.substring(sta1, end1) + + buf.substring(end2, sta1) + + buf.substring(sta2, end2) + buf.substring(end1); buf.clear(); buf.write(res); @@ -1988,11 +2044,11 @@ while (count-- > 0) { do { buf.move(findDir); - } while (buf.cursor() > 0 && buf.cursor() < buf.length() + } while (buf.cursor() > 0 + && buf.cursor() < buf.length() && buf.currChar() != findChar && buf.currChar() != '\n'); - if (buf.cursor() <= 0 || buf.cursor() >= buf.length() - || buf.currChar() == '\n') { + if (buf.cursor() <= 0 || buf.cursor() >= buf.length() || buf.currChar() == '\n') { buf.cursor(cursor); return false; } @@ -2211,18 +2267,17 @@ * character or if there was no matching bracket. */ protected boolean doViMatchBracket() { - int pos = buf.cursor(); + int pos = buf.cursor(); if (pos == buf.length()) { return false; } - int type = getBracketType(buf.atChar(pos)); - int move = (type < 0) ? -1 : 1; - int count = 1; + int type = getBracketType(buf.atChar(pos)); + int move = (type < 0) ? -1 : 1; + int count = 1; - if (type == 0) - return false; + if (type == 0) return false; while (count > 0) { pos += move; @@ -2235,8 +2290,7 @@ int curType = getBracketType(buf.atChar(pos)); if (curType == type) { ++count; - } - else if (curType == -type) { + } else if (curType == -type) { --count; } } @@ -2245,8 +2299,7 @@ * Slight adjustment for delete-to, yank-to, change-to to ensure * that the matching paren is consumed */ - if (move > 0 && isInViMoveOperation()) - ++pos; + if (move > 0 && isInViMoveOperation()) ++pos; buf.cursor(pos); return true; @@ -2259,14 +2312,20 @@ * @return 1 is square, 2 curly, 3 parent, or zero for none. The value * will be negated if it is the closing form of the bracket. */ - protected int getBracketType (int ch) { + protected int getBracketType(int ch) { switch (ch) { - case '[': return 1; - case ']': return -1; - case '{': return 2; - case '}': return -2; - case '(': return 3; - case ')': return -3; + case '[': + return 1; + case ']': + return -1; + case '{': + return 2; + case '}': + return -2; + case '(': + return 3; + case ')': + return -3; default: return 0; } @@ -2331,7 +2390,7 @@ buf.clear(); println(); redrawLine(); -// state = State.INTERRUPT; + // state = State.INTERRUPT; return false; } return true; @@ -2378,6 +2437,10 @@ protected boolean digitArgument() { String s = getLastBinding(); repeatCount = (repeatCount * 10) + s.charAt(s.length() - 1) - '0'; + int maxRepeatCount = getInt(MAX_REPEAT_COUNT, DEFAULT_MAX_REPEAT_COUNT); + if (repeatCount > maxRepeatCount) { + throw new IllegalArgumentException("digit argument should be less than " + maxRepeatCount); + } isArgDigit = true; return true; } @@ -2438,10 +2501,12 @@ protected boolean viYankWholeLine() { int s, e; int p = buf.cursor(); - while (buf.move(-1) == -1 && buf.prevChar() != '\n') ; + while (buf.move(-1) == -1 && buf.prevChar() != '\n') + ; s = buf.cursor(); for (int i = 0; i < repeatCount; i++) { - while (buf.move(1) == 1 && buf.prevChar() != '\n') ; + while (buf.move(1) == 1 && buf.prevChar() != '\n') + ; } e = buf.cursor(); yankBuffer = buf.substring(s, e); @@ -2554,15 +2619,19 @@ return doSearchHistory(true); } - static class Pair { - final U u; final V v; + static class Pair { + final U u; + final V v; + public Pair(U u, V v) { this.u = u; this.v = v; } + public U getU() { return u; } + public V getV() { return v; } @@ -2575,7 +2644,8 @@ KeyMap terminators = new KeyMap<>(); getString(SEARCH_TERMINATORS, DEFAULT_SEARCH_TERMINATORS) - .codePoints().forEach(c -> bind(terminators, ACCEPT_LINE, new String(Character.toChars(c)))); + .codePoints() + .forEach(c -> bind(terminators, ACCEPT_LINE, new String(Character.toChars(c)))); Buffer originalBuffer = buf.copy(); searchIndex = -1; @@ -2583,8 +2653,8 @@ searchBackward = backward; searchFailing = false; post = () -> new AttributedString((searchFailing ? "failing" + " " : "") - + (searchBackward ? "bck-i-search" : "fwd-i-search") - + ": " + searchTerm + "_"); + + (searchBackward ? "bck-i-search" : "fwd-i-search") + + ": " + searchTerm + "_"); redisplay(); try { @@ -2630,8 +2700,9 @@ searchFailing = false; } else { boolean caseInsensitive = isSet(Option.CASE_INSENSITIVE_SEARCH); - Pattern pat = Pattern.compile(pattern, caseInsensitive ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE - : Pattern.UNICODE_CASE); + Pattern pat = Pattern.compile( + pattern, + caseInsensitive ? Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE : Pattern.UNICODE_CASE); Pair pair = null; if (searchBackward) { boolean nextOnly = next; @@ -2641,7 +2712,11 @@ .orElse(null); if (pair == null) { pair = StreamSupport.stream( - Spliterators.spliteratorUnknownSize(history.reverseIterator(searchIndex < 0 ? history.last() : searchIndex - 1), Spliterator.ORDERED), false) + Spliterators.spliteratorUnknownSize( + history.reverseIterator( + searchIndex < 0 ? history.last() : searchIndex - 1), + Spliterator.ORDERED), + false) .flatMap(e -> matches(pat, e.line(), e.index()).stream()) .findFirst() .orElse(null); @@ -2654,7 +2729,11 @@ .orElse(null); if (pair == null) { pair = StreamSupport.stream( - Spliterators.spliteratorUnknownSize(history.iterator((searchIndex < 0 ? history.last() : searchIndex) + 1), Spliterator.ORDERED), false) + Spliterators.spliteratorUnknownSize( + history.iterator( + (searchIndex < 0 ? history.last() : searchIndex) + 1), + Spliterator.ORDERED), + false) .flatMap(e -> matches(pat, e.line(), e.index()).stream()) .findFirst() .orElse(null); @@ -2714,7 +2793,10 @@ sb.append("\\E"); inQuote = false; } - sb.append("[").append(Character.toLowerCase(c)).append(Character.toUpperCase(c)).append("]"); + sb.append("[") + .append(Character.toLowerCase(c)) + .append(Character.toUpperCase(c)) + .append("]"); } else { if (!inQuote) { sb.append("\\Q"); @@ -2742,8 +2824,7 @@ } protected boolean historySearchForward() { - if (historyBuffer == null || buf.length() == 0 - || !buf.toString().equals(history.current())) { + if (historyBuffer == null || buf.length() == 0 || !buf.toString().equals(history.current())) { historyBuffer = buf.copy(); searchBuffer = getFirstWord(); } @@ -2791,8 +2872,7 @@ } protected boolean historySearchBackward() { - if (historyBuffer == null || buf.length() == 0 - || !buf.toString().equals(history.current())) { + if (historyBuffer == null || buf.length() == 0 || !buf.toString().equals(history.current())) { historyBuffer = buf.copy(); searchBuffer = getFirstWord(); } @@ -2984,7 +3064,7 @@ } void indention(int nb, StringBuilder sb) { - int indent = getInt(INDENTATION, DEFAULT_INDENTATION)*nb; + int indent = getInt(INDENTATION, DEFAULT_INDENTATION) * nb; for (int i = 0; i < indent; i++) { sb.append(' '); } @@ -3017,7 +3097,6 @@ return true; } - // // History Control // @@ -3108,13 +3187,11 @@ } protected boolean viUpLineOrHistory() { - return upLine() - || upHistory() && viFirstNonBlank(); + return upLine() || upHistory() && viFirstNonBlank(); } protected boolean viDownLineOrHistory() { - return downLine() - || downHistory() && viFirstNonBlank(); + return downLine() || downHistory() && viFirstNonBlank(); } protected boolean upLine() { @@ -3175,8 +3252,7 @@ } protected boolean viChangeEol() { - return viChange(buf.cursor(), buf.length()) - && setKeyMap(VIINS); + return viChange(buf.cursor(), buf.length()) && setKeyMap(VIINS); } protected boolean viKillEol() { @@ -3199,7 +3275,8 @@ protected boolean viJoin() { if (buf.down()) { - while (buf.move(-1) == -1 && buf.prevChar() != '\n') ; + while (buf.move(-1) == -1 && buf.prevChar() != '\n') + ; buf.backspace(); buf.write(' '); buf.move(-1); @@ -3253,14 +3330,16 @@ protected boolean beginningOfLine() { while (count-- > 0) { - while (buf.move(-1) == -1 && buf.prevChar() != '\n') ; + while (buf.move(-1) == -1 && buf.prevChar() != '\n') + ; } return true; } protected boolean endOfLine() { while (count-- > 0) { - while (buf.move(1) == 1 && buf.currChar() != '\n') ; + while (buf.move(1) == 1 && buf.currChar() != '\n') + ; } return true; } @@ -3384,7 +3463,7 @@ // what is really happening is that if we are in "move-mode" then the // cursor can't be moved off the end of the line, but in "edit-mode" it // is ok, but I have no easy way of knowing which mode we are in. - if (! isChange && startPos > 0 && startPos == buf.length()) { + if (!isChange && startPos > 0 && startPos == buf.length()) { buf.move(-1); } return true; @@ -3424,14 +3503,16 @@ } protected boolean viOpenLineAbove() { - while (buf.move(-1) == -1 && buf.prevChar() != '\n') ; + while (buf.move(-1) == -1 && buf.prevChar() != '\n') + ; buf.write('\n'); buf.move(-1); return setKeyMap(VIINS); } protected boolean viOpenLineBelow() { - while (buf.move(1) == 1 && buf.currChar() != '\n') ; + while (buf.move(1) == 1 && buf.currChar() != '\n') + ; buf.write('\n'); return setKeyMap(VIINS); } @@ -3443,11 +3524,12 @@ */ protected boolean viPutAfter() { if (yankBuffer.indexOf('\n') >= 0) { - while (buf.move(1) == 1 && buf.currChar() != '\n'); + while (buf.move(1) == 1 && buf.currChar() != '\n') + ; buf.move(1); putString(yankBuffer); - buf.move(- yankBuffer.length()); - } else if (yankBuffer.length () != 0) { + buf.move(-yankBuffer.length()); + } else if (yankBuffer.length() != 0) { if (buf.cursor() < buf.length()) { buf.move(1); } @@ -3461,10 +3543,11 @@ protected boolean viPutBefore() { if (yankBuffer.indexOf('\n') >= 0) { - while (buf.move(-1) == -1 && buf.prevChar() != '\n'); + while (buf.move(-1) == -1 && buf.prevChar() != '\n') + ; putString(yankBuffer); - buf.move(- yankBuffer.length()); - } else if (yankBuffer.length () != 0) { + buf.move(-yankBuffer.length()); + } else if (yankBuffer.length() != 0) { if (buf.cursor() > 0) { buf.move(-1); } @@ -3681,7 +3764,7 @@ addBuiltinWidget(widgets, MENU_EXPAND_OR_COMPLETE, this::menuExpandOrComplete); addBuiltinWidget(widgets, NEG_ARGUMENT, this::negArgument); addBuiltinWidget(widgets, OVERWRITE_MODE, this::overwriteMode); -// addBuiltinWidget(widgets, QUIT, this::quit); + // addBuiltinWidget(widgets, QUIT, this::quit); addBuiltinWidget(widgets, QUOTED_INSERT, this::quotedInsert); addBuiltinWidget(widgets, REDISPLAY, this::redisplay); addBuiltinWidget(widgets, REDRAW_LINE, this::redrawLine); @@ -3774,6 +3857,7 @@ public String toString() { return name; } + @Override public boolean apply() { return widget.apply(); @@ -3797,14 +3881,11 @@ Status status = Status.getStatus(terminal, false); if (status != null) { - if (terminal.getType().startsWith(AbstractWindowsTerminal.TYPE_WINDOWS)) { - status.resize(); - } status.redraw(); } if (size.getRows() > 0 && size.getRows() < MIN_ROWS) { - AttributedStringBuilder sb = new AttributedStringBuilder().tabs(TAB_WIDTH); + AttributedStringBuilder sb = new AttributedStringBuilder().tabs(getTabWidth()); sb.append(prompt); concat(getHighlightedBuffer(buf.toString()).columnSplitLength(Integer.MAX_VALUE), sb); @@ -3877,14 +3958,15 @@ int cursorNewLinesId = -1; int cursorColPos = -1; if (size.getColumns() > 0) { - AttributedStringBuilder sb = new AttributedStringBuilder().tabs(TAB_WIDTH); + AttributedStringBuilder sb = new AttributedStringBuilder().tabs(getTabWidth()); sb.append(prompt); String buffer = buf.upToCursor(); if (maskingCallback != null) { buffer = maskingCallback.display(buffer); } sb.append(insertSecondaryPrompts(new AttributedString(buffer), secondaryPrompts, false)); - List promptLines = sb.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); + List promptLines = + sb.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); if (!promptLines.isEmpty()) { cursorNewLinesId = promptLines.size() - 1; cursorColPos = promptLines.get(promptLines.size() - 1).columnLength(); @@ -3904,7 +3986,7 @@ int lineId = newLines.size() - displaySize + 1; int endId = displaySize; int startId = 1; - if (lineId > cursorNewLinesId) { + if (lineId > cursorNewLinesId) { lineId = cursorNewLinesId; endId = displaySize - 1; startId = 0; @@ -3949,10 +4031,9 @@ } History history = getHistory(); StringBuilder sb = new StringBuilder(); - for (char c: buffer.replace("\\", "\\\\").toCharArray()) { - if (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '*' - || c == '$' || c == '.' || c == '?' || c == '+' || c == '|' || c == '<' || c == '>' || c == '!' - || c == '-') { + for (char c : buffer.replace("\\", "\\\\").toCharArray()) { + if (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == '^' || c == '*' || c == '$' + || c == '.' || c == '?' || c == '+' || c == '|' || c == '<' || c == '>' || c == '!' || c == '-') { sb.append('\\'); } sb.append(c); @@ -3984,7 +4065,7 @@ AttributedString attBuf = getHighlightedBuffer(buf.toString()); AttributedString tNewBuf = insertSecondaryPrompts(attBuf, secondaryPrompts); - AttributedStringBuilder full = new AttributedStringBuilder().tabs(TAB_WIDTH); + AttributedStringBuilder full = new AttributedStringBuilder().tabs(getTabWidth()); full.append(prompt); full.append(tNewBuf); if (doAutosuggestion && !isTerminalDumb()) { @@ -4040,15 +4121,15 @@ if (maskingCallback != null) { buffer = maskingCallback.display(buffer); } - if (highlighter != null && !isSet(Option.DISABLE_HIGHLIGHTER) + if (highlighter != null + && !isSet(Option.DISABLE_HIGHLIGHTER) && buffer.length() < getInt(FEATURES_MAX_BUFFER_SIZE, DEFAULT_FEATURES_MAX_BUFFER_SIZE)) { return highlighter.highlight(this, buffer); } return new AttributedString(buffer); } - private AttributedString expandPromptPattern(String pattern, int padToWidth, - String message, int line) { + private AttributedString expandPromptPattern(String pattern, int padToWidth, String message, int line) { ArrayList parts = new ArrayList<>(); boolean isHidden = false; int padPartIndex = -1; @@ -4065,7 +4146,8 @@ if (ch == '%' && i < plen) { int count = 0; boolean countSeen = false; - decode: while (true) { + decode: + while (true) { ch = pattern.charAt(i++); switch (ch) { case '{': @@ -4073,7 +4155,7 @@ String str = sb.toString(); AttributedString astr; if (!isHidden) { - astr = AttributedString.fromAnsi(str); + astr = fromAnsi(str); cols += astr.columnLength(); } else { astr = new AttributedString(str, AttributedStyle.HIDDEN); @@ -4096,12 +4178,10 @@ sb.append(getInt(LINE_OFFSET, 0) + line); break decode; case 'M': - if (message != null) - sb.append(message); + if (message != null) sb.append(message); break decode; case 'P': - if (countSeen && count >= 0) - padToWidth = count; + if (countSeen && count >= 0) padToWidth = count; if (i < plen) { padChar = pattern.charAt(i++); // FIXME check surrogate @@ -4140,25 +4220,28 @@ break decode; } } - } else - sb.append(ch); + } else sb.append(ch); } if (padToWidth > cols && padToWidth > 0) { int padCharCols = WCWidth.wcwidth(padChar); int padCount = (padToWidth - cols) / padCharCols; sb = padPartString; - while (--padCount >= 0) - sb.insert(padPos, (char) padChar); // FIXME if wide - parts.set(padPartIndex, AttributedString.fromAnsi(sb.toString())); + while (--padCount >= 0) sb.insert(padPos, (char) padChar); // FIXME if wide + parts.set(padPartIndex, fromAnsi(sb.toString())); } return AttributedString.join(null, parts); } + private AttributedString fromAnsi(String str) { + return AttributedString.fromAnsi(str, Collections.singletonList(0), alternateIn, alternateOut); + } + private AttributedString insertSecondaryPrompts(AttributedString str, List prompts) { return insertSecondaryPrompts(str, prompts, true); } - private AttributedString insertSecondaryPrompts(AttributedString strAtt, List prompts, boolean computePrompts) { + private AttributedString insertSecondaryPrompts( + AttributedString strAtt, List prompts, boolean computePrompts) { Objects.requireNonNull(prompts); List lines = strAtt.columnSplitLength(Integer.MAX_VALUE); AttributedStringBuilder sb = new AttributedStringBuilder(); @@ -4171,7 +4254,9 @@ if (computePrompts && secondaryPromptPattern.contains("%P")) { width = prompt.columnLength(); if (width > size.getColumns() || prompt.contains('\n')) { - width = new TerminalLine(prompt.toString(), 0, size.getColumns()).getEndLine().length(); + width = new TerminalLine(prompt.toString(), 0, size.getColumns()) + .getEndLine() + .length(); } for (int line = 0; line < lines.size() - 1; line++) { AttributedString prompt; @@ -4227,11 +4312,9 @@ private AttributedString addRightPrompt(AttributedString prompt, AttributedString line) { int width = prompt.columnLength(); - boolean endsWithNl = line.length() > 0 - && line.charAt(line.length() - 1) == '\n'; + boolean endsWithNl = line.length() > 0 && line.charAt(line.length() - 1) == '\n'; // columnLength counts -1 for the final newline; adjust for that - int nb = size.getColumns() - width - - (line.columnLength() + (endsWithNl ? 1 : 0)); + int nb = size.getColumns() - width - (line.columnLength() + (endsWithNl ? 1 : 0)); if (nb >= 3) { AttributedStringBuilder sb = new AttributedStringBuilder(size.getColumns()); sb.append(line, 0, endsWithNl ? line.length() - 1 : line.length()); @@ -4253,8 +4336,8 @@ protected boolean insertTab() { return isSet(Option.INSERT_TAB) - && getLastBinding().equals("\t") - && buf.toString().matches("(^|[\\s\\S]*\n)[\r\n\t ]*"); + && getLastBinding().equals("\t") + && buf.toString().matches("(^|[\\s\\S]*\n)[\r\n\t ]*"); } protected boolean expandHistory() { @@ -4465,7 +4548,8 @@ if (op != null) { String chars = getString(REMOVE_SUFFIX_CHARS, DEFAULT_REMOVE_SUFFIX_CHARS); String ref = op instanceof Reference ? ((Reference) op).name() : null; - if (SELF_INSERT.equals(ref) && chars.indexOf(getLastBinding().charAt(0)) >= 0 + if (SELF_INSERT.equals(ref) + && chars.indexOf(getLastBinding().charAt(0)) >= 0 || ACCEPT_LINE.equals(ref)) { buf.backspace(completion.suffix().length()); if (getLastBinding().charAt(0) != ' ') { @@ -4533,27 +4617,35 @@ public String word() { return line.word(); } + public int wordCursor() { return line.wordCursor(); } + public int wordIndex() { return line.wordIndex(); } + public List words() { return line.words(); } + public String line() { return line.line(); } + public int cursor() { return line.cursor(); } + public CharSequence escape(CharSequence candidate, boolean complete) { return candidate; } + public int rawWordCursor() { return wordCursor(); } + public int rawWordLength() { return word().length(); } @@ -4564,8 +4656,7 @@ protected Comparator getCandidateComparator(boolean caseInsensitive, String word) { String wdi = caseInsensitive ? word.toLowerCase() : word; ToIntFunction wordDistance = w -> ReaderUtils.distance(wdi, caseInsensitive ? w.toLowerCase() : w); - return Comparator - .comparing(Candidate::value, Comparator.comparingInt(wordDistance)) + return Comparator.comparing(Candidate::value, Comparator.comparingInt(wordDistance)) .thenComparing(Comparator.naturalOrder()); } @@ -4577,9 +4668,10 @@ return getString(ORIGINAL_GROUP_NAME, DEFAULT_ORIGINAL_GROUP_NAME); } - protected Comparator getGroupComparator() { - return Comparator.comparingInt(s -> getOthersGroupName().equals(s) ? 1 : getOriginalGroupName().equals(s) ? -1 : 0) + return Comparator.comparingInt(s -> getOthersGroupName().equals(s) + ? 1 + : getOriginalGroupName().equals(s) ? -1 : 0) .thenComparing(String::toLowerCase, Comparator.naturalOrder()); } @@ -4600,11 +4692,9 @@ // the same description candidates.sort(Comparator.comparing(Candidate::value)); Candidate first = candidates.get(0); - String disp = candidates.stream() - .map(Candidate::displ) - .collect(Collectors.joining(" ")); - possible.add(new Candidate(first.value(), disp, first.group(), - first.descr(), first.suffix(), null, first.complete())); + String disp = candidates.stream().map(Candidate::displ).collect(Collectors.joining(" ")); + possible.add(new Candidate( + first.value(), disp, first.group(), first.descr(), first.suffix(), null, first.complete())); } } } @@ -4636,8 +4726,10 @@ } private int promptLines() { - AttributedString text = insertSecondaryPrompts(AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); - return text.columnSplitLength(size.getColumns(), false, display.delayLineWrap()).size(); + AttributedString text = + insertSecondaryPrompts(AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); + return text.columnSplitLength(size.getColumns(), false, display.delayLineWrap()) + .size(); } private class MenuSupport implements Supplier { @@ -4651,7 +4743,8 @@ int columns; String completed; - public MenuSupport(List original, String completed, BiFunction escaper) { + public MenuSupport( + List original, String completed, BiFunction escaper) { this.possible = new ArrayList<>(); this.escaper = escaper; this.selection = -1; @@ -4714,7 +4807,7 @@ if (selection - row + axis > options) { // selection is the last row/column // so there are fewer options than other rows - axis = options%axis; + axis = options % axis; } selection = selection - row + ((axis + row + step) % axis); update(); @@ -4772,7 +4865,9 @@ AttributedString post = pr.post; if (post.length() > 0 && post.charAt(post.length() - 1) != '\n') { post = new AttributedStringBuilder(post.length() + 1) - .append(post).append("\n").toAttributedString(); + .append(post) + .append("\n") + .toAttributedString(); } List lines = post.columnSplitLength(size.getColumns(), true, display.delayLineWrap()); List sub = new ArrayList<>(lines.subList(topLine, topLine + displayed)); @@ -4785,7 +4880,8 @@ .append(" of ") .append(Integer.toString(lines.size())) .append("\n") - .style(AttributedStyle.DEFAULT).toAttributedString()); + .style(AttributedStyle.DEFAULT) + .toAttributedString()); computed = AttributedString.join(AttributedString.EMPTY, sub); } else { computed = pr.post; @@ -4798,10 +4894,10 @@ public AttributedString get() { return computed; } - } - protected boolean doMenu(List original, String completed, BiFunction escaper) { + protected boolean doMenu( + List original, String completed, BiFunction escaper) { // Reorder candidates according to display order final List possible = new ArrayList<>(); boolean caseInsensitive = isSet(Option.CASE_INSENSITIVE); @@ -4854,7 +4950,7 @@ if (completion.suffix() != null) { String chars = getString(REMOVE_SUFFIX_CHARS, DEFAULT_REMOVE_SUFFIX_CHARS); if (SELF_INSERT.equals(ref) - && chars.indexOf(getLastBinding().charAt(0)) >= 0 + && chars.indexOf(getLastBinding().charAt(0)) >= 0 || BACKWARD_DELETE_CHAR.equals(ref)) { buf.backspace(completion.suffix().length()); } @@ -4866,8 +4962,8 @@ } if (!ACCEPT_LINE.equals(ref) && !(SELF_INSERT.equals(ref) - && completion.suffix() != null - && completion.suffix().startsWith(getLastBinding()))) { + && completion.suffix() != null + && completion.suffix().startsWith(getLastBinding()))) { pushBackBinding(true); } post = null; @@ -4888,29 +4984,40 @@ return doList(new ArrayList<>(), "", false, null, false); } - protected boolean doList(List possible - , String completed, boolean runLoop, BiFunction escaper) { + protected boolean doList( + List possible, + String completed, + boolean runLoop, + BiFunction escaper) { return doList(possible, completed, runLoop, escaper, false); } - protected boolean doList(List possible - , String completed - , boolean runLoop, BiFunction escaper, boolean forSuggestion) { + protected boolean doList( + List possible, + String completed, + boolean runLoop, + BiFunction escaper, + boolean forSuggestion) { // If we list only and if there's a big // number of items, we should ask the user // for confirmation, display the list // and redraw the line at the bottom mergeCandidates(possible); - AttributedString text = insertSecondaryPrompts(AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); - int promptLines = text.columnSplitLength(size.getColumns(), false, display.delayLineWrap()).size(); + AttributedString text = + insertSecondaryPrompts(AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); + int promptLines = text.columnSplitLength(size.getColumns(), false, display.delayLineWrap()) + .size(); PostResult postResult = computePost(possible, null, null, completed); int lines = postResult.lines; int listMax = getInt(LIST_MAX, DEFAULT_LIST_MAX); - if (listMax > 0 && possible.size() >= listMax - || lines >= size.getRows() - promptLines) { + int possibleSize = possible.size(); + if (possibleSize == 0 || size.getRows() == 0) { + return false; + } + if (listMax > 0 && possibleSize >= listMax || lines >= size.getRows() - promptLines) { if (!forSuggestion) { // prompt - post = () -> new AttributedString(getAppName() + ": do you wish to see all " + possible.size() + post = () -> new AttributedString(getAppName() + ": do you wish to see all " + possibleSize + " possibilities (" + lines + " lines)?"); redisplay(true); int c = readCharacter(); @@ -4930,8 +5037,7 @@ String current = completed + sb.toString(); List cands; if (sb.length() > 0) { - completionMatcher.compile(options, false, new CompletingWord(current), caseInsensitive, 0 - , null); + completionMatcher.compile(options, false, new CompletingWord(current), caseInsensitive, 0, null); cands = completionMatcher.matches(possible).stream() .sorted(getCandidateComparator(caseInsensitive, current)) .collect(Collectors.toList()); @@ -4944,8 +5050,10 @@ candidateStartPosition = candidateStartPosition(cands); } post = () -> { - AttributedString t = insertSecondaryPrompts(AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); - int pl = t.columnSplitLength(size.getColumns(), false, display.delayLineWrap()).size(); + AttributedString t = insertSecondaryPrompts( + AttributedStringBuilder.append(prompt, buf.toString()), new ArrayList<>()); + int pl = t.columnSplitLength(size.getColumns(), false, display.delayLineWrap()) + .size(); PostResult pr = computePost(cands, null, null, current); if (pr.lines >= size.getRows() - pl) { post = null; @@ -4954,7 +5062,8 @@ redisplay(false); buf.cursor(oldCursor); println(); - List ls = pr.post.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); + List ls = + pr.post.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); Display d = new Display(terminal, false); d.resize(size.getRows(), size.getColumns()); d.update(ls, -1); @@ -5074,25 +5183,41 @@ } } - protected PostResult computePost(List possible, Candidate selection, List ordered, String completed) { - return computePost(possible, selection, ordered, completed, display::wcwidth, size.getColumns(), isSet(Option.AUTO_GROUP), isSet(Option.GROUP), isSet(Option.LIST_ROWS_FIRST)); - } - - protected PostResult computePost(List possible, Candidate selection, List ordered, String completed, Function wcwidth, int width, boolean autoGroup, boolean groupName, boolean rowsFirst) { + protected PostResult computePost( + List possible, Candidate selection, List ordered, String completed) { + return computePost( + possible, + selection, + ordered, + completed, + display::wcwidth, + size.getColumns(), + isSet(Option.AUTO_GROUP), + isSet(Option.GROUP), + isSet(Option.LIST_ROWS_FIRST)); + } + + protected PostResult computePost( + List possible, + Candidate selection, + List ordered, + String completed, + Function wcwidth, + int width, + boolean autoGroup, + boolean groupName, + boolean rowsFirst) { List strings = new ArrayList<>(); - boolean customOrder = possible.stream().anyMatch(c -> c.sort() != 0); if (groupName) { Comparator groupComparator = getGroupComparator(); - Map> sorted; - sorted = groupComparator != null - ? new TreeMap<>(groupComparator) - : new LinkedHashMap<>(); + Map> sorted; + sorted = groupComparator != null ? new TreeMap<>(groupComparator) : new LinkedHashMap<>(); for (Candidate cand : possible) { String group = cand.group(); - sorted.computeIfAbsent(group != null ? group : "", s -> new LinkedHashMap<>()) - .put((customOrder ? cand.sort() : cand.value()), cand); + sorted.computeIfAbsent(group != null ? group : "", s -> new ArrayList<>()) + .add(cand); } - for (Map.Entry> entry : sorted.entrySet()) { + for (Map.Entry> entry : sorted.entrySet()) { String group = entry.getKey(); if (group.isEmpty() && sorted.size() > 1) { group = getOthersGroupName(); @@ -5100,27 +5225,30 @@ if (!group.isEmpty() && autoGroup) { strings.add(group); } - strings.add(new ArrayList<>(entry.getValue().values())); + List candidates = entry.getValue(); + Collections.sort(candidates); + strings.add(candidates); if (ordered != null) { - ordered.addAll(entry.getValue().values()); + ordered.addAll(candidates); } } } else { Set groups = new LinkedHashSet<>(); - TreeMap sorted = new TreeMap<>(); + List sorted = new ArrayList<>(); for (Candidate cand : possible) { String group = cand.group(); if (group != null) { groups.add(group); } - sorted.put((customOrder ? cand.sort() : cand.value()), cand); + sorted.add(cand); } if (autoGroup) { strings.addAll(groups); } - strings.add(new ArrayList<>(sorted.values())); + Collections.sort(sorted); + strings.add(sorted); if (ordered != null) { - ordered.addAll(sorted.values()); + ordered.addAll(sorted); } } return toColumns(strings, selection, completed, wcwidth, width, rowsFirst); @@ -5163,12 +5291,15 @@ } private int candidateStartPosition(List cands) { - List values = cands.stream().map(c -> AttributedString.stripAnsi(c.displ())) - .filter(c -> !c.matches("\\w+") && c.length() > 1).collect(Collectors.toList()); + List values = cands.stream() + .map(c -> AttributedString.stripAnsi(c.displ())) + .filter(c -> !c.matches("\\w+") && c.length() > 1) + .collect(Collectors.toList()); Set notDelimiters = new HashSet<>(); - values.forEach(v -> v.substring(0, v.length() - 1).chars() + values.forEach(v -> v.substring(0, v.length() - 1) + .chars() .filter(c -> !Character.isDigit(c) && !Character.isAlphabetic(c)) - .forEach(c -> notDelimiters.add(Character.toString((char)c)))); + .forEach(c -> notDelimiters.add(Character.toString((char) c)))); int width = size.getColumns(); int promptLength = prompt != null ? prompt.length() : 0; if (promptLength > 0) { @@ -5179,8 +5310,7 @@ int out = tl.getStartPos(); String buffer = tl.getEndLine(); for (int i = buffer.length(); i > 0; i--) { - if (buffer.substring(0, i).matches(".*\\W") - && !notDelimiters.contains(buffer.substring(i - 1, i))) { + if (buffer.substring(0, i).matches(".*\\W") && !notDelimiters.contains(buffer.substring(i - 1, i))) { out += i; break; } @@ -5189,7 +5319,13 @@ } @SuppressWarnings("unchecked") - protected PostResult toColumns(List items, Candidate selection, String completed, Function wcwidth, int width, boolean rowsFirst) { + protected PostResult toColumns( + List items, + Candidate selection, + String completed, + Function wcwidth, + int width, + boolean rowsFirst) { int[] out = new int[2]; // TODO: support Option.LIST_PACKED // Compute column width @@ -5199,8 +5335,7 @@ if (item instanceof String) { int len = wcwidth.apply((String) item); maxWidth = Math.max(maxWidth, len); - } - else if (item instanceof List) { + } else if (item instanceof List) { for (Candidate cand : (List) item) { listSize++; int len = wcwidth.apply(cand.displ()); @@ -5218,7 +5353,10 @@ AttributedStringBuilder sb = new AttributedStringBuilder(); if (listSize > 0) { if (isSet(Option.AUTO_MENU_LIST) - && listSize < Math.min(getInt(MENU_LIST_MAX, DEFAULT_MENU_LIST_MAX), visibleDisplayRows() - promptLines())) { + && listSize + < Math.min( + getInt(MENU_LIST_MAX, DEFAULT_MENU_LIST_MAX), + visibleDisplayRows() - promptLines())) { maxWidth = Math.max(maxWidth, MENU_LIST_WIDTH); sb.tabs(Math.max(Math.min(candidateStartPosition, width - maxWidth - 1), 1)); width = maxWidth + 2; @@ -5251,8 +5389,16 @@ } @SuppressWarnings("unchecked") - protected void toColumns(Object items, int width, int maxWidth, AttributedStringBuilder sb, Candidate selection, String completed - , boolean rowsFirst, boolean doMenuList, int[] out) { + protected void toColumns( + Object items, + int width, + int maxWidth, + AttributedStringBuilder sb, + Candidate selection, + String completed, + boolean rowsFirst, + boolean doMenuList, + int[] out) { if (maxWidth <= 0 || width <= 0) { return; } @@ -5305,18 +5451,20 @@ if (idx < candidates.size()) { Candidate cand = candidates.get(idx); boolean hasRightItem = j < columns - 1 && index.applyAsInt(i, j + 1) < candidates.size(); - AttributedString left = AttributedString.fromAnsi(cand.displ()); - AttributedString right = AttributedString.fromAnsi(cand.descr()); + AttributedString left = fromAnsi(cand.displ()); + AttributedString right = fromAnsi(cand.descr()); int lw = left.columnLength(); int rw = 0; if (right != null) { - int rem = maxWidth - (lw + MARGIN_BETWEEN_DISPLAY_AND_DESC - + DESC_PREFIX.length() + DESC_SUFFIX.length()); + int rem = maxWidth + - (lw + + MARGIN_BETWEEN_DISPLAY_AND_DESC + + DESC_PREFIX.length() + + DESC_SUFFIX.length()); rw = right.columnLength(); if (rw > rem) { right = AttributedStringBuilder.append( - right.columnSubSequence(0, rem - WCWidth.wcwidth('\u2026')), - "\u2026"); + right.columnSubSequence(0, rem - WCWidth.wcwidth('\u2026')), "\u2026"); rw = right.columnLength(); } right = AttributedStringBuilder.append(DESC_PREFIX, right, DESC_SUFFIX); @@ -5325,8 +5473,9 @@ if (cand == selection) { out[1] = i; asb.style(getCompletionStyleSelection(doMenuList)); - if (left.toString().regionMatches( - isSet(Option.CASE_INSENSITIVE), 0, completed, 0, completed.length())) { + if (left.toString() + .regionMatches( + isSet(Option.CASE_INSENSITIVE), 0, completed, 0, completed.length())) { asb.append(left.toString(), 0, completed.length()); asb.append(left.toString(), completed.length(), left.length()); } else { @@ -5340,8 +5489,9 @@ } asb.style(AttributedStyle.DEFAULT); } else { - if (left.toString().regionMatches( - isSet(Option.CASE_INSENSITIVE), 0, completed, 0, completed.length())) { + if (left.toString() + .regionMatches( + isSet(Option.CASE_INSENSITIVE), 0, completed, 0, completed.length())) { asb.style(getCompletionStyleStarting(doMenuList)); asb.append(left, 0, completed.length()); asb.style(AttributedStyle.DEFAULT); @@ -5447,7 +5597,7 @@ } protected AttributedStyle buildStyle(String str) { - return AttributedString.fromAnsi("\u001b[" + str + "m ").styleAt(0); + return fromAnsi("\u001b[" + str + "m ").styleAt(0); } /** @@ -5477,14 +5627,14 @@ } if (next && !history.next()) { return false; - } - else if (!next && !history.previous()) { + } else if (!next && !history.previous()) { return false; } - setBuffer(modifiedHistory.containsKey(history.index()) - ? modifiedHistory.get(history.index()) - : history.current()); + setBuffer( + modifiedHistory.containsKey(history.index()) + ? modifiedHistory.get(history.index()) + : history.current()); return true; } @@ -5515,7 +5665,6 @@ redrawLine(); } - // // Actions // @@ -5725,8 +5874,7 @@ public boolean mouse() { MouseEvent event = readMouseEvent(); - if (event.getType() == MouseEvent.Type.Released - && event.getButton() == MouseEvent.Button.Button1) { + if (event.getType() == MouseEvent.Type.Released && event.getButton() == MouseEvent.Button.Button1) { StringBuilder tsb = new StringBuilder(); Cursor cursor = terminal.getCursorPosition(c -> tsb.append((char) c)); bindingReader.runMacro(tsb.toString()); @@ -5734,15 +5882,20 @@ List secondaryPrompts = new ArrayList<>(); getDisplayedBufferWithPrompts(secondaryPrompts); - AttributedStringBuilder sb = new AttributedStringBuilder().tabs(TAB_WIDTH); + AttributedStringBuilder sb = new AttributedStringBuilder().tabs(getTabWidth()); sb.append(prompt); sb.append(insertSecondaryPrompts(new AttributedString(buf.upToCursor()), secondaryPrompts, false)); - List promptLines = sb.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); + List promptLines = + sb.columnSplitLength(size.getColumns(), false, display.delayLineWrap()); int currentLine = promptLines.size() - 1; int wantedLine = Math.max(0, Math.min(currentLine + event.getY() - cursor.getY(), secondaryPrompts.size())); - int pl0 = currentLine == 0 ? prompt.columnLength() : secondaryPrompts.get(currentLine - 1).columnLength(); - int pl1 = wantedLine == 0 ? prompt.columnLength() : secondaryPrompts.get(wantedLine - 1).columnLength(); + int pl0 = currentLine == 0 + ? prompt.columnLength() + : secondaryPrompts.get(currentLine - 1).columnLength(); + int pl1 = wantedLine == 0 + ? prompt.columnLength() + : secondaryPrompts.get(wantedLine - 1).columnLength(); int adjust = pl1 - pl0; buf.moveXY(event.getX() - cursor.getX() - adjust, event.getY() - cursor.getY()); } @@ -5814,13 +5967,11 @@ bell_preference = BellType.VISIBLE; break; case "on": - bell_preference = getBoolean(PREFER_VISIBLE_BELL, false) - ? BellType.VISIBLE : BellType.AUDIBLE; + bell_preference = getBoolean(PREFER_VISIBLE_BELL, false) ? BellType.VISIBLE : BellType.AUDIBLE; break; } if (bell_preference == BellType.VISIBLE) { - if (terminal.puts(Capability.flash_screen) - || terminal.puts(Capability.bell)) { + if (terminal.puts(Capability.flash_screen) || terminal.puts(Capability.bell)) { flush(); } } else if (bell_preference == BellType.AUDIBLE) { @@ -5869,8 +6020,7 @@ protected boolean isWord(int c) { String wordchars = getString(WORDCHARS, DEFAULT_WORDCHARS); - return Character.isLetterOrDigit(c) - || (c < 128 && wordchars.indexOf((char) c) >= 0); + return Character.isLetterOrDigit(c) || (c < 128 && wordchars.indexOf((char) c) >= 0); } String getString(String name, String def) { @@ -5899,6 +6049,8 @@ keyMaps.put(VIOPP, viOpp()); keyMaps.put(VISUAL, visual()); keyMaps.put(SAFE, safe()); + keyMaps.put(DUMB, dumb()); + if (getBoolean(BIND_TTY_SPECIAL_CHARS, true)) { Attributes attr = terminal.getAttributes(); bindConsoleChars(keyMaps.get(EMACS), attr); @@ -5909,240 +6061,241 @@ keyMap.setUnicode(new Reference(SELF_INSERT)); keyMap.setAmbiguousTimeout(getLong(AMBIGUOUS_BINDING, DEFAULT_AMBIGUOUS_BINDING)); } - // By default, link main to emacs - keyMaps.put(MAIN, keyMaps.get(EMACS)); + // By default, link main to emacs unless the temrinal is dumb + keyMaps.put(MAIN, keyMaps.get(isTerminalDumb() ? DUMB : EMACS)); + return keyMaps; } public KeyMap emacs() { KeyMap emacs = new KeyMap<>(); bindKeys(emacs); - bind(emacs, SET_MARK_COMMAND, ctrl('@')); - bind(emacs, BEGINNING_OF_LINE, ctrl('A')); - bind(emacs, BACKWARD_CHAR, ctrl('B')); - bind(emacs, DELETE_CHAR_OR_LIST, ctrl('D')); - bind(emacs, END_OF_LINE, ctrl('E')); - bind(emacs, FORWARD_CHAR, ctrl('F')); - bind(emacs, SEND_BREAK, ctrl('G')); - bind(emacs, BACKWARD_DELETE_CHAR, ctrl('H')); - bind(emacs, EXPAND_OR_COMPLETE, ctrl('I')); - bind(emacs, ACCEPT_LINE, ctrl('J')); - bind(emacs, KILL_LINE, ctrl('K')); - bind(emacs, CLEAR_SCREEN, ctrl('L')); - bind(emacs, ACCEPT_LINE, ctrl('M')); - bind(emacs, DOWN_LINE_OR_HISTORY, ctrl('N')); - bind(emacs, ACCEPT_LINE_AND_DOWN_HISTORY, ctrl('O')); - bind(emacs, UP_LINE_OR_HISTORY, ctrl('P')); - bind(emacs, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); - bind(emacs, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); - bind(emacs, TRANSPOSE_CHARS, ctrl('T')); - bind(emacs, KILL_WHOLE_LINE, ctrl('U')); - bind(emacs, QUOTED_INSERT, ctrl('V')); - bind(emacs, BACKWARD_KILL_WORD, ctrl('W')); - bind(emacs, YANK, ctrl('Y')); - bind(emacs, CHARACTER_SEARCH, ctrl(']')); - bind(emacs, UNDO, ctrl('_')); - bind(emacs, SELF_INSERT, range(" -~")); - bind(emacs, INSERT_CLOSE_PAREN, ")"); - bind(emacs, INSERT_CLOSE_SQUARE, "]"); - bind(emacs, INSERT_CLOSE_CURLY, "}"); - bind(emacs, BACKWARD_DELETE_CHAR, del()); - bind(emacs, VI_MATCH_BRACKET, translate("^X^B")); - bind(emacs, SEND_BREAK, translate("^X^G")); - bind(emacs, EDIT_AND_EXECUTE_COMMAND, translate("^X^E")); - bind(emacs, VI_FIND_NEXT_CHAR, translate("^X^F")); - bind(emacs, VI_JOIN, translate("^X^J")); - bind(emacs, KILL_BUFFER, translate("^X^K")); - bind(emacs, INFER_NEXT_HISTORY, translate("^X^N")); - bind(emacs, OVERWRITE_MODE, translate("^X^O")); - bind(emacs, REDO, translate("^X^R")); - bind(emacs, UNDO, translate("^X^U")); - bind(emacs, VI_CMD_MODE, translate("^X^V")); - bind(emacs, EXCHANGE_POINT_AND_MARK, translate("^X^X")); - bind(emacs, DO_LOWERCASE_VERSION, translate("^XA-^XZ")); - bind(emacs, WHAT_CURSOR_POSITION, translate("^X=")); - bind(emacs, KILL_LINE, translate("^X^?")); - bind(emacs, SEND_BREAK, alt(ctrl('G'))); - bind(emacs, BACKWARD_KILL_WORD, alt(ctrl('H'))); - bind(emacs, SELF_INSERT_UNMETA, alt(ctrl('M'))); - bind(emacs, COMPLETE_WORD, alt(esc())); - bind(emacs, CHARACTER_SEARCH_BACKWARD, alt(ctrl(']'))); - bind(emacs, COPY_PREV_WORD, alt(ctrl('_'))); - bind(emacs, SET_MARK_COMMAND, alt(' ')); - bind(emacs, NEG_ARGUMENT, alt('-')); - bind(emacs, DIGIT_ARGUMENT, range("\\E0-\\E9")); - bind(emacs, BEGINNING_OF_HISTORY, alt('<')); - bind(emacs, LIST_CHOICES, alt('=')); - bind(emacs, END_OF_HISTORY, alt('>')); - bind(emacs, LIST_CHOICES, alt('?')); - bind(emacs, DO_LOWERCASE_VERSION, range("^[A-^[Z")); - bind(emacs, ACCEPT_AND_HOLD, alt('a')); - bind(emacs, BACKWARD_WORD, alt('b')); - bind(emacs, CAPITALIZE_WORD, alt('c')); - bind(emacs, KILL_WORD, alt('d')); - bind(emacs, KILL_WORD, translate("^[[3;5~")); // ctrl-delete - bind(emacs, FORWARD_WORD, alt('f')); - bind(emacs, DOWN_CASE_WORD, alt('l')); - bind(emacs, HISTORY_SEARCH_FORWARD, alt('n')); - bind(emacs, HISTORY_SEARCH_BACKWARD, alt('p')); - bind(emacs, TRANSPOSE_WORDS, alt('t')); - bind(emacs, UP_CASE_WORD, alt('u')); - bind(emacs, YANK_POP, alt('y')); - bind(emacs, BACKWARD_KILL_WORD, alt(del())); + bind(emacs, SET_MARK_COMMAND, ctrl('@')); + bind(emacs, BEGINNING_OF_LINE, ctrl('A')); + bind(emacs, BACKWARD_CHAR, ctrl('B')); + bind(emacs, DELETE_CHAR_OR_LIST, ctrl('D')); + bind(emacs, END_OF_LINE, ctrl('E')); + bind(emacs, FORWARD_CHAR, ctrl('F')); + bind(emacs, SEND_BREAK, ctrl('G')); + bind(emacs, BACKWARD_DELETE_CHAR, ctrl('H')); + bind(emacs, EXPAND_OR_COMPLETE, ctrl('I')); + bind(emacs, ACCEPT_LINE, ctrl('J')); + bind(emacs, KILL_LINE, ctrl('K')); + bind(emacs, CLEAR_SCREEN, ctrl('L')); + bind(emacs, ACCEPT_LINE, ctrl('M')); + bind(emacs, DOWN_LINE_OR_HISTORY, ctrl('N')); + bind(emacs, ACCEPT_LINE_AND_DOWN_HISTORY, ctrl('O')); + bind(emacs, UP_LINE_OR_HISTORY, ctrl('P')); + bind(emacs, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); + bind(emacs, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); + bind(emacs, TRANSPOSE_CHARS, ctrl('T')); + bind(emacs, KILL_WHOLE_LINE, ctrl('U')); + bind(emacs, QUOTED_INSERT, ctrl('V')); + bind(emacs, BACKWARD_KILL_WORD, ctrl('W')); + bind(emacs, YANK, ctrl('Y')); + bind(emacs, CHARACTER_SEARCH, ctrl(']')); + bind(emacs, UNDO, ctrl('_')); + bind(emacs, SELF_INSERT, range(" -~")); + bind(emacs, INSERT_CLOSE_PAREN, ")"); + bind(emacs, INSERT_CLOSE_SQUARE, "]"); + bind(emacs, INSERT_CLOSE_CURLY, "}"); + bind(emacs, BACKWARD_DELETE_CHAR, del()); + bind(emacs, VI_MATCH_BRACKET, translate("^X^B")); + bind(emacs, SEND_BREAK, translate("^X^G")); + bind(emacs, EDIT_AND_EXECUTE_COMMAND, translate("^X^E")); + bind(emacs, VI_FIND_NEXT_CHAR, translate("^X^F")); + bind(emacs, VI_JOIN, translate("^X^J")); + bind(emacs, KILL_BUFFER, translate("^X^K")); + bind(emacs, INFER_NEXT_HISTORY, translate("^X^N")); + bind(emacs, OVERWRITE_MODE, translate("^X^O")); + bind(emacs, REDO, translate("^X^R")); + bind(emacs, UNDO, translate("^X^U")); + bind(emacs, VI_CMD_MODE, translate("^X^V")); + bind(emacs, EXCHANGE_POINT_AND_MARK, translate("^X^X")); + bind(emacs, DO_LOWERCASE_VERSION, translate("^XA-^XZ")); + bind(emacs, WHAT_CURSOR_POSITION, translate("^X=")); + bind(emacs, KILL_LINE, translate("^X^?")); + bind(emacs, SEND_BREAK, alt(ctrl('G'))); + bind(emacs, BACKWARD_KILL_WORD, alt(ctrl('H'))); + bind(emacs, SELF_INSERT_UNMETA, alt(ctrl('M'))); + bind(emacs, COMPLETE_WORD, alt(esc())); + bind(emacs, CHARACTER_SEARCH_BACKWARD, alt(ctrl(']'))); + bind(emacs, COPY_PREV_WORD, alt(ctrl('_'))); + bind(emacs, SET_MARK_COMMAND, alt(' ')); + bind(emacs, NEG_ARGUMENT, alt('-')); + bind(emacs, DIGIT_ARGUMENT, range("\\E0-\\E9")); + bind(emacs, BEGINNING_OF_HISTORY, alt('<')); + bind(emacs, LIST_CHOICES, alt('=')); + bind(emacs, END_OF_HISTORY, alt('>')); + bind(emacs, LIST_CHOICES, alt('?')); + bind(emacs, DO_LOWERCASE_VERSION, range("^[A-^[Z")); + bind(emacs, ACCEPT_AND_HOLD, alt('a')); + bind(emacs, BACKWARD_WORD, alt('b')); + bind(emacs, CAPITALIZE_WORD, alt('c')); + bind(emacs, KILL_WORD, alt('d')); + bind(emacs, KILL_WORD, translate("^[[3;5~")); // ctrl-delete + bind(emacs, FORWARD_WORD, alt('f')); + bind(emacs, DOWN_CASE_WORD, alt('l')); + bind(emacs, HISTORY_SEARCH_FORWARD, alt('n')); + bind(emacs, HISTORY_SEARCH_BACKWARD, alt('p')); + bind(emacs, TRANSPOSE_WORDS, alt('t')); + bind(emacs, UP_CASE_WORD, alt('u')); + bind(emacs, YANK_POP, alt('y')); + bind(emacs, BACKWARD_KILL_WORD, alt(del())); bindArrowKeys(emacs); - bind(emacs, FORWARD_WORD, translate("^[[1;5C")); // ctrl-left - bind(emacs, BACKWARD_WORD, translate("^[[1;5D")); // ctrl-right - bind(emacs, FORWARD_WORD, alt(key(Capability.key_right))); - bind(emacs, BACKWARD_WORD, alt(key(Capability.key_left))); - bind(emacs, FORWARD_WORD, alt(translate("^[[C"))); - bind(emacs, BACKWARD_WORD, alt(translate("^[[D"))); + bind(emacs, FORWARD_WORD, translate("^[[1;5C")); // ctrl-left + bind(emacs, BACKWARD_WORD, translate("^[[1;5D")); // ctrl-right + bind(emacs, FORWARD_WORD, alt(key(Capability.key_right))); + bind(emacs, BACKWARD_WORD, alt(key(Capability.key_left))); + bind(emacs, FORWARD_WORD, alt(translate("^[[C"))); + bind(emacs, BACKWARD_WORD, alt(translate("^[[D"))); return emacs; } public KeyMap viInsertion() { KeyMap viins = new KeyMap<>(); bindKeys(viins); - bind(viins, SELF_INSERT, range("^@-^_")); - bind(viins, LIST_CHOICES, ctrl('D')); - bind(viins, SEND_BREAK, ctrl('G')); - bind(viins, BACKWARD_DELETE_CHAR, ctrl('H')); - bind(viins, EXPAND_OR_COMPLETE, ctrl('I')); - bind(viins, ACCEPT_LINE, ctrl('J')); - bind(viins, CLEAR_SCREEN, ctrl('L')); - bind(viins, ACCEPT_LINE, ctrl('M')); - bind(viins, MENU_COMPLETE, ctrl('N')); - bind(viins, REVERSE_MENU_COMPLETE, ctrl('P')); - bind(viins, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); - bind(viins, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); - bind(viins, TRANSPOSE_CHARS, ctrl('T')); - bind(viins, KILL_WHOLE_LINE, ctrl('U')); - bind(viins, QUOTED_INSERT, ctrl('V')); - bind(viins, BACKWARD_KILL_WORD, ctrl('W')); - bind(viins, YANK, ctrl('Y')); - bind(viins, VI_CMD_MODE, ctrl('[')); - bind(viins, UNDO, ctrl('_')); - bind(viins, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('X') + "r"); - bind(viins, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('X') + "s"); - bind(viins, SELF_INSERT, range(" -~")); - bind(viins, INSERT_CLOSE_PAREN, ")"); - bind(viins, INSERT_CLOSE_SQUARE, "]"); - bind(viins, INSERT_CLOSE_CURLY, "}"); - bind(viins, BACKWARD_DELETE_CHAR, del()); + bind(viins, SELF_INSERT, range("^@-^_")); + bind(viins, LIST_CHOICES, ctrl('D')); + bind(viins, SEND_BREAK, ctrl('G')); + bind(viins, BACKWARD_DELETE_CHAR, ctrl('H')); + bind(viins, EXPAND_OR_COMPLETE, ctrl('I')); + bind(viins, ACCEPT_LINE, ctrl('J')); + bind(viins, CLEAR_SCREEN, ctrl('L')); + bind(viins, ACCEPT_LINE, ctrl('M')); + bind(viins, MENU_COMPLETE, ctrl('N')); + bind(viins, REVERSE_MENU_COMPLETE, ctrl('P')); + bind(viins, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); + bind(viins, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); + bind(viins, TRANSPOSE_CHARS, ctrl('T')); + bind(viins, KILL_WHOLE_LINE, ctrl('U')); + bind(viins, QUOTED_INSERT, ctrl('V')); + bind(viins, BACKWARD_KILL_WORD, ctrl('W')); + bind(viins, YANK, ctrl('Y')); + bind(viins, VI_CMD_MODE, ctrl('[')); + bind(viins, UNDO, ctrl('_')); + bind(viins, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('X') + "r"); + bind(viins, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('X') + "s"); + bind(viins, SELF_INSERT, range(" -~")); + bind(viins, INSERT_CLOSE_PAREN, ")"); + bind(viins, INSERT_CLOSE_SQUARE, "]"); + bind(viins, INSERT_CLOSE_CURLY, "}"); + bind(viins, BACKWARD_DELETE_CHAR, del()); bindArrowKeys(viins); return viins; } public KeyMap viCmd() { KeyMap vicmd = new KeyMap<>(); - bind(vicmd, LIST_CHOICES, ctrl('D')); - bind(vicmd, EMACS_EDITING_MODE, ctrl('E')); - bind(vicmd, SEND_BREAK, ctrl('G')); - bind(vicmd, VI_BACKWARD_CHAR, ctrl('H')); - bind(vicmd, ACCEPT_LINE, ctrl('J')); - bind(vicmd, KILL_LINE, ctrl('K')); - bind(vicmd, CLEAR_SCREEN, ctrl('L')); - bind(vicmd, ACCEPT_LINE, ctrl('M')); - bind(vicmd, VI_DOWN_LINE_OR_HISTORY, ctrl('N')); - bind(vicmd, VI_UP_LINE_OR_HISTORY, ctrl('P')); - bind(vicmd, QUOTED_INSERT, ctrl('Q')); - bind(vicmd, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); - bind(vicmd, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); - bind(vicmd, TRANSPOSE_CHARS, ctrl('T')); - bind(vicmd, KILL_WHOLE_LINE, ctrl('U')); - bind(vicmd, QUOTED_INSERT, ctrl('V')); - bind(vicmd, BACKWARD_KILL_WORD, ctrl('W')); - bind(vicmd, YANK, ctrl('Y')); - bind(vicmd, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('X') + "r"); - bind(vicmd, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('X') + "s"); - bind(vicmd, SEND_BREAK, alt(ctrl('G'))); - bind(vicmd, BACKWARD_KILL_WORD, alt(ctrl('H'))); - bind(vicmd, SELF_INSERT_UNMETA, alt(ctrl('M'))); - bind(vicmd, COMPLETE_WORD, alt(esc())); - bind(vicmd, CHARACTER_SEARCH_BACKWARD, alt(ctrl(']'))); - bind(vicmd, SET_MARK_COMMAND, alt(' ')); -// bind(vicmd, INSERT_COMMENT, alt('#')); -// bind(vicmd, INSERT_COMPLETIONS, alt('*')); - bind(vicmd, DIGIT_ARGUMENT, alt('-')); - bind(vicmd, BEGINNING_OF_HISTORY, alt('<')); - bind(vicmd, LIST_CHOICES, alt('=')); - bind(vicmd, END_OF_HISTORY, alt('>')); - bind(vicmd, LIST_CHOICES, alt('?')); - bind(vicmd, DO_LOWERCASE_VERSION, range("^[A-^[Z")); - bind(vicmd, BACKWARD_WORD, alt('b')); - bind(vicmd, CAPITALIZE_WORD, alt('c')); - bind(vicmd, KILL_WORD, alt('d')); - bind(vicmd, FORWARD_WORD, alt('f')); - bind(vicmd, DOWN_CASE_WORD, alt('l')); - bind(vicmd, HISTORY_SEARCH_FORWARD, alt('n')); - bind(vicmd, HISTORY_SEARCH_BACKWARD, alt('p')); - bind(vicmd, TRANSPOSE_WORDS, alt('t')); - bind(vicmd, UP_CASE_WORD, alt('u')); - bind(vicmd, YANK_POP, alt('y')); - bind(vicmd, BACKWARD_KILL_WORD, alt(del())); - - bind(vicmd, FORWARD_CHAR, " "); - bind(vicmd, VI_INSERT_COMMENT, "#"); - bind(vicmd, END_OF_LINE, "$"); - bind(vicmd, VI_MATCH_BRACKET, "%"); - bind(vicmd, VI_DOWN_LINE_OR_HISTORY, "+"); - bind(vicmd, VI_REV_REPEAT_FIND, ","); - bind(vicmd, VI_UP_LINE_OR_HISTORY, "-"); - bind(vicmd, VI_REPEAT_CHANGE, "."); - bind(vicmd, VI_HISTORY_SEARCH_BACKWARD, "/"); - bind(vicmd, VI_DIGIT_OR_BEGINNING_OF_LINE, "0"); - bind(vicmd, DIGIT_ARGUMENT, range("1-9")); - bind(vicmd, VI_REPEAT_FIND, ";"); - bind(vicmd, LIST_CHOICES, "="); - bind(vicmd, VI_HISTORY_SEARCH_FORWARD, "?"); - bind(vicmd, VI_ADD_EOL, "A"); - bind(vicmd, VI_BACKWARD_BLANK_WORD, "B"); - bind(vicmd, VI_CHANGE_EOL, "C"); - bind(vicmd, VI_KILL_EOL, "D"); - bind(vicmd, VI_FORWARD_BLANK_WORD_END, "E"); - bind(vicmd, VI_FIND_PREV_CHAR, "F"); - bind(vicmd, VI_FETCH_HISTORY, "G"); - bind(vicmd, VI_INSERT_BOL, "I"); - bind(vicmd, VI_JOIN, "J"); - bind(vicmd, VI_REV_REPEAT_SEARCH, "N"); - bind(vicmd, VI_OPEN_LINE_ABOVE, "O"); - bind(vicmd, VI_PUT_BEFORE, "P"); - bind(vicmd, VI_REPLACE, "R"); - bind(vicmd, VI_KILL_LINE, "S"); - bind(vicmd, VI_FIND_PREV_CHAR_SKIP, "T"); - bind(vicmd, REDO, "U"); - bind(vicmd, VISUAL_LINE_MODE, "V"); - bind(vicmd, VI_FORWARD_BLANK_WORD, "W"); - bind(vicmd, VI_BACKWARD_DELETE_CHAR, "X"); - bind(vicmd, VI_YANK_WHOLE_LINE, "Y"); - bind(vicmd, VI_FIRST_NON_BLANK, "^"); - bind(vicmd, VI_ADD_NEXT, "a"); - bind(vicmd, VI_BACKWARD_WORD, "b"); - bind(vicmd, VI_CHANGE, "c"); - bind(vicmd, VI_DELETE, "d"); - bind(vicmd, VI_FORWARD_WORD_END, "e"); - bind(vicmd, VI_FIND_NEXT_CHAR, "f"); - bind(vicmd, WHAT_CURSOR_POSITION, "ga"); - bind(vicmd, VI_BACKWARD_BLANK_WORD_END, "gE"); - bind(vicmd, VI_BACKWARD_WORD_END, "ge"); - bind(vicmd, VI_BACKWARD_CHAR, "h"); - bind(vicmd, VI_INSERT, "i"); - bind(vicmd, DOWN_LINE_OR_HISTORY, "j"); - bind(vicmd, UP_LINE_OR_HISTORY, "k"); - bind(vicmd, VI_FORWARD_CHAR, "l"); - bind(vicmd, VI_REPEAT_SEARCH, "n"); - bind(vicmd, VI_OPEN_LINE_BELOW, "o"); - bind(vicmd, VI_PUT_AFTER, "p"); - bind(vicmd, VI_REPLACE_CHARS, "r"); - bind(vicmd, VI_SUBSTITUTE, "s"); - bind(vicmd, VI_FIND_NEXT_CHAR_SKIP, "t"); - bind(vicmd, UNDO, "u"); - bind(vicmd, VISUAL_MODE, "v"); - bind(vicmd, VI_FORWARD_WORD, "w"); - bind(vicmd, VI_DELETE_CHAR, "x"); - bind(vicmd, VI_YANK, "y"); - bind(vicmd, VI_GOTO_COLUMN, "|"); - bind(vicmd, VI_SWAP_CASE, "~"); - bind(vicmd, VI_BACKWARD_CHAR, del()); + bind(vicmd, LIST_CHOICES, ctrl('D')); + bind(vicmd, EMACS_EDITING_MODE, ctrl('E')); + bind(vicmd, SEND_BREAK, ctrl('G')); + bind(vicmd, VI_BACKWARD_CHAR, ctrl('H')); + bind(vicmd, ACCEPT_LINE, ctrl('J')); + bind(vicmd, KILL_LINE, ctrl('K')); + bind(vicmd, CLEAR_SCREEN, ctrl('L')); + bind(vicmd, ACCEPT_LINE, ctrl('M')); + bind(vicmd, VI_DOWN_LINE_OR_HISTORY, ctrl('N')); + bind(vicmd, VI_UP_LINE_OR_HISTORY, ctrl('P')); + bind(vicmd, QUOTED_INSERT, ctrl('Q')); + bind(vicmd, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('R')); + bind(vicmd, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('S')); + bind(vicmd, TRANSPOSE_CHARS, ctrl('T')); + bind(vicmd, KILL_WHOLE_LINE, ctrl('U')); + bind(vicmd, QUOTED_INSERT, ctrl('V')); + bind(vicmd, BACKWARD_KILL_WORD, ctrl('W')); + bind(vicmd, YANK, ctrl('Y')); + bind(vicmd, HISTORY_INCREMENTAL_SEARCH_BACKWARD, ctrl('X') + "r"); + bind(vicmd, HISTORY_INCREMENTAL_SEARCH_FORWARD, ctrl('X') + "s"); + bind(vicmd, SEND_BREAK, alt(ctrl('G'))); + bind(vicmd, BACKWARD_KILL_WORD, alt(ctrl('H'))); + bind(vicmd, SELF_INSERT_UNMETA, alt(ctrl('M'))); + bind(vicmd, COMPLETE_WORD, alt(esc())); + bind(vicmd, CHARACTER_SEARCH_BACKWARD, alt(ctrl(']'))); + bind(vicmd, SET_MARK_COMMAND, alt(' ')); + // bind(vicmd, INSERT_COMMENT, alt('#')); + // bind(vicmd, INSERT_COMPLETIONS, alt('*')); + bind(vicmd, DIGIT_ARGUMENT, alt('-')); + bind(vicmd, BEGINNING_OF_HISTORY, alt('<')); + bind(vicmd, LIST_CHOICES, alt('=')); + bind(vicmd, END_OF_HISTORY, alt('>')); + bind(vicmd, LIST_CHOICES, alt('?')); + bind(vicmd, DO_LOWERCASE_VERSION, range("^[A-^[Z")); + bind(vicmd, BACKWARD_WORD, alt('b')); + bind(vicmd, CAPITALIZE_WORD, alt('c')); + bind(vicmd, KILL_WORD, alt('d')); + bind(vicmd, FORWARD_WORD, alt('f')); + bind(vicmd, DOWN_CASE_WORD, alt('l')); + bind(vicmd, HISTORY_SEARCH_FORWARD, alt('n')); + bind(vicmd, HISTORY_SEARCH_BACKWARD, alt('p')); + bind(vicmd, TRANSPOSE_WORDS, alt('t')); + bind(vicmd, UP_CASE_WORD, alt('u')); + bind(vicmd, YANK_POP, alt('y')); + bind(vicmd, BACKWARD_KILL_WORD, alt(del())); + + bind(vicmd, FORWARD_CHAR, " "); + bind(vicmd, VI_INSERT_COMMENT, "#"); + bind(vicmd, END_OF_LINE, "$"); + bind(vicmd, VI_MATCH_BRACKET, "%"); + bind(vicmd, VI_DOWN_LINE_OR_HISTORY, "+"); + bind(vicmd, VI_REV_REPEAT_FIND, ","); + bind(vicmd, VI_UP_LINE_OR_HISTORY, "-"); + bind(vicmd, VI_REPEAT_CHANGE, "."); + bind(vicmd, VI_HISTORY_SEARCH_BACKWARD, "/"); + bind(vicmd, VI_DIGIT_OR_BEGINNING_OF_LINE, "0"); + bind(vicmd, DIGIT_ARGUMENT, range("1-9")); + bind(vicmd, VI_REPEAT_FIND, ";"); + bind(vicmd, LIST_CHOICES, "="); + bind(vicmd, VI_HISTORY_SEARCH_FORWARD, "?"); + bind(vicmd, VI_ADD_EOL, "A"); + bind(vicmd, VI_BACKWARD_BLANK_WORD, "B"); + bind(vicmd, VI_CHANGE_EOL, "C"); + bind(vicmd, VI_KILL_EOL, "D"); + bind(vicmd, VI_FORWARD_BLANK_WORD_END, "E"); + bind(vicmd, VI_FIND_PREV_CHAR, "F"); + bind(vicmd, VI_FETCH_HISTORY, "G"); + bind(vicmd, VI_INSERT_BOL, "I"); + bind(vicmd, VI_JOIN, "J"); + bind(vicmd, VI_REV_REPEAT_SEARCH, "N"); + bind(vicmd, VI_OPEN_LINE_ABOVE, "O"); + bind(vicmd, VI_PUT_BEFORE, "P"); + bind(vicmd, VI_REPLACE, "R"); + bind(vicmd, VI_KILL_LINE, "S"); + bind(vicmd, VI_FIND_PREV_CHAR_SKIP, "T"); + bind(vicmd, REDO, "U"); + bind(vicmd, VISUAL_LINE_MODE, "V"); + bind(vicmd, VI_FORWARD_BLANK_WORD, "W"); + bind(vicmd, VI_BACKWARD_DELETE_CHAR, "X"); + bind(vicmd, VI_YANK_WHOLE_LINE, "Y"); + bind(vicmd, VI_FIRST_NON_BLANK, "^"); + bind(vicmd, VI_ADD_NEXT, "a"); + bind(vicmd, VI_BACKWARD_WORD, "b"); + bind(vicmd, VI_CHANGE, "c"); + bind(vicmd, VI_DELETE, "d"); + bind(vicmd, VI_FORWARD_WORD_END, "e"); + bind(vicmd, VI_FIND_NEXT_CHAR, "f"); + bind(vicmd, WHAT_CURSOR_POSITION, "ga"); + bind(vicmd, VI_BACKWARD_BLANK_WORD_END, "gE"); + bind(vicmd, VI_BACKWARD_WORD_END, "ge"); + bind(vicmd, VI_BACKWARD_CHAR, "h"); + bind(vicmd, VI_INSERT, "i"); + bind(vicmd, DOWN_LINE_OR_HISTORY, "j"); + bind(vicmd, UP_LINE_OR_HISTORY, "k"); + bind(vicmd, VI_FORWARD_CHAR, "l"); + bind(vicmd, VI_REPEAT_SEARCH, "n"); + bind(vicmd, VI_OPEN_LINE_BELOW, "o"); + bind(vicmd, VI_PUT_AFTER, "p"); + bind(vicmd, VI_REPLACE_CHARS, "r"); + bind(vicmd, VI_SUBSTITUTE, "s"); + bind(vicmd, VI_FIND_NEXT_CHAR_SKIP, "t"); + bind(vicmd, UNDO, "u"); + bind(vicmd, VISUAL_MODE, "v"); + bind(vicmd, VI_FORWARD_WORD, "w"); + bind(vicmd, VI_DELETE_CHAR, "x"); + bind(vicmd, VI_YANK, "y"); + bind(vicmd, VI_GOTO_COLUMN, "|"); + bind(vicmd, VI_SWAP_CASE, "~"); + bind(vicmd, VI_BACKWARD_CHAR, del()); bindArrowKeys(vicmd); return vicmd; @@ -6150,38 +6303,46 @@ public KeyMap menu() { KeyMap menu = new KeyMap<>(); - bind(menu, MENU_COMPLETE, "\t"); - bind(menu, REVERSE_MENU_COMPLETE, key(Capability.back_tab)); - bind(menu, ACCEPT_LINE, "\r", "\n"); + bind(menu, MENU_COMPLETE, "\t"); + bind(menu, REVERSE_MENU_COMPLETE, key(Capability.back_tab)); + bind(menu, ACCEPT_LINE, "\r", "\n"); bindArrowKeys(menu); return menu; } public KeyMap safe() { KeyMap safe = new KeyMap<>(); - bind(safe, SELF_INSERT, range("^@-^?")); - bind(safe, ACCEPT_LINE, "\r", "\n"); - bind(safe, SEND_BREAK, ctrl('G')); + bind(safe, SELF_INSERT, range("^@-^?")); + bind(safe, ACCEPT_LINE, "\r", "\n"); + bind(safe, SEND_BREAK, ctrl('G')); return safe; } + public KeyMap dumb() { + KeyMap dumb = new KeyMap<>(); + bind(dumb, SELF_INSERT, range("^@-^?")); + bind(dumb, ACCEPT_LINE, "\r", "\n"); + bind(dumb, BEEP, ctrl('G')); + return dumb; + } + public KeyMap visual() { KeyMap visual = new KeyMap<>(); - bind(visual, UP_LINE, key(Capability.key_up), "k"); - bind(visual, DOWN_LINE, key(Capability.key_down), "j"); - bind(visual, this::deactivateRegion, esc()); - bind(visual, EXCHANGE_POINT_AND_MARK, "o"); - bind(visual, PUT_REPLACE_SELECTION, "p"); - bind(visual, VI_DELETE, "x"); - bind(visual, VI_OPER_SWAP_CASE, "~"); + bind(visual, UP_LINE, key(Capability.key_up), "k"); + bind(visual, DOWN_LINE, key(Capability.key_down), "j"); + bind(visual, this::deactivateRegion, esc()); + bind(visual, EXCHANGE_POINT_AND_MARK, "o"); + bind(visual, PUT_REPLACE_SELECTION, "p"); + bind(visual, VI_DELETE, "x"); + bind(visual, VI_OPER_SWAP_CASE, "~"); return visual; } public KeyMap viOpp() { KeyMap viOpp = new KeyMap<>(); - bind(viOpp, UP_LINE, key(Capability.key_up), "k"); - bind(viOpp, DOWN_LINE, key(Capability.key_down), "j"); - bind(viOpp, VI_CMD_MODE, esc()); + bind(viOpp, UP_LINE, key(Capability.key_up), "k"); + bind(viOpp, DOWN_LINE, key(Capability.key_down), "j"); + bind(viOpp, VI_CMD_MODE, esc()); return viOpp; } @@ -6210,19 +6371,19 @@ } private void bindArrowKeys(KeyMap map) { - bind(map, UP_LINE_OR_SEARCH, key(Capability.key_up)); - bind(map, DOWN_LINE_OR_SEARCH, key(Capability.key_down)); - bind(map, BACKWARD_CHAR, key(Capability.key_left)); - bind(map, FORWARD_CHAR, key(Capability.key_right)); - bind(map, BEGINNING_OF_LINE, key(Capability.key_home)); - bind(map, END_OF_LINE, key(Capability.key_end)); - bind(map, DELETE_CHAR, key(Capability.key_dc)); - bind(map, KILL_WHOLE_LINE, key(Capability.key_dl)); - bind(map, OVERWRITE_MODE, key(Capability.key_ic)); - bind(map, MOUSE, key(Capability.key_mouse)); - bind(map, BEGIN_PASTE, BRACKETED_PASTE_BEGIN); - bind(map, FOCUS_IN, FOCUS_IN_SEQ); - bind(map, FOCUS_OUT, FOCUS_OUT_SEQ); + bind(map, UP_LINE_OR_SEARCH, key(Capability.key_up)); + bind(map, DOWN_LINE_OR_SEARCH, key(Capability.key_down)); + bind(map, BACKWARD_CHAR, key(Capability.key_left)); + bind(map, FORWARD_CHAR, key(Capability.key_right)); + bind(map, BEGINNING_OF_LINE, key(Capability.key_home)); + bind(map, END_OF_LINE, key(Capability.key_end)); + bind(map, DELETE_CHAR, key(Capability.key_dc)); + bind(map, KILL_WHOLE_LINE, key(Capability.key_dl)); + bind(map, OVERWRITE_MODE, key(Capability.key_ic)); + bind(map, MOUSE, key(Capability.key_mouse)); + bind(map, BEGIN_PASTE, BRACKETED_PASTE_BEGIN); + bind(map, FOCUS_IN, FOCUS_IN_SEQ); + bind(map, FOCUS_OUT, FOCUS_OUT_SEQ); } /** @@ -6231,14 +6392,10 @@ */ private void bindConsoleChars(KeyMap keyMap, Attributes attr) { if (attr != null) { - rebind(keyMap, BACKWARD_DELETE_CHAR, - del(), (char) attr.getControlChar(ControlChar.VERASE)); - rebind(keyMap, BACKWARD_KILL_WORD, - ctrl('W'), (char) attr.getControlChar(ControlChar.VWERASE)); - rebind(keyMap, KILL_WHOLE_LINE, - ctrl('U'), (char) attr.getControlChar(ControlChar.VKILL)); - rebind(keyMap, QUOTED_INSERT, - ctrl('V'), (char) attr.getControlChar(ControlChar.VLNEXT)); + rebind(keyMap, BACKWARD_DELETE_CHAR, del(), (char) attr.getControlChar(ControlChar.VERASE)); + rebind(keyMap, BACKWARD_KILL_WORD, ctrl('W'), (char) attr.getControlChar(ControlChar.VWERASE)); + rebind(keyMap, KILL_WHOLE_LINE, ctrl('U'), (char) attr.getControlChar(ControlChar.VKILL)); + rebind(keyMap, QUOTED_INSERT, ctrl('V'), (char) attr.getControlChar(ControlChar.VLNEXT)); } } @@ -6250,4 +6407,8 @@ } } + @Override + public void zeroOut() { + buf.zeroOut(); + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/ReaderUtils.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/ReaderUtils.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/ReaderUtils.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/ReaderUtils.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -13,7 +13,7 @@ public class ReaderUtils { - private ReaderUtils() { } + private ReaderUtils() {} public static boolean isSet(LineReader reader, LineReader.Option option) { return reader != null && reader.isSet(option); @@ -30,8 +30,7 @@ return (Boolean) v; } else if (v != null) { String s = v.toString(); - return s.isEmpty() || s.equalsIgnoreCase("on") - || s.equalsIgnoreCase("1") || s.equalsIgnoreCase("true"); + return s.isEmpty() || s.equalsIgnoreCase("on") || s.equalsIgnoreCase("1") || s.equalsIgnoreCase("true"); } return def; } @@ -77,5 +76,4 @@ return Levenshtein.distance(word, cand); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/SimpleMaskingCallback.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/SimpleMaskingCallback.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/SimpleMaskingCallback.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/SimpleMaskingCallback.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,10 +8,10 @@ */ package jdk.internal.org.jline.reader.impl; -import jdk.internal.org.jline.reader.MaskingCallback; - import java.util.Objects; +import jdk.internal.org.jline.reader.MaskingCallback; + /** * Simple {@link MaskingCallback} that will replace all the characters in the line with the given mask. * If the given mask is equal to {@link LineReaderImpl#NULL_MASK} then the line will be replaced with an empty String. @@ -29,7 +29,7 @@ return ""; } else { StringBuilder sb = new StringBuilder(line.length()); - for (int i = line.length(); i-- > 0;) { + for (int i = line.length(); i-- > 0; ) { sb.append((char) mask); } return sb.toString(); @@ -40,5 +40,4 @@ public String history(String line) { return null; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/UndoTree.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/UndoTree.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/UndoTree.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/UndoTree.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -20,6 +20,7 @@ private final Node parent; private Node current; + @SuppressWarnings("this-escape") public UndoTree(Consumer s) { state = s; parent = new Node(null); @@ -71,5 +72,4 @@ state = s; } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/AggregateCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/AggregateCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/AggregateCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/AggregateCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -24,9 +24,7 @@ * @author Jason Dillon * @since 2.3 */ -public class AggregateCompleter - implements Completer -{ +public class AggregateCompleter implements Completer { private final Collection completers; /** @@ -78,9 +76,6 @@ */ @Override public String toString() { - return getClass().getSimpleName() + "{" + - "completers=" + completers + - '}'; + return getClass().getSimpleName() + "{" + "completers=" + completers + '}'; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/ArgumentCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/ArgumentCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/ArgumentCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/ArgumentCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2019, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -29,8 +29,7 @@ * @author Jason Dillon * @since 2.3 */ -public class ArgumentCompleter implements Completer -{ +public class ArgumentCompleter implements Completer { private final List completers = new ArrayList<>(); private boolean strict = true; @@ -108,12 +107,12 @@ // if we are beyond the end of the completers, just use the last one if (line.wordIndex() >= completers.size()) { completer = completers.get(completers.size() - 1); - } - else { + } else { completer = completers.get(line.wordIndex()); } - // ensure that all the previous completers are successful before allowing this completer to pass (only if strict). + // ensure that all the previous completers are successful before allowing this completer to pass (only if + // strict). for (int i = strictCommand ? 0 : 1; isStrict() && (i < line.wordIndex()); i++) { int idx = i >= completers.size() ? (completers.size() - 1) : i; if (idx == 0 && !strictCommand) { diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/EnumCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/EnumCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/EnumCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/EnumCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -19,8 +19,7 @@ * @author Jason Dillon * @since 2.3 */ -public class EnumCompleter extends StringsCompleter -{ +public class EnumCompleter extends StringsCompleter { public EnumCompleter(Class> source) { Objects.requireNonNull(source); for (Enum n : source.getEnumConstants()) { diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/FileNameCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/FileNameCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/FileNameCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/FileNameCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -9,6 +9,7 @@ package jdk.internal.org.jline.reader.impl.completer; import java.io.IOException; +import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -41,11 +42,10 @@ * @author Marc Prud'hommeaux * @author Jason Dillon * @since 2.3 - * @deprecated use jdk.internal.org.jline.builtins.Completers$FileNameCompleter instead + * @deprecated use org.jline.builtins.Completers$FileNameCompleter instead */ @Deprecated -public class FileNameCompleter implements Completer -{ +public class FileNameCompleter implements Completer { public void complete(LineReader reader, ParsedLine commandLine, final List candidates) { assert commandLine != null; @@ -72,20 +72,21 @@ curBuf = ""; current = getUserDir(); } - try { - Files.newDirectoryStream(current, this::accept).forEach(p -> { + try (DirectoryStream directoryStream = Files.newDirectoryStream(current, this::accept)) { + directoryStream.forEach(p -> { String value = curBuf + p.getFileName().toString(); if (Files.isDirectory(p)) { candidates.add(new Candidate( value + (reader.isSet(Option.AUTO_PARAM_SLASH) ? sep : ""), getDisplay(reader.getTerminal(), p), - null, null, + null, + null, reader.isSet(Option.AUTO_REMOVE_SLASH) ? sep : null, null, false)); } else { - candidates.add(new Candidate(value, getDisplay(reader.getTerminal(), p), - null, null, null, null, true)); + candidates.add( + new Candidate(value, getDisplay(reader.getTerminal(), p), null, null, null, null, true)); } }); } catch (IOException e) { @@ -125,5 +126,4 @@ } return name; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/NullCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/NullCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/NullCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/NullCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -22,11 +22,8 @@ * @author Jason Dillon * @since 2.3 */ -public final class NullCompleter - implements Completer -{ +public final class NullCompleter implements Completer { public static final NullCompleter INSTANCE = new NullCompleter(); - public void complete(LineReader reader, final ParsedLine line, final List candidates) { - } + public void complete(LineReader reader, final ParsedLine line, final List candidates) {} } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/StringsCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/StringsCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/StringsCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/StringsCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2019, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -27,8 +27,7 @@ * @author Jason Dillon * @since 2.3 */ -public class StringsCompleter implements Completer -{ +public class StringsCompleter implements Completer { protected Collection candidates; protected Supplier> stringsSupplier; @@ -54,7 +53,7 @@ } } - public StringsCompleter(Candidate ... candidates) { + public StringsCompleter(Candidate... candidates) { this(Arrays.asList(candidates)); } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/SystemCompleter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/SystemCompleter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/SystemCompleter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/completer/SystemCompleter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -22,8 +22,8 @@ * @author Matti Rinta-Nikkola */ public class SystemCompleter implements Completer { - private Map> completers = new HashMap<>(); - private Map aliasCommand = new HashMap<>(); + private Map> completers = new HashMap<>(); + private Map aliasCommand = new HashMap<>(); private StringsCompleter commands; private boolean compiled = false; @@ -44,9 +44,9 @@ commands.complete(reader, commandLine, candidates); } else if (reader.getParser().validVariableName(buffer.substring(0, eq))) { String curBuf = buffer.substring(0, eq + 1); - for (String c: completers.keySet()) { - candidates.add(new Candidate(AttributedString.stripAnsi(curBuf+c) - , c, null, null, null, null, true)); + for (String c : completers.keySet()) { + candidates.add( + new Candidate(AttributedString.stripAnsi(curBuf + c), c, null, null, null, null, true)); } } } else { @@ -81,7 +81,7 @@ } public void add(List commands, Completer completer) { - for (String c: commands) { + for (String c : commands) { add(c, completer); } } @@ -104,22 +104,22 @@ if (other.isCompiled()) { throw new IllegalStateException(); } - for (Map.Entry> entry: other.getCompleters().entrySet()) { - for (Completer c: entry.getValue()) { + for (Map.Entry> entry : other.getCompleters().entrySet()) { + for (Completer c : entry.getValue()) { add(entry.getKey(), c); } } addAliases(other.getAliases()); } - public void addAliases(Map aliasCommand) { + public void addAliases(Map aliasCommand) { if (compiled) { throw new IllegalStateException(); } this.aliasCommand.putAll(aliasCommand); } - private Map getAliases() { + private Map getAliases() { return aliasCommand; } @@ -128,7 +128,7 @@ return; } Map> compiledCompleters = new HashMap<>(); - for (Map.Entry> entry: completers.entrySet()) { + for (Map.Entry> entry : completers.entrySet()) { if (entry.getValue().size() == 1) { compiledCompleters.put(entry.getKey(), entry.getValue()); } else { @@ -143,8 +143,7 @@ compiled = true; } - public Map> getCompleters() { + public Map> getCompleters() { return completers; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/history/DefaultHistory.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/history/DefaultHistory.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/history/DefaultHistory.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/reader/impl/history/DefaultHistory.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -41,9 +41,9 @@ private int offset = 0; private int index = 0; - public DefaultHistory() { - } + public DefaultHistory() {} + @SuppressWarnings("this-escape") public DefaultHistory(LineReader reader) { attach(reader); } @@ -67,8 +67,7 @@ this.reader = reader; try { load(); - } - catch (IllegalArgumentException | IOException e) { + } catch (IllegalArgumentException | IOException e) { Log.warn("Failed to load history", e); } } @@ -117,13 +116,13 @@ } } - private String doHistoryFileDataKey (Path path){ + private String doHistoryFileDataKey(Path path) { return path != null ? path.toAbsolutePath().toString() : null; } private HistoryFileData getHistoryFileData(Path path) { String key = doHistoryFileDataKey(path); - if (!historyFiles.containsKey(key)){ + if (!historyFiles.containsKey(key)) { historyFiles.put(key, new HistoryFileData()); } return historyFiles.get(key); @@ -133,7 +132,7 @@ historyFiles.put(doHistoryFileDataKey(path), historyFileData); } - private boolean isLineReaderHistory (Path path) throws IOException { + private boolean isLineReaderHistory(Path path) throws IOException { Path lrp = getPath(); if (lrp == null) { return path == null; @@ -141,23 +140,23 @@ return Files.isSameFile(lrp, path); } - private void setLastLoaded(Path path, int lastloaded){ + private void setLastLoaded(Path path, int lastloaded) { getHistoryFileData(path).setLastLoaded(lastloaded); } - private void setEntriesInFile(Path path, int entriesInFile){ + private void setEntriesInFile(Path path, int entriesInFile) { getHistoryFileData(path).setEntriesInFile(entriesInFile); } - private void incEntriesInFile(Path path, int amount){ + private void incEntriesInFile(Path path, int amount) { getHistoryFileData(path).incEntriesInFile(amount); } - private int getLastLoaded(Path path){ + private int getLastLoaded(Path path) { return getHistoryFileData(path).getLastLoaded(); } - private int getEntriesInFile(Path path){ + private int getEntriesInFile(Path path) { return getHistoryFileData(path).getEntriesInFile(); } @@ -168,9 +167,8 @@ protected void addHistoryLine(Path path, String line, boolean checkDuplicates) { if (reader.isSet(LineReader.Option.HISTORY_TIMESTAMPED)) { int idx = line.indexOf(':'); - final String badHistoryFileSyntax = "Bad history file syntax! " + - "The history file `" + path + "` may be an older history: " + - "please remove it or use a different history file."; + final String badHistoryFileSyntax = "Bad history file syntax! " + "The history file `" + path + + "` may be an older history: " + "please remove it or use a different history file."; if (idx < 0) { throw new IllegalArgumentException(badHistoryFileSyntax); } @@ -183,8 +181,7 @@ String unescaped = unescape(line.substring(idx + 1)); internalAdd(time, unescaped, checkDuplicates); - } - else { + } else { internalAdd(Instant.now(), unescape(line), checkDuplicates); } } @@ -210,8 +207,7 @@ @Override public void append(Path file, boolean incremental) throws IOException { - internalWrite(file != null ? file : getPath(), - incremental ? getLastLoaded(file) : 0); + internalWrite(file != null ? file : getPath(), incremental ? getLastLoaded(file) : 0); } @Override @@ -227,8 +223,11 @@ Files.createDirectories(parent); } // Append new items to the history file - try (BufferedWriter writer = Files.newBufferedWriter(path.toAbsolutePath(), - StandardOpenOption.WRITE, StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { + try (BufferedWriter writer = Files.newBufferedWriter( + path.toAbsolutePath(), + StandardOpenOption.WRITE, + StandardOpenOption.APPEND, + StandardOpenOption.CREATE)) { for (Entry entry : items.subList(from, items.size())) { if (isPersistable(entry)) { writer.append(format(entry)); @@ -248,18 +247,23 @@ Log.trace("Trimming history path: ", path); // Load all history entries LinkedList allItems = new LinkedList<>(); - try (BufferedReader reader = Files.newBufferedReader(path)) { - reader.lines().forEach(l -> { - int idx = l.indexOf(':'); - Instant time = Instant.ofEpochMilli(Long.parseLong(l.substring(0, idx))); - String line = unescape(l.substring(idx + 1)); - allItems.add(createEntry(allItems.size(), time, line)); + try (BufferedReader historyFileReader = Files.newBufferedReader(path)) { + historyFileReader.lines().forEach(l -> { + if (reader.isSet(LineReader.Option.HISTORY_TIMESTAMPED)) { + int idx = l.indexOf(':'); + Instant time = Instant.ofEpochMilli(Long.parseLong(l.substring(0, idx))); + String line = unescape(l.substring(idx + 1)); + allItems.add(createEntry(allItems.size(), time, line)); + } else { + allItems.add(createEntry(allItems.size(), Instant.now(), unescape(l))); + } }); } // Remove duplicates List trimmedItems = doTrimHistory(allItems, max); // Write history - Path temp = Files.createTempFile(path.toAbsolutePath().getParent(), path.getFileName().toString(), ".tmp"); + Path temp = Files.createTempFile( + path.toAbsolutePath().getParent(), path.getFileName().toString(), ".tmp"); try (BufferedWriter writer = Files.newBufferedWriter(temp, StandardOpenOption.WRITE)) { for (Entry entry : trimmedItems) { writer.append(format(entry)); @@ -351,7 +355,7 @@ public String get(final int index) { int idx = index - offset; if (idx >= items.size() || idx < 0) { - throw new IllegalArgumentException("IndexOutOfBounds: Index:" + idx +", Size:" + items.size()); + throw new IllegalArgumentException("IndexOutOfBounds: Index:" + idx + ", Size:" + items.size()); } return items.get(idx).line(); } @@ -382,8 +386,7 @@ if (isSet(reader, LineReader.Option.HISTORY_INCREMENTAL)) { try { save(); - } - catch (IOException e) { + } catch (IOException e) { Log.warn("Failed to save history", e); } } @@ -417,7 +420,7 @@ protected void internalAdd(Instant time, String line, boolean checkDuplicates) { Entry entry = new EntryImpl(offset + items.size(), time, line); if (checkDuplicates) { - for (Entry e: items) { + for (Entry e : items) { if (e.line().trim().equals(line.trim())) { return; } @@ -430,7 +433,7 @@ private void maybeResize() { while (size() > getInt(reader, LineReader.HISTORY_SIZE, DEFAULT_HISTORY_SIZE)) { items.removeFirst(); - for (HistoryFileData hfd: historyFiles.values()) { + for (HistoryFileData hfd : historyFiles.values()) { hfd.decLastLoaded(); } offset++; @@ -633,8 +636,7 @@ private int lastLoaded = 0; private int entriesInFile = 0; - public HistoryFileData() { - } + public HistoryFileData() {} public HistoryFileData(int lastLoaded, int entriesInFile) { this.lastLoaded = lastLoaded; @@ -667,8 +669,5 @@ public void incEntriesInFile(int amount) { entriesInFile = entriesInFile + amount; } - } - } - diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Attributes.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Attributes.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Attributes.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Attributes.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -43,63 +43,65 @@ * Input flags - software input processing */ public enum InputFlag { - IGNBRK, /* ignore BREAK condition */ - BRKINT, /* map BREAK to SIGINTR */ - IGNPAR, /* ignore (discard) parity errors */ - PARMRK, /* mark parity and framing errors */ - INPCK, /* enable checking of parity errors */ - ISTRIP, /* strip 8th bit off chars */ - INLCR, /* map NL into CR */ - IGNCR, /* ignore CR */ - ICRNL, /* map CR to NL (ala CRMOD) */ - IXON, /* enable output flow control */ - IXOFF, /* enable input flow control */ - IXANY, /* any char will restart after stop */ - IMAXBEL, /* ring bell on input queue full */ - IUTF8 /* maintain state for UTF-8 VERASE */ + IGNBRK, /* ignore BREAK condition */ + BRKINT, /* map BREAK to SIGINTR */ + IGNPAR, /* ignore (discard) parity errors */ + PARMRK, /* mark parity and framing errors */ + INPCK, /* enable checking of parity errors */ + ISTRIP, /* strip 8th bit off chars */ + INLCR, /* map NL into CR */ + IGNCR, /* ignore CR */ + ICRNL, /* map CR to NL (ala CRMOD) */ + IXON, /* enable output flow control */ + IXOFF, /* enable input flow control */ + IXANY, /* any char will restart after stop */ + IMAXBEL, /* ring bell on input queue full */ + IUTF8, /* maintain state for UTF-8 VERASE */ + + INORMEOL /* normalize end-of-line */ } /* * Output flags - software output processing */ public enum OutputFlag { - OPOST, /* enable following output processing */ - ONLCR, /* map NL to CR-NL (ala CRMOD) */ - OXTABS, /* expand tabs to spaces */ - ONOEOT, /* discard EOT's (^D) on output) */ - OCRNL, /* map CR to NL on output */ - ONOCR, /* no CR output at column 0 */ - ONLRET, /* NL performs CR function */ - OFILL, /* use fill characters for delay */ - NLDLY, /* \n delay */ - TABDLY, /* horizontal tab delay */ - CRDLY, /* \r delay */ - FFDLY, /* form feed delay */ - BSDLY, /* \b delay */ - VTDLY, /* vertical tab delay */ - OFDEL /* fill is DEL, else NUL */ + OPOST, /* enable following output processing */ + ONLCR, /* map NL to CR-NL (ala CRMOD) */ + OXTABS, /* expand tabs to spaces */ + ONOEOT, /* discard EOT's (^D) on output) */ + OCRNL, /* map CR to NL on output */ + ONOCR, /* no CR output at column 0 */ + ONLRET, /* NL performs CR function */ + OFILL, /* use fill characters for delay */ + NLDLY, /* \n delay */ + TABDLY, /* horizontal tab delay */ + CRDLY, /* \r delay */ + FFDLY, /* form feed delay */ + BSDLY, /* \b delay */ + VTDLY, /* vertical tab delay */ + OFDEL /* fill is DEL, else NUL */ } /* * Control flags - hardware control of terminal */ public enum ControlFlag { - CIGNORE, /* ignore control flags */ - CS5, /* 5 bits (pseudo) */ - CS6, /* 6 bits */ - CS7, /* 7 bits */ - CS8, /* 8 bits */ - CSTOPB, /* send 2 stop bits */ - CREAD, /* enable receiver */ - PARENB, /* parity enable */ - PARODD, /* odd parity, else even */ - HUPCL, /* hang up on last close */ - CLOCAL, /* ignore modem status lines */ - CCTS_OFLOW, /* CTS flow control of output */ - CRTS_IFLOW, /* RTS flow control of input */ - CDTR_IFLOW, /* DTR flow control of input */ - CDSR_OFLOW, /* DSR flow control of output */ - CCAR_OFLOW /* DCD flow control of output */ + CIGNORE, /* ignore control flags */ + CS5, /* 5 bits (pseudo) */ + CS6, /* 6 bits */ + CS7, /* 7 bits */ + CS8, /* 8 bits */ + CSTOPB, /* send 2 stop bits */ + CREAD, /* enable receiver */ + PARENB, /* parity enable */ + PARODD, /* odd parity, else even */ + HUPCL, /* hang up on last close */ + CLOCAL, /* ignore modem status lines */ + CCTS_OFLOW, /* CTS flow control of output */ + CRTS_IFLOW, /* RTS flow control of input */ + CDTR_IFLOW, /* DTR flow control of input */ + CDSR_OFLOW, /* DSR flow control of output */ + CCAR_OFLOW /* DCD flow control of output */ } /* @@ -110,23 +112,23 @@ * input flag. */ public enum LocalFlag { - ECHOKE, /* visual erase for line kill */ - ECHOE, /* visually erase chars */ - ECHOK, /* echo NL after line kill */ - ECHO, /* enable echoing */ - ECHONL, /* echo NL even if ECHO is off */ - ECHOPRT, /* visual erase mode for hardcopy */ - ECHOCTL, /* echo control chars as ^(Char) */ - ISIG, /* enable signals INTR, QUIT, [D]SUSP */ - ICANON, /* canonicalize input lines */ - ALTWERASE, /* use alternate WERASE algorithm */ - IEXTEN, /* enable DISCARD and LNEXT */ - EXTPROC, /* external processing */ - TOSTOP, /* stop background jobs from output */ - FLUSHO, /* output being flushed (state) */ - NOKERNINFO, /* no kernel output from VSTATUS */ - PENDIN, /* XXX retype pending input (state) */ - NOFLSH /* don't flush after interrupt */ + ECHOKE, /* visual erase for line kill */ + ECHOE, /* visually erase chars */ + ECHOK, /* echo NL after line kill */ + ECHO, /* enable echoing */ + ECHONL, /* echo NL even if ECHO is off */ + ECHOPRT, /* visual erase mode for hardcopy */ + ECHOCTL, /* echo control chars as ^(Char) */ + ISIG, /* enable signals INTR, QUIT, [D]SUSP */ + ICANON, /* canonicalize input lines */ + ALTWERASE, /* use alternate WERASE algorithm */ + IEXTEN, /* enable DISCARD and LNEXT */ + EXTPROC, /* external processing */ + TOSTOP, /* stop background jobs from output */ + FLUSHO, /* output being flushed (state) */ + NOKERNINFO, /* no kernel output from VSTATUS */ + PENDIN, /* XXX retype pending input (state) */ + NOFLSH /* don't flush after interrupt */ } final EnumSet iflag = EnumSet.noneOf(InputFlag.class); @@ -135,9 +137,9 @@ final EnumSet lflag = EnumSet.noneOf(LocalFlag.class); final EnumMap cchars = new EnumMap<>(ControlChar.class); - public Attributes() { - } + public Attributes() {} + @SuppressWarnings("this-escape") public Attributes(Attributes attr) { copy(attr); } @@ -310,13 +312,12 @@ @Override public String toString() { - return "Attributes[" + - "lflags: " + append(lflag) + ", " + - "iflags: " + append(iflag) + ", " + - "oflags: " + append(oflag) + ", " + - "cflags: " + append(cflag) + ", " + - "cchars: " + append(EnumSet.allOf(ControlChar.class), this::display) + - "]"; + return "Attributes[" + "lflags: " + + append(lflag) + ", " + "iflags: " + + append(iflag) + ", " + "oflags: " + + append(oflag) + ", " + "cflags: " + + append(cflag) + ", " + "cchars: " + + append(EnumSet.allOf(ControlChar.class), this::display) + "]"; } private String display(ControlChar c) { @@ -345,5 +346,4 @@ private > String append(EnumSet set, Function toString) { return set.stream().map(toString).collect(Collectors.joining(" ")); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Cursor.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Cursor.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Cursor.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Cursor.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/MouseEvent.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/MouseEvent.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/MouseEvent.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/MouseEvent.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -71,12 +71,11 @@ @Override public String toString() { - return "MouseEvent[" + - "type=" + type + - ", button=" + button + - ", modifiers=" + modifiers + - ", x=" + x + - ", y=" + y + - ']'; + return "MouseEvent[" + "type=" + + type + ", button=" + + button + ", modifiers=" + + modifiers + ", x=" + + x + ", y=" + + y + ']'; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Size.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Size.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Size.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Size.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -13,9 +13,9 @@ private int rows; private int cols; - public Size() { - } + public Size() {} + @SuppressWarnings("this-escape") public Size(int columns, int rows) { this(); setColumns(columns); @@ -50,7 +50,7 @@ * @return the cursor position */ public int cursorPos(int row, int col) { - return row * (cols+1) + col; + return row * (cols + 1) + col; } public void copy(Size size) { diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Terminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Terminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Terminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/Terminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -34,6 +34,7 @@ * Type used for dumb terminals. */ String TYPE_DUMB = "dumb"; + String TYPE_DUMB_COLOR = "dumb-color"; String getName(); @@ -42,6 +43,9 @@ // Signal support // + /** + * Types of signals. + */ enum Signal { INT, QUIT, @@ -51,16 +55,55 @@ WINCH } + /** + * The SignalHandler defines the interface used to trap signals and perform specific behaviors. + * @see Terminal.Signal + * @see Terminal#handle(Signal, SignalHandler) + */ interface SignalHandler { + /** + * The {@code SIG_DFL} value can be used to specify that the JVM default behavior + * should be used to handle this signal. + */ SignalHandler SIG_DFL = NativeSignalHandler.SIG_DFL; + + /** + * The {@code SIG_IGN} value can be used to ignore this signal and not perform + * any special processing. + */ SignalHandler SIG_IGN = NativeSignalHandler.SIG_IGN; + /** + * Handle the signal. + * @param signal the signal + */ void handle(Signal signal); } + /** + * Registers a handler for the given {@link Signal}. + *

+ * Note that the JVM does not easily allow catching the {@link Signal#QUIT} signal, which causes a thread dump + * to be displayed. This signal is mainly used when connecting through an SSH socket to a virtual terminal. + * + * @param signal the signal to register a handler for + * @param handler the handler + * @return the previous signal handler + */ SignalHandler handle(Signal signal, SignalHandler handler); + /** + * Raise the specific signal. + * This is not method usually called by non system terminals. + * When accessing a terminal through a SSH or Telnet connection, signals may be + * conveyed by the protocol and thus need to be raised when reaching the terminal code. + * The terminals do that automatically when the terminal input stream has a character + * mapped to {@link Attributes.ControlChar#VINTR}, {@link Attributes.ControlChar#VQUIT}, + * or {@link Attributes.ControlChar#VSUSP}. + * + * @param signal the signal to raise + */ void raise(Signal signal); // @@ -180,8 +223,21 @@ boolean echo(boolean echo); + /** + * Returns the terminal attributes. + * The returned object can be safely modified + * further used in a call to {@link #setAttributes(Attributes)}. + * + * @return the terminal attributes. + */ Attributes getAttributes(); + /** + * Set the terminal attributes. + * The terminal will perform a copy of the given attributes. + * + * @param attr the new attributes + */ void setAttributes(Attributes attr); /** @@ -334,5 +390,4 @@ * Color support */ ColorPalette getPalette(); - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/TerminalBuilder.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/TerminalBuilder.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/TerminalBuilder.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/TerminalBuilder.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,9 +8,6 @@ */ package jdk.internal.org.jline.terminal; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -19,11 +16,16 @@ import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.ServiceLoader; +import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; @@ -31,8 +33,10 @@ import jdk.internal.org.jline.terminal.impl.AbstractPosixTerminal; import jdk.internal.org.jline.terminal.impl.AbstractTerminal; -import jdk.internal.org.jline.terminal.impl.AbstractWindowsTerminal; import jdk.internal.org.jline.terminal.impl.DumbTerminal; +import jdk.internal.org.jline.terminal.impl.DumbTerminalProvider; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalExt; import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.Log; import jdk.internal.org.jline.utils.OSUtils; @@ -49,16 +53,30 @@ public static final String PROP_ENCODING = "org.jline.terminal.encoding"; public static final String PROP_CODEPAGE = "org.jline.terminal.codepage"; public static final String PROP_TYPE = "org.jline.terminal.type"; - public static final String PROP_JNA = "org.jline.terminal.jna"; - public static final String PROP_JANSI = "org.jline.terminal.jansi"; - public static final String PROP_EXEC = "org.jline.terminal.exec"; - public static final String PROP_DUMB = "org.jline.terminal.dumb"; + public static final String PROP_PROVIDER = "org.jline.terminal.provider"; + public static final String PROP_PROVIDERS = "org.jline.terminal.providers"; + public static final String PROP_PROVIDER_FFM = "ffm"; + public static final String PROP_PROVIDER_JNI = "jni"; + public static final String PROP_PROVIDER_JANSI = "jansi"; + public static final String PROP_PROVIDER_JNA = "jna"; + public static final String PROP_PROVIDER_EXEC = "exec"; + public static final String PROP_PROVIDER_DUMB = "dumb"; + public static final String PROP_PROVIDERS_DEFAULT = String.join( + ",", PROP_PROVIDER_FFM, PROP_PROVIDER_JNI, PROP_PROVIDER_JANSI, PROP_PROVIDER_JNA, PROP_PROVIDER_EXEC); + public static final String PROP_FFM = "org.jline.terminal." + PROP_PROVIDER_FFM; + public static final String PROP_JNI = "org.jline.terminal." + PROP_PROVIDER_JNI; + public static final String PROP_JANSI = "org.jline.terminal." + PROP_PROVIDER_JANSI; + public static final String PROP_JNA = "org.jline.terminal." + PROP_PROVIDER_JNA; + public static final String PROP_EXEC = "org.jline.terminal." + PROP_PROVIDER_EXEC; + public static final String PROP_DUMB = "org.jline.terminal." + PROP_PROVIDER_DUMB; public static final String PROP_DUMB_COLOR = "org.jline.terminal.dumb.color"; public static final String PROP_OUTPUT = "org.jline.terminal.output"; public static final String PROP_OUTPUT_OUT = "out"; public static final String PROP_OUTPUT_ERR = "err"; public static final String PROP_OUTPUT_OUT_ERR = "out-err"; public static final String PROP_OUTPUT_ERR_OUT = "err-out"; + public static final String PROP_OUTPUT_FORCED_OUT = "forced-out"; + public static final String PROP_OUTPUT_FORCED_ERR = "forced-err"; // // Other system properties controlling various jline parts @@ -69,13 +87,41 @@ public static final String PROP_DISABLE_ALTERNATE_CHARSET = "org.jline.utils.disableAlternateCharset"; // + // System properties controlling how FileDescriptor are create. + // The value can be a comma separated list of defined mechanisms. + // + public static final String PROP_FILE_DESCRIPTOR_CREATION_MODE = "org.jline.terminal.pty.fileDescriptorCreationMode"; + public static final String PROP_FILE_DESCRIPTOR_CREATION_MODE_NATIVE = "native"; + public static final String PROP_FILE_DESCRIPTOR_CREATION_MODE_REFLECTION = "reflection"; + public static final String PROP_FILE_DESCRIPTOR_CREATION_MODE_DEFAULT = + String.join(",", PROP_FILE_DESCRIPTOR_CREATION_MODE_REFLECTION, PROP_FILE_DESCRIPTOR_CREATION_MODE_NATIVE); + + // + // System properties controlling how RedirectPipe are created. + // The value can be a comma separated list of defined mechanisms. + // + public static final String PROP_REDIRECT_PIPE_CREATION_MODE = "org.jline.terminal.exec.redirectPipeCreationMode"; + public static final String PROP_REDIRECT_PIPE_CREATION_MODE_NATIVE = "native"; + public static final String PROP_REDIRECT_PIPE_CREATION_MODE_REFLECTION = "reflection"; + public static final String PROP_REDIRECT_PIPE_CREATION_MODE_DEFAULT = + String.join(",", PROP_REDIRECT_PIPE_CREATION_MODE_REFLECTION, PROP_REDIRECT_PIPE_CREATION_MODE_NATIVE); + + public static final Set DEPRECATED_PROVIDERS = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList(PROP_PROVIDER_JNA, PROP_PROVIDER_JANSI))); + + public static final String PROP_DISABLE_DEPRECATED_PROVIDER_WARNING = + "org.jline.terminal.disableDeprecatedProviderWarning"; + + // // Terminal output control // public enum SystemOutput { SysOut, SysErr, SysOutOrSysErr, - SysErrOrSysOut + SysErrOrSysOut, + ForcedSysOut, + ForcedSysErr } /** @@ -115,20 +161,23 @@ private int codepage; private Boolean system; private SystemOutput systemOutput; + private String provider; + private String providers; private Boolean jna; private Boolean jansi; + private Boolean jni; private Boolean exec; + private Boolean ffm; private Boolean dumb; private Boolean color; private Attributes attributes; private Size size; - private boolean nativeSignals = false; + private boolean nativeSignals = true; private Function inputStreamWrapper = in -> in; private Terminal.SignalHandler signalHandler = Terminal.SignalHandler.SIG_DFL; private boolean paused = false; - private TerminalBuilder() { - } + private TerminalBuilder() {} public TerminalBuilder name(String name) { this.name = name; @@ -160,6 +209,16 @@ return this; } + public TerminalBuilder provider(String provider) { + this.provider = provider; + return this; + } + + public TerminalBuilder providers(String providers) { + this.providers = providers; + return this; + } + public TerminalBuilder jna(boolean jna) { this.jna = jna; return this; @@ -170,11 +229,21 @@ return this; } + public TerminalBuilder jni(boolean jni) { + this.jni = jni; + return this; + } + public TerminalBuilder exec(boolean exec) { this.exec = exec; return this; } + public TerminalBuilder ffm(boolean ffm) { + this.ffm = ffm; + return this; + } + public TerminalBuilder dumb(boolean dumb) { this.dumb = dumb; return this; @@ -280,6 +349,12 @@ return this; } + /** + * Determines the default value for signal handlers. + * All signals will be mapped to the given handler. + * @param signalHandler the default signal handler + * @return The builder + */ public TerminalBuilder signalHandler(Terminal.SignalHandler signalHandler) { this.signalHandler = signalHandler; return this; @@ -305,6 +380,11 @@ return this; } + /** + * Builds the terminal. + * @return the newly created terminal, never {@code null} + * @throws IOException if an error occurs + */ public Terminal build() throws IOException { Terminal override = TERMINAL_OVERRIDE.get(); Terminal terminal = override != null ? override : doBuild(); @@ -313,7 +393,8 @@ } Log.debug(() -> "Using terminal " + terminal.getClass().getSimpleName()); if (terminal instanceof AbstractPosixTerminal) { - Log.debug(() -> "Using pty " + ((AbstractPosixTerminal) terminal).getPty().getClass().getSimpleName()); + Log.debug(() -> "Using pty " + + ((AbstractPosixTerminal) terminal).getPty().getClass().getSimpleName()); } return terminal; } @@ -323,144 +404,76 @@ if (name == null) { name = "JLine terminal"; } - Charset encoding = this.encoding; - if (encoding == null) { - String charsetName = System.getProperty(PROP_ENCODING); - if (charsetName != null && Charset.isSupported(charsetName)) { - encoding = Charset.forName(charsetName); - } - } - if (encoding == null) { - int codepage = this.codepage; - if (codepage <= 0) { - String str = System.getProperty(PROP_CODEPAGE); - if (str != null) { - codepage = Integer.parseInt(str); - } - } - if (codepage >= 0) { - encoding = getCodepageCharset(codepage); - } else { - encoding = StandardCharsets.UTF_8; - } - } - String type = this.type; - if (type == null) { - type = System.getProperty(PROP_TYPE); - } - if (type == null) { - type = System.getenv("TERM"); - } - Boolean jna = this.jna; - if (jna == null) { - jna = getBoolean(PROP_JNA, true); - } - Boolean jansi = this.jansi; - if (jansi == null) { - jansi = getBoolean(PROP_JANSI, true); - } - Boolean exec = this.exec; - if (exec == null) { - exec = getBoolean(PROP_EXEC, true); + Charset encoding = computeEncoding(); + String type = computeType(); + + String provider = this.provider; + if (provider == null) { + provider = System.getProperty(PROP_PROVIDER, null); } + + boolean forceDumb = + (DumbTerminal.TYPE_DUMB.equals(type) || type != null && type.startsWith(DumbTerminal.TYPE_DUMB_COLOR)) + || (provider != null && provider.equals(PROP_PROVIDER_DUMB)); Boolean dumb = this.dumb; if (dumb == null) { dumb = getBoolean(PROP_DUMB, null); } IllegalStateException exception = new IllegalStateException("Unable to create a terminal"); - List providers = new ArrayList<>(); - if (jna) { - try { - TerminalProvider provider = TerminalProvider.load("jna"); - providers.add(provider); - } catch (Throwable t) { - Log.debug("Unable to load JNA support: ", t); - exception.addSuppressed(t); - } - } - if (jansi) { - try { - TerminalProvider provider = TerminalProvider.load("jansi"); - providers.add(provider); - } catch (Throwable t) { - Log.debug("Unable to load JANSI support: ", t); - exception.addSuppressed(t); - } - } - if (exec) - { - try { - TerminalProvider provider = TerminalProvider.load("exec"); - providers.add(provider); - } catch (Throwable t) { - Log.debug("Unable to load EXEC support: ", t); - exception.addSuppressed(t); - } - } - + List providers = getProviders(provider, exception); Terminal terminal = null; if ((system != null && system) || (system == null && in == null && out == null)) { - if (system != null && ((in != null && !in.equals(System.in)) || - (out != null && !out.equals(System.out) && !out.equals(System.err)))) { + if (system != null + && ((in != null && !in.equals(System.in)) + || (out != null && !out.equals(System.out) && !out.equals(System.err)))) { throw new IllegalArgumentException("Cannot create a system terminal using non System streams"); } if (attributes != null || size != null) { Log.warn("Attributes and size fields are ignored when creating a system terminal"); } - if (out != null) { - if (out.equals(System.out)) { - systemOutput = SystemOutput.SysOut; - } else if (out.equals(System.err)) { - systemOutput = SystemOutput.SysErr; - } - } - if (systemOutput == null) { - String str = System.getProperty(PROP_OUTPUT); - if (str != null) { - switch (str.trim().toLowerCase(Locale.ROOT)) { - case PROP_OUTPUT_OUT: systemOutput = SystemOutput.SysOut; break; - case PROP_OUTPUT_ERR: systemOutput = SystemOutput.SysErr; break; - case PROP_OUTPUT_OUT_ERR: systemOutput = SystemOutput.SysOutOrSysErr; break; - case PROP_OUTPUT_ERR_OUT: systemOutput = SystemOutput.SysErrOrSysOut; break; - default: - Log.debug("Unsupported value for " + PROP_OUTPUT + ": " + str + ". Supported values are: " - + String.join(", ", PROP_OUTPUT_OUT, PROP_OUTPUT_ERR, PROP_OUTPUT_OUT_ERR,PROP_OUTPUT_ERR_OUT) - + "."); - } - } - } - if (systemOutput == null) { - systemOutput = SystemOutput.SysOutOrSysErr; - } - Map system = Stream.of(TerminalProvider.Stream.values()) - .collect(Collectors.toMap(stream -> stream, stream -> providers.stream().anyMatch(p -> p.isSystemStream(stream)))); - TerminalProvider.Stream console = select(system, systemOutput); + SystemOutput systemOutput = computeSystemOutput(); + Map system = Stream.of(SystemStream.values()) + .collect(Collectors.toMap( + stream -> stream, stream -> providers.stream().anyMatch(p -> p.isSystemStream(stream)))); + SystemStream systemStream = select(system, systemOutput); - if (system.get(TerminalProvider.Stream.Input) && console != null) { + if (!forceDumb && system.get(SystemStream.Input) && systemStream != null) { if (attributes != null || size != null) { Log.warn("Attributes and size fields are ignored when creating a system terminal"); } boolean ansiPassThrough = OSUtils.IS_CONEMU; // Cygwin defaults to XTERM, but actually supports 256 colors, // so if the value comes from the environment, change it to xterm-256color - if ((OSUtils.IS_CYGWIN || OSUtils.IS_MSYSTEM) && "xterm".equals(type) - && this.type == null && System.getProperty(PROP_TYPE) == null) { + if ((OSUtils.IS_CYGWIN || OSUtils.IS_MSYSTEM) + && "xterm".equals(type) + && this.type == null + && System.getProperty(PROP_TYPE) == null) { type = "xterm-256color"; } - for ( TerminalProvider provider : providers) { + for (TerminalProvider prov : providers) { if (terminal == null) { try { - terminal = provider.sysTerminal(name, type, ansiPassThrough, encoding, - nativeSignals, signalHandler, paused, console, inputStreamWrapper); + terminal = prov.sysTerminal( + name, + type, + ansiPassThrough, + encoding, + nativeSignals, + signalHandler, + paused, + systemStream, + inputStreamWrapper); } catch (Throwable t) { - Log.debug("Error creating " + provider.name() + " based terminal: ", t.getMessage(), t); + Log.debug("Error creating " + prov.name() + " based terminal: ", t.getMessage(), t); exception.addSuppressed(t); } } } - if (terminal == null && OSUtils.IS_WINDOWS && !jna && !jansi && (dumb == null || !dumb)) { - throw new IllegalStateException("Unable to create a system terminal. On windows, either " - + "JNA or JANSI library is required. Make sure to add one of those in the classpath."); + if (terminal == null && OSUtils.IS_WINDOWS && providers.isEmpty() && (dumb == null || !dumb)) { + throw new IllegalStateException( + "Unable to create a system terminal. On Windows, either JLine's native libraries, JNA " + + "or Jansi library is required. Make sure to add one of those in the classpath.", + exception); } } if (terminal instanceof AbstractTerminal) { @@ -468,54 +481,42 @@ if (SYSTEM_TERMINAL.compareAndSet(null, t)) { t.setOnClose(() -> SYSTEM_TERMINAL.compareAndSet(t, null)); } else { - exception.addSuppressed(new IllegalStateException("A system terminal is already running. " + - "Make sure to use the created system Terminal on the LineReaderBuilder if you're using one " + - "or that previously created system Terminals have been correctly closed.")); + exception.addSuppressed(new IllegalStateException("A system terminal is already running. " + + "Make sure to use the created system Terminal on the LineReaderBuilder if you're using one " + + "or that previously created system Terminals have been correctly closed.")); terminal.close(); terminal = null; } } - if (terminal == null && (dumb == null || dumb)) { - // forced colored dumb terminal - Boolean color = this.color; - if (color == null) { - color = getBoolean(PROP_DUMB_COLOR, false); - // detect emacs using the env variable - if (!color) { - String emacs = System.getenv("INSIDE_EMACS"); - color = emacs != null && emacs.contains("comint"); - } - // detect Intellij Idea - if (!color) { - String command = getParentProcessCommand(); - color = command != null && command.contains("idea"); - } - if (!color) { - color = system.get(TerminalProvider.Stream.Output) && System.getenv("TERM") != null; - } - if (!color && dumb == null) { - if (Log.isDebugEnabled()) { - Log.warn("input is tty: {}", system.get(TerminalProvider.Stream.Input)); - Log.warn("output is tty: {}", system.get(TerminalProvider.Stream.Output)); - Log.warn("error is tty: {}", system.get(TerminalProvider.Stream.Error)); - Log.warn("Creating a dumb terminal", exception); - } else { - Log.warn("Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)"); - } + if (terminal == null && (forceDumb || dumb == null || dumb)) { + if (!forceDumb && dumb == null) { + if (Log.isDebugEnabled()) { + Log.warn("input is tty: " + system.get(SystemStream.Input)); + Log.warn("output is tty: " + system.get(SystemStream.Output)); + Log.warn("error is tty: " + system.get(SystemStream.Error)); + Log.warn("Creating a dumb terminal", exception); + } else { + Log.warn( + "Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)"); } } - terminal = new DumbTerminal(name, color ? Terminal.TYPE_DUMB_COLOR : Terminal.TYPE_DUMB, - new FileInputStream(FileDescriptor.in), - new FileOutputStream(console == TerminalProvider.Stream.Output ? FileDescriptor.out : FileDescriptor.err), - encoding, signalHandler); + type = getDumbTerminalType(dumb, systemStream); + terminal = new DumbTerminalProvider() + .sysTerminal(name, type, false, encoding, nativeSignals, signalHandler, paused, systemStream, inputStreamWrapper); + if (OSUtils.IS_WINDOWS) { + Attributes attr = terminal.getAttributes(); + attr.setInputFlag(Attributes.InputFlag.IGNCR, true); + terminal.setAttributes(attr); + } } } else { - for ( TerminalProvider provider : providers) { + for (TerminalProvider prov : providers) { if (terminal == null) { try { - terminal = provider.newTerminal(name, type, inputStreamWrapper.apply(in), out, encoding, signalHandler, paused, attributes, size); + terminal = prov.newTerminal( + name, type, in, out, encoding, signalHandler, paused, attributes, size); } catch (Throwable t) { - Log.debug("Error creating " + provider.name() + " based terminal: ", t.getMessage(), t); + Log.debug("Error creating " + prov.name() + " based terminal: ", t.getMessage(), t); exception.addSuppressed(t); } } @@ -524,25 +525,220 @@ if (terminal == null) { throw exception; } + if (terminal instanceof TerminalExt) { + TerminalExt te = (TerminalExt) terminal; + if (DEPRECATED_PROVIDERS.contains(te.getProvider().name()) + && !getBoolean(PROP_DISABLE_DEPRECATED_PROVIDER_WARNING, false)) { + Log.warn("The terminal provider " + te.getProvider().name() + + " has been deprecated, check your configuration. This warning can be disabled by setting the system property " + + PROP_DISABLE_DEPRECATED_PROVIDER_WARNING + " to true."); + } + } return terminal; } - private TerminalProvider.Stream select(Map system, SystemOutput systemOutput) { + private String getDumbTerminalType(Boolean dumb, SystemStream systemStream) { + // forced colored dumb terminal + Boolean color = this.color; + if (color == null) { + color = getBoolean(PROP_DUMB_COLOR, null); + } + if (dumb == null) { + // detect emacs using the env variable + if (color == null) { + String emacs = System.getenv("INSIDE_EMACS"); + if (emacs != null && emacs.contains("comint")) { + color = true; + } + } + // detect Intellij Idea + if (color == null) { + // using the env variable on windows + String ideHome = System.getenv("IDE_HOME"); + if (ideHome != null) { + color = true; + } else { + // using the parent process command on unix/mac + String command = getParentProcessCommand(); + if (command != null && command.endsWith("/idea")) { + color = true; + } + } + } + if (color == null) { + color = systemStream != null && System.getenv("TERM") != null; + } + } else { + if (color == null) { + color = false; + } + } + return color ? Terminal.TYPE_DUMB_COLOR : Terminal.TYPE_DUMB; + } + + public SystemOutput computeSystemOutput() { + SystemOutput systemOutput = null; + if (out != null) { + if (out.equals(System.out)) { + systemOutput = SystemOutput.SysOut; + } else if (out.equals(System.err)) { + systemOutput = SystemOutput.SysErr; + } + } + if (systemOutput == null) { + systemOutput = this.systemOutput; + } + if (systemOutput == null) { + String str = System.getProperty(PROP_OUTPUT); + if (str != null) { + switch (str.trim().toLowerCase(Locale.ROOT)) { + case PROP_OUTPUT_OUT: + systemOutput = SystemOutput.SysOut; + break; + case PROP_OUTPUT_ERR: + systemOutput = SystemOutput.SysErr; + break; + case PROP_OUTPUT_OUT_ERR: + systemOutput = SystemOutput.SysOutOrSysErr; + break; + case PROP_OUTPUT_ERR_OUT: + systemOutput = SystemOutput.SysErrOrSysOut; + break; + case PROP_OUTPUT_FORCED_OUT: + systemOutput = SystemOutput.ForcedSysOut; + break; + case PROP_OUTPUT_FORCED_ERR: + systemOutput = SystemOutput.ForcedSysErr; + break; + default: + Log.debug("Unsupported value for " + PROP_OUTPUT + ": " + str + ". Supported values are: " + + String.join( + ", ", + PROP_OUTPUT_OUT, + PROP_OUTPUT_ERR, + PROP_OUTPUT_OUT_ERR, + PROP_OUTPUT_ERR_OUT) + + "."); + } + } + } + if (systemOutput == null) { + systemOutput = SystemOutput.SysOutOrSysErr; + } + return systemOutput; + } + + public String computeType() { + String type = this.type; + if (type == null) { + type = System.getProperty(PROP_TYPE); + } + if (type == null) { + type = System.getenv("TERM"); + } + return type; + } + + public Charset computeEncoding() { + Charset encoding = this.encoding; + if (encoding == null) { + String charsetName = System.getProperty(PROP_ENCODING); + if (charsetName != null && Charset.isSupported(charsetName)) { + encoding = Charset.forName(charsetName); + } + } + if (encoding == null) { + int codepage = this.codepage; + if (codepage <= 0) { + String str = System.getProperty(PROP_CODEPAGE); + if (str != null) { + codepage = Integer.parseInt(str); + } + } + if (codepage >= 0) { + encoding = getCodepageCharset(codepage); + } else { + encoding = StandardCharsets.UTF_8; + } + } + return encoding; + } + + /** + * Get the list of available terminal providers. + * This list is sorted according to the {@link #PROP_PROVIDERS} system property. + * @param provider if not {@code null}, only this provider will be checked + * @param exception if a provider throws an exception, it will be added to this exception as a suppressed exception + * @return a list of terminal providers + */ + public List getProviders(String provider, IllegalStateException exception) { + List providers = new ArrayList<>(); + // Check ffm provider + checkProvider(provider, exception, providers, ffm, PROP_FFM, PROP_PROVIDER_FFM); + // Check jni provider + checkProvider(provider, exception, providers, jni, PROP_JNI, PROP_PROVIDER_JNI); + // Check jansi provider + checkProvider(provider, exception, providers, jansi, PROP_JANSI, PROP_PROVIDER_JANSI); + // Check jna provider + checkProvider(provider, exception, providers, jna, PROP_JNA, PROP_PROVIDER_JNA); + // Check exec provider + checkProvider(provider, exception, providers, exec, PROP_EXEC, PROP_PROVIDER_EXEC); + // Order providers + List order = Arrays.asList( + (this.providers != null ? this.providers : System.getProperty(PROP_PROVIDERS, PROP_PROVIDERS_DEFAULT)) + .split(",")); + providers.sort(Comparator.comparing(l -> { + int idx = order.indexOf(l.name()); + return idx >= 0 ? idx : Integer.MAX_VALUE; + })); + String names = providers.stream().map(TerminalProvider::name).collect(Collectors.joining(", ")); + Log.debug("Available providers: " + names); + return providers; + } + + private void checkProvider( + String provider, + IllegalStateException exception, + List providers, + Boolean load, + String property, + String name) { + Boolean doLoad = provider != null ? (Boolean) name.equals(provider) : load; + if (doLoad == null) { + doLoad = getBoolean(property, true); + } + if (doLoad) { + try { + TerminalProvider prov = TerminalProvider.load(name); + prov.isSystemStream(SystemStream.Output); + providers.add(prov); + } catch (Throwable t) { + Log.debug("Unable to load " + name + " provider: ", t); + exception.addSuppressed(t); + } + } + } + + private SystemStream select(Map system, SystemOutput systemOutput) { switch (systemOutput) { case SysOut: - return select(system, TerminalProvider.Stream.Output); + return select(system, SystemStream.Output); case SysErr: - return select(system, TerminalProvider.Stream.Error); + return select(system, SystemStream.Error); case SysOutOrSysErr: - return select(system, TerminalProvider.Stream.Output, TerminalProvider.Stream.Error); + return select(system, SystemStream.Output, SystemStream.Error); case SysErrOrSysOut: - return select(system, TerminalProvider.Stream.Error, TerminalProvider.Stream.Output); + return select(system, SystemStream.Error, SystemStream.Output); + case ForcedSysOut: + return SystemStream.Output; + case ForcedSysErr: + return SystemStream.Error; } return null; } - private static TerminalProvider.Stream select(Map system, TerminalProvider.Stream... streams) { - for (TerminalProvider.Stream s : streams) { + private static SystemStream select(Map system, SystemStream... streams) { + for (SystemStream s : streams) { if (system.get(s)) { return s; } @@ -557,7 +753,9 @@ Object parent = ((Optional) phClass.getMethod("parent").invoke(current)).orElse(null); Method infoMethod = phClass.getMethod("info"); Object info = infoMethod.invoke(parent); - Object command = ((Optional) infoMethod.getReturnType().getMethod("command").invoke(info)).orElse(null); + Object command = ((Optional) + infoMethod.getReturnType().getMethod("command").invoke(info)) + .orElse(null); return (String) command; } catch (Throwable t) { return null; @@ -582,7 +780,7 @@ private static final int UTF8_CODE_PAGE = 65001; private static Charset getCodepageCharset(int codepage) { - //http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html + // http://docs.oracle.com/javase/6/docs/technotes/guides/intl/encoding.doc.html if (codepage == UTF8_CODE_PAGE) { return StandardCharsets.UTF_8; } @@ -629,5 +827,4 @@ public static void setTerminalOverride(final Terminal terminal) { TERMINAL_OVERRIDE.set(terminal); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPosixTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPosixTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPosixTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPosixTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -18,6 +18,8 @@ import jdk.internal.org.jline.terminal.Cursor; import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.spi.Pty; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; public abstract class AbstractPosixTerminal extends AbstractTerminal { @@ -28,7 +30,8 @@ this(name, type, pty, null, SignalHandler.SIG_DFL); } - public AbstractPosixTerminal(String name, String type, Pty pty, Charset encoding, SignalHandler signalHandler) throws IOException { + public AbstractPosixTerminal(String name, String type, Pty pty, Charset encoding, SignalHandler signalHandler) + throws IOException { super(name, type, encoding, signalHandler); Objects.requireNonNull(pty); this.pty = pty; @@ -82,4 +85,13 @@ return CursorSupport.getCursorPosition(this, discarded); } + @Override + public TerminalProvider getProvider() { + return getPty().getProvider(); + } + + @Override + public SystemStream getSystemStream() { + return getPty().getSystemStream(); + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPty.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPty.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPty.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractPty.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2019, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,20 +8,39 @@ */ package jdk.internal.org.jline.terminal.impl; -import jdk.internal.org.jline.terminal.Attributes; -import jdk.internal.org.jline.terminal.spi.Pty; -import jdk.internal.org.jline.utils.NonBlockingInputStream; - +import java.io.FileDescriptor; +import java.io.FilterInputStream; import java.io.IOError; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; +import java.lang.reflect.Field; + +//import jdk.internal.org.jline.nativ.JLineLibrary; +//import jdk.internal.org.jline.nativ.JLineNativeLoader; +import jdk.internal.org.jline.terminal.Attributes; +import jdk.internal.org.jline.terminal.spi.Pty; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; +import jdk.internal.org.jline.utils.NonBlockingInputStream; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_FILE_DESCRIPTOR_CREATION_MODE; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_FILE_DESCRIPTOR_CREATION_MODE_DEFAULT; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_FILE_DESCRIPTOR_CREATION_MODE_NATIVE; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_FILE_DESCRIPTOR_CREATION_MODE_REFLECTION; import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_NON_BLOCKING_READS; public abstract class AbstractPty implements Pty { + protected final TerminalProvider provider; + protected final SystemStream systemStream; private Attributes current; + private boolean skipNextLf; + + public AbstractPty(TerminalProvider provider, SystemStream systemStream) { + this.provider = provider; + this.systemStream = systemStream; + } @Override public void setAttr(Attributes attr) throws IOException { @@ -32,10 +51,32 @@ @Override public InputStream getSlaveInput() throws IOException { InputStream si = doGetSlaveInput(); + InputStream nsi = new FilterInputStream(si) { + @Override + public int read() throws IOException { + for (; ; ) { + int c = super.read(); + if (current.getInputFlag(Attributes.InputFlag.INORMEOL)) { + if (c == '\r') { + skipNextLf = true; + c = '\n'; + } else if (c == '\n') { + if (skipNextLf) { + skipNextLf = false; + continue; + } + } else { + skipNextLf = false; + } + } + return c; + } + } + }; if (Boolean.parseBoolean(System.getProperty(PROP_NON_BLOCKING_READS, "true"))) { - return new PtyInputStream(si); + return new PtyInputStream(nsi); } else { - return si; + return nsi; } } @@ -49,6 +90,16 @@ } } + @Override + public TerminalProvider getProvider() { + return provider; + } + + @Override + public SystemStream getSystemStream() { + return systemStream; + } + class PtyInputStream extends NonBlockingInputStream { final InputStream in; int c = 0; @@ -102,4 +153,103 @@ } } + private static FileDescriptorCreator fileDescriptorCreator; + + protected static FileDescriptor newDescriptor(int fd) { + if (fileDescriptorCreator == null) { + String str = + System.getProperty(PROP_FILE_DESCRIPTOR_CREATION_MODE, PROP_FILE_DESCRIPTOR_CREATION_MODE_DEFAULT); + String[] modes = str.split(","); + IllegalStateException ise = new IllegalStateException("Unable to create FileDescriptor"); + for (String mode : modes) { + try { + switch (mode) { + case PROP_FILE_DESCRIPTOR_CREATION_MODE_NATIVE: + fileDescriptorCreator = null;//new NativeFileDescriptorCreator(); + break; + case PROP_FILE_DESCRIPTOR_CREATION_MODE_REFLECTION: + fileDescriptorCreator = new ReflectionFileDescriptorCreator(); + break; + } + } catch (Throwable t) { + // ignore + ise.addSuppressed(t); + } + if (fileDescriptorCreator != null) { + break; + } + } + if (fileDescriptorCreator == null) { + throw ise; + } + } + return fileDescriptorCreator.newDescriptor(fd); + } + + interface FileDescriptorCreator { + FileDescriptor newDescriptor(int fd); + } + + /* + * Class that could be used on OpenJDK 17. However, it requires the following JVM option + * --add-exports java.base/jdk.internal.access=ALL-UNNAMED + * so the benefit does not seem important enough to warrant the problems caused + * by access the jdk.internal.access package at compile time, which itself requires + * custom compiler options and a different maven module, or at least a different compile + * phase with a JDK 17 compiler. + * So, just keep the ReflectionFileDescriptorCreator for now. + * + static class Jdk17FileDescriptorCreator implements FileDescriptorCreator { + private final jdk.internal.access.JavaIOFileDescriptorAccess fdAccess; + Jdk17FileDescriptorCreator() { + fdAccess = jdk.internal.access.SharedSecrets.getJavaIOFileDescriptorAccess(); + } + + @Override + public FileDescriptor newDescriptor(int fd) { + FileDescriptor descriptor = new FileDescriptor(); + fdAccess.set(descriptor, fd); + return descriptor; + } + } + */ + + /** + * Reflection based file descriptor creator. + * This requires the following option + * --add-opens java.base/java.io=ALL-UNNAMED + */ + static class ReflectionFileDescriptorCreator implements FileDescriptorCreator { + private final Field fileDescriptorField; + + ReflectionFileDescriptorCreator() throws Exception { + Field field = FileDescriptor.class.getDeclaredField("fd"); + field.setAccessible(true); + fileDescriptorField = field; + } + + @Override + public FileDescriptor newDescriptor(int fd) { + FileDescriptor descriptor = new FileDescriptor(); + try { + fileDescriptorField.set(descriptor, fd); + } catch (IllegalAccessException e) { + // This should not happen as the field has been set accessible + throw new IllegalStateException(e); + } + return descriptor; + } + } + +// static class NativeFileDescriptorCreator implements FileDescriptorCreator { +// NativeFileDescriptorCreator() { +// // Force load the library +// JLineNativeLoader.initialize(); +// } +// +// @Override +// public FileDescriptor newDescriptor(int fd) { +// return JLineLibrary.newFileDescriptor(fd); +// } +// } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -27,7 +27,7 @@ import jdk.internal.org.jline.terminal.Attributes.LocalFlag; import jdk.internal.org.jline.terminal.Cursor; import jdk.internal.org.jline.terminal.MouseEvent; -import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.terminal.spi.TerminalExt; import jdk.internal.org.jline.utils.ColorPalette; import jdk.internal.org.jline.utils.Curses; import jdk.internal.org.jline.utils.InfoCmp; @@ -35,7 +35,7 @@ import jdk.internal.org.jline.utils.Log; import jdk.internal.org.jline.utils.Status; -public abstract class AbstractTerminal implements Terminal { +public abstract class AbstractTerminal implements TerminalExt { protected final String name; protected final String type; @@ -44,7 +44,7 @@ protected final Set bools = new HashSet<>(); protected final Map ints = new HashMap<>(); protected final Map strings = new HashMap<>(); - protected final ColorPalette palette = new ColorPalette(this); + protected final ColorPalette palette; protected Status status; protected Runnable onClose; @@ -52,10 +52,13 @@ this(name, type, null, SignalHandler.SIG_DFL); } - public AbstractTerminal(String name, String type, Charset encoding, SignalHandler signalHandler) throws IOException { + @SuppressWarnings("this-escape") + public AbstractTerminal(String name, String type, Charset encoding, SignalHandler signalHandler) + throws IOException { this.name = name; this.type = type != null ? type : "ansi"; this.encoding = encoding != null ? encoding : Charset.defaultCharset(); + this.palette = new ColorPalette(this); for (Signal signal : Signal.values()) { handlers.put(signal, signalHandler); } @@ -85,12 +88,13 @@ public void raise(Signal signal) { Objects.requireNonNull(signal); SignalHandler handler = handlers.get(signal); - if (handler != SignalHandler.SIG_DFL && handler != SignalHandler.SIG_IGN) { + if (handler == SignalHandler.SIG_DFL) { + if (status != null && signal == Signal.WINCH) { + status.resize(); + } + } else if (handler != SignalHandler.SIG_IGN) { handler.handle(signal); } - if (status != null && signal == Signal.WINCH) { - status.resize(); - } } public final void close() throws IOException { @@ -105,8 +109,7 @@ protected void doClose() throws IOException { if (status != null) { - status.update(null); - flush(); + status.close(); } } @@ -126,7 +129,7 @@ if (cc != null) { int vcc = getAttributes().getControlChar(cc); if (vcc > 0 && vcc < 32) { - writer().write(new char[]{'^', (char) (vcc + '@')}, 0, 2); + writer().write(new char[] {'^', (char) (vcc + '@')}, 0, 2); } } } @@ -217,8 +220,7 @@ } private MouseEvent lastMouseEvent = new MouseEvent( - MouseEvent.Type.Moved, MouseEvent.Button.NoButton, - EnumSet.noneOf(MouseEvent.Modifier.class), 0, 0); + MouseEvent.Type.Moved, MouseEvent.Button.NoButton, EnumSet.noneOf(MouseEvent.Modifier.class), 0, 0); @Override public boolean hasMouseSupport() { @@ -268,16 +270,13 @@ } @Override - public void pause() { - } + public void pause() {} @Override - public void pause(boolean wait) throws InterruptedException { - } + public void pause(boolean wait) throws InterruptedException {} @Override - public void resume() { - } + public void resume() {} @Override public boolean paused() { diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsConsoleWriter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsConsoleWriter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsConsoleWriter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsConsoleWriter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -29,11 +29,8 @@ } @Override - public void flush() { - } + public void flush() {} @Override - public void close() { - } - + public void close() {} } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/AbstractWindowsTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2023, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,8 +8,20 @@ */ package jdk.internal.org.jline.terminal.impl; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + import jdk.internal.org.jline.terminal.Attributes; import jdk.internal.org.jline.terminal.Size; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.Curses; import jdk.internal.org.jline.utils.InfoCmp; import jdk.internal.org.jline.utils.Log; @@ -21,17 +33,6 @@ import jdk.internal.org.jline.utils.Signals; import jdk.internal.org.jline.utils.WriterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.Writer; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - /** * The AbstractWindowsTerminal is used as the base class for windows terminal. * Due to windows limitations, mostly the missing support for ansi sequences, @@ -44,7 +45,7 @@ * the writer() becomes the primary output, while the output() is bridged * to the writer() using a WriterOutputStream wrapper. */ -public abstract class AbstractWindowsTerminal extends AbstractTerminal { +public abstract class AbstractWindowsTerminal extends AbstractTerminal { public static final String TYPE_WINDOWS = "windows"; public static final String TYPE_WINDOWS_256_COLOR = "windows-256color"; @@ -56,12 +57,13 @@ private static final int UTF8_CODE_PAGE = 65001; protected static final int ENABLE_PROCESSED_INPUT = 0x0001; - protected static final int ENABLE_LINE_INPUT = 0x0002; - protected static final int ENABLE_ECHO_INPUT = 0x0004; - protected static final int ENABLE_WINDOW_INPUT = 0x0008; - protected static final int ENABLE_MOUSE_INPUT = 0x0010; - protected static final int ENABLE_INSERT_MODE = 0x0020; + protected static final int ENABLE_LINE_INPUT = 0x0002; + protected static final int ENABLE_ECHO_INPUT = 0x0004; + protected static final int ENABLE_WINDOW_INPUT = 0x0008; + protected static final int ENABLE_MOUSE_INPUT = 0x0010; + protected static final int ENABLE_INSERT_MODE = 0x0020; protected static final int ENABLE_QUICK_EDIT_MODE = 0x0040; + protected static final int ENABLE_EXTENDED_FLAGS = 0x0080; protected final Writer slaveInputPipe; protected final InputStream input; @@ -71,7 +73,12 @@ protected final Map nativeHandlers = new HashMap<>(); protected final ShutdownHooks.Task closer; protected final Attributes attributes = new Attributes(); - protected final int originalConsoleMode; + protected final Console inConsole; + protected final Console outConsole; + protected final int originalInConsoleMode; + protected final int originalOutConsoleMode; + private final TerminalProvider provider; + private final SystemStream systemStream; protected final Object lock = new Object(); protected boolean paused = true; @@ -80,21 +87,42 @@ protected MouseTracking tracking = MouseTracking.Off; protected boolean focusTracking = false; private volatile boolean closing; + protected boolean skipNextLf; - public AbstractWindowsTerminal(Writer writer, String name, String type, Charset encoding, boolean nativeSignals, SignalHandler signalHandler, Function inputStreamWrapper) throws IOException { + @SuppressWarnings("this-escape") + public AbstractWindowsTerminal( + TerminalProvider provider, + SystemStream systemStream, + Writer writer, + String name, + String type, + Charset encoding, + boolean nativeSignals, + SignalHandler signalHandler, + Console inConsole, + int inConsoleMode, + Console outConsole, + int outConsoleMode, + Function inputStreamWrapper) + throws IOException { super(name, type, encoding, signalHandler); + this.provider = provider; + this.systemStream = systemStream; NonBlockingPumpReader reader = NonBlocking.nonBlockingPumpReader(); this.slaveInputPipe = reader.getWriter(); this.input = inputStreamWrapper.apply(NonBlocking.nonBlockingStream(reader, encoding())); this.reader = NonBlocking.nonBlocking(name, input, encoding()); this.writer = new PrintWriter(writer); this.output = new WriterOutputStream(writer, encoding()); + this.inConsole = inConsole; + this.outConsole = outConsole; parseInfoCmp(); // Attributes - originalConsoleMode = getConsoleMode(); + this.originalInConsoleMode = inConsoleMode; + this.originalOutConsoleMode = outConsoleMode; attributes.setLocalFlag(Attributes.LocalFlag.ISIG, true); attributes.setControlChar(Attributes.ControlChar.VINTR, ctrl('C')); - attributes.setControlChar(Attributes.ControlChar.VEOF, ctrl('D')); + attributes.setControlChar(Attributes.ControlChar.VEOF, ctrl('D')); attributes.setControlChar(Attributes.ControlChar.VSUSP, ctrl('Z')); // Handle signals if (nativeSignals) { @@ -148,7 +176,7 @@ } public Attributes getAttributes() { - int mode = getConsoleMode(); + int mode = getConsoleMode(inConsole); if ((mode & ENABLE_ECHO_INPUT) != 0) { attributes.setLocalFlag(Attributes.LocalFlag.ECHO, true); } @@ -173,8 +201,11 @@ } if (tracking != MouseTracking.Off) { mode |= ENABLE_MOUSE_INPUT; + // mouse events not send with quick edit mode + // to disable ENABLE_QUICK_EDIT_MODE just set extended flag + mode |= ENABLE_EXTENDED_FLAGS; } - setConsoleMode(mode); + setConsoleMode(inConsole, mode); } protected int ctrl(char key) { @@ -197,23 +228,26 @@ } reader.close(); writer.close(); - setConsoleMode(originalConsoleMode); + setConsoleMode(inConsole, originalInConsoleMode); + setConsoleMode(outConsole, originalOutConsoleMode); } static final int SHIFT_FLAG = 0x01; - static final int ALT_FLAG = 0x02; - static final int CTRL_FLAG = 0x04; + static final int ALT_FLAG = 0x02; + static final int CTRL_FLAG = 0x04; - static final int RIGHT_ALT_PRESSED = 0x0001; - static final int LEFT_ALT_PRESSED = 0x0002; - static final int RIGHT_CTRL_PRESSED = 0x0004; - static final int LEFT_CTRL_PRESSED = 0x0008; - static final int SHIFT_PRESSED = 0x0010; - static final int NUMLOCK_ON = 0x0020; - static final int SCROLLLOCK_ON = 0x0040; - static final int CAPSLOCK_ON = 0x0080; - - protected void processKeyEvent(final boolean isKeyDown, final short virtualKeyCode, char ch, final int controlKeyState) throws IOException { + static final int RIGHT_ALT_PRESSED = 0x0001; + static final int LEFT_ALT_PRESSED = 0x0002; + static final int RIGHT_CTRL_PRESSED = 0x0004; + static final int LEFT_CTRL_PRESSED = 0x0008; + static final int SHIFT_PRESSED = 0x0010; + static final int NUMLOCK_ON = 0x0020; + static final int SCROLLLOCK_ON = 0x0040; + static final int CAPSLOCK_ON = 0x0080; + + protected void processKeyEvent( + final boolean isKeyDown, final short virtualKeyCode, char ch, final int controlKeyState) + throws IOException { final boolean isCtrl = (controlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) > 0; final boolean isAlt = (controlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)) > 0; final boolean isShift = (controlKeyState & SHIFT_PRESSED) > 0; @@ -222,11 +256,13 @@ // Pressing "Alt Gr" is translated to Alt-Ctrl, hence it has to be checked that Ctrl is _not_ pressed, // otherwise inserting of "Alt Gr" codes on non-US keyboards would yield errors if (ch != 0 - && (controlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED | SHIFT_PRESSED)) - == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)) { + && (controlKeyState + & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED | RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)) + == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)) { processInputChar(ch); } else { - final String keySeq = getEscapeSequence(virtualKeyCode, (isCtrl ? CTRL_FLAG : 0) + (isAlt ? ALT_FLAG : 0) + (isShift ? SHIFT_FLAG : 0)); + final String keySeq = getEscapeSequence( + virtualKeyCode, (isCtrl ? CTRL_FLAG : 0) + (isAlt ? ALT_FLAG : 0) + (isShift ? SHIFT_FLAG : 0)); if (keySeq != null) { for (char c : keySeq.toCharArray()) { processInputChar(c); @@ -240,7 +276,7 @@ * 4). Ctrl + Space(0x20) : uchar=0x20 * 5). Ctrl + : uchar=0 * 6). Ctrl + Alt + : uchar=0 - */ + */ if (ch > 0) { if (isAlt) { processInputChar('\033'); @@ -254,10 +290,10 @@ } else { processInputChar(ch); } - } else if (isCtrl) { //Handles the ctrl key events(uchar=0) + } else if (isCtrl) { // Handles the ctrl key events(uchar=0) if (virtualKeyCode >= 'A' && virtualKeyCode <= 'Z') { ch = (char) (virtualKeyCode - 0x40); - } else if (virtualKeyCode == 191) { //? + } else if (virtualKeyCode == 191) { // ? ch = 127; } if (ch > 0) { @@ -275,7 +311,7 @@ else { // support ALT+NumPad input method if (virtualKeyCode == 0x12 /*VK_MENU ALT key*/ && ch > 0) { - processInputChar(ch); // no such combination in Windows + processInputChar(ch); // no such combination in Windows } } } @@ -468,7 +504,19 @@ raise(Signal.INFO); } } - if (c == '\r') { + if (attributes.getInputFlag(Attributes.InputFlag.INORMEOL)) { + if (c == '\r') { + skipNextLf = true; + c = '\n'; + } else if (c == '\n') { + if (skipNextLf) { + skipNextLf = false; + return; + } + } else { + skipNextLf = false; + } + } else if (c == '\r') { if (attributes.getInputFlag(Attributes.InputFlag.IGNCR)) { return; } @@ -478,10 +526,10 @@ } else if (c == '\n' && attributes.getInputFlag(Attributes.InputFlag.INLCR)) { c = '\r'; } -// if (attributes.getLocalFlag(Attributes.LocalFlag.ECHO)) { -// processOutputByte(c); -// masterOutput.flush(); -// } + // if (attributes.getLocalFlag(Attributes.LocalFlag.ECHO)) { + // processOutputByte(c); + // masterOutput.flush(); + // } slaveInputPipe.write(c); } @@ -492,9 +540,9 @@ return true; } - protected abstract int getConsoleMode(); + protected abstract int getConsoleMode(Console console); - protected abstract void setConsoleMode(int mode); + protected abstract void setConsoleMode(Console console, int mode); /** * Read a single input event from the input buffer and process it. @@ -504,5 +552,13 @@ */ protected abstract boolean processConsoleInput() throws IOException; -} + @Override + public TerminalProvider getProvider() { + return provider; + } + @Override + public SystemStream getSystemStream() { + return systemStream; + } +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/CursorSupport.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/CursorSupport.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/CursorSupport.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/CursorSupport.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,17 +8,17 @@ */ package jdk.internal.org.jline.terminal.impl; -import jdk.internal.org.jline.terminal.Cursor; -import jdk.internal.org.jline.terminal.Terminal; -import jdk.internal.org.jline.utils.Curses; -import jdk.internal.org.jline.utils.InfoCmp; - import java.io.IOError; import java.io.IOException; import java.util.function.IntConsumer; import java.util.regex.Matcher; import java.util.regex.Pattern; +import jdk.internal.org.jline.terminal.Cursor; +import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.utils.Curses; +import jdk.internal.org.jline.utils.InfoCmp; + public class CursorSupport { public static Cursor getCursorPosition(Terminal terminal, IntConsumer discarded) { @@ -105,5 +105,4 @@ throw new IOError(e); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/Diag.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/Diag.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/Diag.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/Diag.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, the original author or authors. + * Copyright (c) 2022, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -17,6 +17,7 @@ import jdk.internal.org.jline.terminal.Attributes; import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.terminal.spi.SystemStream; import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.OSUtils; @@ -26,7 +27,7 @@ diag(System.out); } - static void diag(PrintStream out) { + public static void diag(PrintStream out) { out.println("System properties"); out.println("================="); out.println("os.name = " + System.getProperty("os.name")); @@ -50,6 +51,17 @@ out.println("IS_OSX = " + OSUtils.IS_OSX); out.println(); + // FFM + out.println("FFM Support"); + out.println("================="); + try { + TerminalProvider provider = TerminalProvider.load("ffm"); + testProvider(out, provider); + } catch (Throwable t) { + out.println("FFM support not available: " + t); + } + out.println(); + out.println("JnaSupport"); out.println("================="); try { @@ -60,13 +72,23 @@ } out.println(); - out.println("JansiSupport"); + out.println("Jansi2Support"); out.println("================="); try { TerminalProvider provider = TerminalProvider.load("jansi"); testProvider(out, provider); } catch (Throwable t) { - out.println("Jansi support not available: " + t); + out.println("Jansi 2 support not available: " + t); + } + out.println(); + + out.println("JniSupport"); + out.println("================="); + try { + TerminalProvider provider = TerminalProvider.load("jni"); + testProvider(out, provider); + } catch (Throwable t) { + out.println("JNI support not available: " + t); } out.println(); @@ -83,32 +105,45 @@ private static void testProvider(PrintStream out, TerminalProvider provider) { try { - out.println("StdIn stream = " + provider.isSystemStream(TerminalProvider.Stream.Input)); - out.println("StdOut stream = " + provider.isSystemStream(TerminalProvider.Stream.Output)); - out.println("StdErr stream = " + provider.isSystemStream(TerminalProvider.Stream.Error)); + out.println("StdIn stream = " + provider.isSystemStream(SystemStream.Input)); + out.println("StdOut stream = " + provider.isSystemStream(SystemStream.Output)); + out.println("StdErr stream = " + provider.isSystemStream(SystemStream.Error)); } catch (Throwable t2) { out.println("Unable to check stream: " + t2); } try { - out.println("StdIn stream name = " + provider.systemStreamName(TerminalProvider.Stream.Input)); - out.println("StdOut stream name = " + provider.systemStreamName(TerminalProvider.Stream.Output)); - out.println("StdErr stream name = " + provider.systemStreamName(TerminalProvider.Stream.Error)); + out.println("StdIn stream name = " + provider.systemStreamName(SystemStream.Input)); + out.println("StdOut stream name = " + provider.systemStreamName(SystemStream.Output)); + out.println("StdErr stream name = " + provider.systemStreamName(SystemStream.Error)); } catch (Throwable t2) { out.println("Unable to check stream names: " + t2); } - try (Terminal terminal = provider.sysTerminal("diag", "xterm", false, StandardCharsets.UTF_8, - false, Terminal.SignalHandler.SIG_DFL, false, TerminalProvider.Stream.Output, input -> input) ) { + try (Terminal terminal = provider.sysTerminal( + "diag", + "xterm", + false, + StandardCharsets.UTF_8, + false, + Terminal.SignalHandler.SIG_DFL, + false, + SystemStream.Output, + input -> input)) { if (terminal != null) { Attributes attr = terminal.enterRawMode(); try { out.println("Terminal size: " + terminal.getSize()); - ForkJoinTask t = new ForkJoinPool(1).submit(() -> terminal.reader().read(1) ); + ForkJoinTask t = + new ForkJoinPool(1).submit(() -> terminal.reader().read(1)); int r = t.get(1000, TimeUnit.MILLISECONDS); StringBuilder sb = new StringBuilder(); sb.append("The terminal seems to work: "); sb.append("terminal ").append(terminal.getClass().getName()); if (terminal instanceof AbstractPosixTerminal) { - sb.append(" with pty ").append(((AbstractPosixTerminal) terminal).getPty().getClass().getName()); + sb.append(" with pty ") + .append(((AbstractPosixTerminal) terminal) + .getPty() + .getClass() + .getName()); } out.println(sb); } catch (Throwable t3) { @@ -129,5 +164,4 @@ static S load(Class clazz) { return ServiceLoader.load(clazz, clazz.getClassLoader()).iterator().next(); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -14,38 +14,58 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.Charset; +import java.util.function.Function; import jdk.internal.org.jline.terminal.Attributes; import jdk.internal.org.jline.terminal.Attributes.ControlChar; import jdk.internal.org.jline.terminal.Size; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.NonBlocking; import jdk.internal.org.jline.utils.NonBlockingInputStream; import jdk.internal.org.jline.utils.NonBlockingReader; public class DumbTerminal extends AbstractTerminal { + private final TerminalProvider provider; + private final SystemStream systemStream; private final NonBlockingInputStream input; private final OutputStream output; private final NonBlockingReader reader; private final PrintWriter writer; private final Attributes attributes; private final Size size; + private boolean skipNextLf; - public DumbTerminal(InputStream in, OutputStream out) throws IOException { - this(TYPE_DUMB, TYPE_DUMB, in, out, null); + public DumbTerminal(InputStream in, OutputStream out, Function inputStreamWrapper) throws IOException { + this(TYPE_DUMB, TYPE_DUMB, in, out, null, inputStreamWrapper); } - public DumbTerminal(String name, String type, InputStream in, OutputStream out, Charset encoding) throws IOException { - this(name, type, in, out, encoding, SignalHandler.SIG_DFL); - } - - public DumbTerminal(String name, String type, InputStream in, OutputStream out, Charset encoding, SignalHandler signalHandler) throws IOException { + public DumbTerminal(String name, String type, InputStream in, OutputStream out, Charset encoding, Function inputStreamWrapper) + throws IOException { + this(null, null, name, type, in, out, encoding, SignalHandler.SIG_DFL, inputStreamWrapper); + } + + @SuppressWarnings("this-escape") + public DumbTerminal( + TerminalProvider provider, + SystemStream systemStream, + String name, + String type, + InputStream in, + OutputStream out, + Charset encoding, + SignalHandler signalHandler, + Function inputStreamWrapper) + throws IOException { super(name, type, encoding, signalHandler); - NonBlockingInputStream nbis = NonBlocking.nonBlocking(getName(), in); + this.provider = provider; + this.systemStream = systemStream; + NonBlockingInputStream nbis = NonBlocking.nonBlocking(getName(), inputStreamWrapper.apply(in)); this.input = new NonBlockingInputStream() { @Override public int read(long timeout, boolean isPeek) throws IOException { - for (;;) { + for (; ; ) { int c = nbis.read(timeout, isPeek); if (attributes.getLocalFlag(Attributes.LocalFlag.ISIG)) { if (c == attributes.getControlChar(ControlChar.VINTR)) { @@ -62,7 +82,19 @@ continue; } } - if (c == '\r') { + if (attributes.getInputFlag(Attributes.InputFlag.INORMEOL)) { + if (c == '\r') { + skipNextLf = true; + c = '\n'; + } else if (c == '\n') { + if (skipNextLf) { + skipNextLf = false; + continue; + } + } else { + skipNextLf = false; + } + } else if (c == '\r') { if (attributes.getInputFlag(Attributes.InputFlag.IGNCR)) { continue; } @@ -80,10 +112,10 @@ this.reader = NonBlocking.nonBlocking(getName(), input, encoding()); this.writer = new PrintWriter(new OutputStreamWriter(output, encoding())); this.attributes = new Attributes(); - this.attributes.setControlChar(ControlChar.VERASE, (char) 127); + this.attributes.setControlChar(ControlChar.VERASE, (char) 127); this.attributes.setControlChar(ControlChar.VWERASE, (char) 23); - this.attributes.setControlChar(ControlChar.VKILL, (char) 21); - this.attributes.setControlChar(ControlChar.VLNEXT, (char) 22); + this.attributes.setControlChar(ControlChar.VKILL, (char) 21); + this.attributes.setControlChar(ControlChar.VLNEXT, (char) 22); this.size = new Size(); parseInfoCmp(); } @@ -107,9 +139,7 @@ } public Attributes getAttributes() { - Attributes attr = new Attributes(); - attr.copy(attributes); - return attr; + return new Attributes(attributes); } public void setAttributes(Attributes attr) { @@ -126,4 +156,13 @@ size.copy(sz); } + @Override + public TerminalProvider getProvider() { + return provider; + } + + @Override + public SystemStream getSystemStream() { + return systemStream; + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminalProvider.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminalProvider.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminalProvider.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/DumbTerminalProvider.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2023, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.terminal.impl; + +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.util.function.Function; + +import jdk.internal.org.jline.terminal.Attributes; +import jdk.internal.org.jline.terminal.Size; +import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.terminal.TerminalBuilder; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; + +public class DumbTerminalProvider implements TerminalProvider { + + @Override + public String name() { + return TerminalBuilder.PROP_PROVIDER_DUMB; + } + + @Override + public Terminal sysTerminal( + String name, + String type, + boolean ansiPassThrough, + Charset encoding, + boolean nativeSignals, + Terminal.SignalHandler signalHandler, + boolean paused, + SystemStream systemStream, + Function inputStreamWrapper) + throws IOException { + return new DumbTerminal( + this, + systemStream, + name, + type, + new FileInputStream(FileDescriptor.in), + new FileOutputStream(systemStream == SystemStream.Error ? FileDescriptor.err : FileDescriptor.out), + encoding, + signalHandler, + inputStreamWrapper); + } + + @Override + public Terminal newTerminal( + String name, + String type, + InputStream masterInput, + OutputStream masterOutput, + Charset encoding, + Terminal.SignalHandler signalHandler, + boolean paused, + Attributes attributes, + Size size) + throws IOException { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isSystemStream(SystemStream stream) { + return false; + } + + @Override + public String systemStreamName(SystemStream stream) { + return null; + } + + //@Override + //public int systemStreamWidth(SystemStream stream) { + // return 0; + //} + + @Override + public String toString() { + return "TerminalProvider[" + name() + "]"; + } +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExecPty.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExecPty.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExecPty.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExecPty.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,296 +0,0 @@ -/* - * Copyright (c) 2002-2016, the original author or authors. - * - * This software is distributable under the BSD license. See the terms of the - * BSD license in the documentation provided with this software. - * - * https://opensource.org/licenses/BSD-3-Clause - */ -package jdk.internal.org.jline.terminal.impl; - -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.FileDescriptor; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import jdk.internal.org.jline.terminal.Attributes; -import jdk.internal.org.jline.terminal.Attributes.ControlChar; -import jdk.internal.org.jline.terminal.Attributes.ControlFlag; -import jdk.internal.org.jline.terminal.Attributes.InputFlag; -import jdk.internal.org.jline.terminal.Attributes.LocalFlag; -import jdk.internal.org.jline.terminal.Attributes.OutputFlag; -import jdk.internal.org.jline.terminal.Size; -import jdk.internal.org.jline.terminal.spi.TerminalProvider; -import jdk.internal.org.jline.terminal.spi.Pty; -import jdk.internal.org.jline.utils.OSUtils; - -import static jdk.internal.org.jline.utils.ExecHelper.exec; - -public class ExecPty extends AbstractPty implements Pty { - - private final String name; - private final TerminalProvider.Stream console; - - public static Pty current(TerminalProvider.Stream console) throws IOException { - try { - String result = exec(true, OSUtils.TTY_COMMAND); - if (console != TerminalProvider.Stream.Output && console != TerminalProvider.Stream.Error) { - throw new IllegalArgumentException("console should be Output or Error: " + console); - } - return new ExecPty(result.trim(), console); - } catch (IOException e) { - throw new IOException("Not a tty", e); - } - } - - protected ExecPty(String name, TerminalProvider.Stream console) { - this.name = name; - this.console = console; - } - - @Override - public void close() throws IOException { - } - - public String getName() { - return name; - } - - @Override - public InputStream getMasterInput() { - throw new UnsupportedOperationException(); - } - - @Override - public OutputStream getMasterOutput() { - throw new UnsupportedOperationException(); - } - - @Override - protected InputStream doGetSlaveInput() throws IOException { - return console != null - ? new FileInputStream(FileDescriptor.in) - : new FileInputStream(getName()); - } - - @Override - public OutputStream getSlaveOutput() throws IOException { - return console == TerminalProvider.Stream.Output - ? new FileOutputStream(FileDescriptor.out) - : console == TerminalProvider.Stream.Error - ? new FileOutputStream(FileDescriptor.err) - : new FileOutputStream(getName()); - } - - @Override - public Attributes getAttr() throws IOException { - String cfg = doGetConfig(); - return doGetAttr(cfg); - } - - @Override - protected void doSetAttr(Attributes attr) throws IOException { - List commands = getFlagsToSet(attr, getAttr()); - if (!commands.isEmpty()) { - commands.add(0, OSUtils.STTY_COMMAND); - if (console == null) { - commands.add(1, OSUtils.STTY_F_OPTION); - commands.add(2, getName()); - } - exec(console != null, commands.toArray(new String[0])); - } - } - - protected List getFlagsToSet(Attributes attr, Attributes current) { - List commands = new ArrayList<>(); - for (InputFlag flag : InputFlag.values()) { - if (attr.getInputFlag(flag) != current.getInputFlag(flag)) { - commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); - } - } - for (OutputFlag flag : OutputFlag.values()) { - if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) { - commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); - } - } - for (ControlFlag flag : ControlFlag.values()) { - if (attr.getControlFlag(flag) != current.getControlFlag(flag)) { - commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); - } - } - for (LocalFlag flag : LocalFlag.values()) { - if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) { - commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); - } - } - String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef"; - for (ControlChar cchar : ControlChar.values()) { - int v = attr.getControlChar(cchar); - if (v >= 0 && v != current.getControlChar(cchar)) { - String str = ""; - commands.add(cchar.name().toLowerCase().substring(1)); - if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) { - commands.add(Integer.toString(v)); - } - else if (v == 0) { - commands.add(undef); - } - else { - if (v >= 128) { - v -= 128; - str += "M-"; - } - if (v < 32 || v == 127) { - v ^= 0x40; - str += "^"; - } - str += (char) v; - commands.add(str); - } - } - } - return commands; - } - - @Override - public Size getSize() throws IOException { - String cfg = doGetConfig(); - return doGetSize(cfg); - } - - protected String doGetConfig() throws IOException { - return console != null - ? exec(true, OSUtils.STTY_COMMAND, "-a") - : exec(false, OSUtils.STTY_COMMAND, OSUtils.STTY_F_OPTION, getName(), "-a"); - } - - static Attributes doGetAttr(String cfg) throws IOException { - Attributes attributes = new Attributes(); - for (InputFlag flag : InputFlag.values()) { - Boolean value = doGetFlag(cfg, flag); - if (value != null) { - attributes.setInputFlag(flag, value); - } - } - for (OutputFlag flag : OutputFlag.values()) { - Boolean value = doGetFlag(cfg, flag); - if (value != null) { - attributes.setOutputFlag(flag, value); - } - } - for (ControlFlag flag : ControlFlag.values()) { - Boolean value = doGetFlag(cfg, flag); - if (value != null) { - attributes.setControlFlag(flag, value); - } - } - for (LocalFlag flag : LocalFlag.values()) { - Boolean value = doGetFlag(cfg, flag); - if (value != null) { - attributes.setLocalFlag(flag, value); - } - } - for (ControlChar cchar : ControlChar.values()) { - String name = cchar.name().toLowerCase().substring(1); - if ("reprint".endsWith(name)) { - name = "(?:reprint|rprnt)"; - } - Matcher matcher = Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg); - if (matcher.find()) { - attributes.setControlChar(cchar, parseControlChar(matcher.group(1).toUpperCase())); - } - } - return attributes; - } - - private static Boolean doGetFlag(String cfg, Enum flag) { - Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)").matcher(cfg); - return matcher.find() ? !matcher.group(1).startsWith("-") : null; - } - - static int parseControlChar(String str) { - // undef - if ("".equals(str)) { - return -1; - } - // del - if ("DEL".equalsIgnoreCase(str)) { - return 127; - } - // octal - if (str.charAt(0) == '0') { - return Integer.parseInt(str, 8); - } - // decimal - if (str.charAt(0) >= '1' && str.charAt(0) <= '9') { - return Integer.parseInt(str, 10); - } - // control char - if (str.charAt(0) == '^') { - if (str.charAt(1) == '?') { - return 127; - } else { - return str.charAt(1) - 64; - } - } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') { - if (str.charAt(2) == '^') { - if (str.charAt(3) == '?') { - return 127 + 128; - } else { - return str.charAt(3) - 64 + 128; - } - } else { - return str.charAt(2) + 128; - } - } else { - return str.charAt(0); - } - } - - static Size doGetSize(String cfg) throws IOException { - return new Size(doGetInt("columns", cfg), doGetInt("rows", cfg)); - } - - static int doGetInt(String name, String cfg) throws IOException { - String[] patterns = new String[] { - "\\b([0-9]+)\\s+" + name + "\\b", - "\\b" + name + "\\s+([0-9]+)\\b", - "\\b" + name + "\\s*=\\s*([0-9]+)\\b" - }; - for (String pattern : patterns) { - Matcher matcher = Pattern.compile(pattern).matcher(cfg); - if (matcher.find()) { - return Integer.parseInt(matcher.group(1)); - } - } - throw new IOException("Unable to parse " + name); - } - - @Override - public void setSize(Size size) throws IOException { - if (console != null) { - exec(true, - OSUtils.STTY_COMMAND, - "columns", Integer.toString(size.getColumns()), - "rows", Integer.toString(size.getRows())); - } else { - exec(false, - OSUtils.STTY_COMMAND, - OSUtils.STTY_F_OPTION, getName(), - "columns", Integer.toString(size.getColumns()), - "rows", Integer.toString(size.getRows())); - } - } - - @Override - public String toString() { - return "ExecPty[" + getName() + (console != null ? ", system]" : "]"); - } - -} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExternalTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExternalTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExternalTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/ExternalTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,10 +8,6 @@ */ package jdk.internal.org.jline.terminal.impl; -import jdk.internal.org.jline.terminal.Attributes; -import jdk.internal.org.jline.terminal.Cursor; -import jdk.internal.org.jline.terminal.Size; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -19,6 +15,11 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.IntConsumer; +import jdk.internal.org.jline.terminal.Attributes; +import jdk.internal.org.jline.terminal.Cursor; +import jdk.internal.org.jline.terminal.Size; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; + /** * Console implementation with embedded line disciplined. * @@ -32,45 +33,59 @@ */ public class ExternalTerminal extends LineDisciplineTerminal { + private final TerminalProvider provider; protected final AtomicBoolean closed = new AtomicBoolean(); protected final InputStream masterInput; protected final Object lock = new Object(); protected boolean paused = true; protected Thread pumpThread; - public ExternalTerminal(String name, String type, - InputStream masterInput, - OutputStream masterOutput, - Charset encoding) throws IOException { - this(name, type, masterInput, masterOutput, encoding, SignalHandler.SIG_DFL); - } - - public ExternalTerminal(String name, String type, - InputStream masterInput, - OutputStream masterOutput, - Charset encoding, - SignalHandler signalHandler) throws IOException { - this(name, type, masterInput, masterOutput, encoding, signalHandler, false); - } - - public ExternalTerminal(String name, String type, - InputStream masterInput, - OutputStream masterOutput, - Charset encoding, - SignalHandler signalHandler, - boolean paused) throws IOException { - this(name, type, masterInput, masterOutput, encoding, signalHandler, paused, null, null); - } - - public ExternalTerminal(String name, String type, - InputStream masterInput, - OutputStream masterOutput, - Charset encoding, - SignalHandler signalHandler, - boolean paused, - Attributes attributes, - Size size) throws IOException { + public ExternalTerminal( + String name, String type, InputStream masterInput, OutputStream masterOutput, Charset encoding) + throws IOException { + this(null, name, type, masterInput, masterOutput, encoding, SignalHandler.SIG_DFL); + } + + public ExternalTerminal( + TerminalProvider provider, + String name, + String type, + InputStream masterInput, + OutputStream masterOutput, + Charset encoding, + SignalHandler signalHandler) + throws IOException { + this(provider, name, type, masterInput, masterOutput, encoding, signalHandler, false); + } + + public ExternalTerminal( + TerminalProvider provider, + String name, + String type, + InputStream masterInput, + OutputStream masterOutput, + Charset encoding, + SignalHandler signalHandler, + boolean paused) + throws IOException { + this(provider, name, type, masterInput, masterOutput, encoding, signalHandler, paused, null, null); + } + + @SuppressWarnings("this-escape") + public ExternalTerminal( + TerminalProvider provider, + String name, + String type, + InputStream masterInput, + OutputStream masterOutput, + Charset encoding, + SignalHandler signalHandler, + boolean paused, + Attributes attributes, + Size size) + throws IOException { super(name, type, masterOutput, encoding, signalHandler); + this.provider = provider; this.masterInput = masterInput; if (attributes != null) { setAttributes(attributes); @@ -171,4 +186,8 @@ return CursorSupport.getCursorPosition(this, discarded); } + @Override + public TerminalProvider getProvider() { + return provider; + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/LineDisciplineTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/LineDisciplineTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/LineDisciplineTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/LineDisciplineTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -14,6 +14,7 @@ import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.Charset; +import java.util.EnumSet; import java.util.Objects; import jdk.internal.org.jline.terminal.Attributes; @@ -23,6 +24,8 @@ import jdk.internal.org.jline.terminal.Attributes.OutputFlag; import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.NonBlocking; import jdk.internal.org.jline.utils.NonBlockingPumpInputStream; import jdk.internal.org.jline.utils.NonBlockingReader; @@ -45,21 +48,6 @@ */ public class LineDisciplineTerminal extends AbstractTerminal { - private static final String DEFAULT_TERMINAL_ATTRIBUTES = - "speed 9600 baud; 24 rows; 80 columns;\n" + - "lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl\n" + - "\t-echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo\n" + - "\t-extproc\n" + - "iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8\n" + - "\t-ignbrk brkint -inpck -ignpar -parmrk\n" + - "oflags: opost onlcr -oxtabs -onocr -onlret\n" + - "cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow\n" + - "\t-dtrflow -mdmbuf\n" + - "cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = ;\n" + - "\teol2 = ; erase = ^?; intr = ^C; kill = ^U; lnext = ^V;\n" + - "\tmin = 1; quit = ^\\; reprint = ^R; start = ^Q; status = ^T;\n" + - "\tstop = ^S; susp = ^Z; time = 0; werase = ^W;\n"; - private static final int PIPE_SIZE = 1024; /* @@ -84,20 +72,20 @@ * Console data */ protected final Attributes attributes; + protected final Size size; - public LineDisciplineTerminal(String name, - String type, - OutputStream masterOutput, - Charset encoding) throws IOException { + protected boolean skipNextLf; + + public LineDisciplineTerminal(String name, String type, OutputStream masterOutput, Charset encoding) + throws IOException { this(name, type, masterOutput, encoding, SignalHandler.SIG_DFL); } - public LineDisciplineTerminal(String name, - String type, - OutputStream masterOutput, - Charset encoding, - SignalHandler signalHandler) throws IOException { + @SuppressWarnings("this-escape") + public LineDisciplineTerminal( + String name, String type, OutputStream masterOutput, Charset encoding, SignalHandler signalHandler) + throws IOException { super(name, type, encoding, signalHandler); NonBlockingPumpInputStream input = NonBlocking.nonBlockingPumpInputStream(PIPE_SIZE); this.slaveInputPipe = input.getOutputStream(); @@ -106,11 +94,66 @@ this.slaveOutput = new FilteringOutputStream(); this.slaveWriter = new PrintWriter(new OutputStreamWriter(slaveOutput, encoding())); this.masterOutput = masterOutput; - this.attributes = ExecPty.doGetAttr(DEFAULT_TERMINAL_ATTRIBUTES); + this.attributes = getDefaultTerminalAttributes(); this.size = new Size(160, 50); parseInfoCmp(); } + private static Attributes getDefaultTerminalAttributes() { + // speed 9600 baud; 24 rows; 80 columns; + // lflags: icanon isig iexten echo echoe -echok echoke -echonl echoctl + // -echoprt -altwerase -noflsh -tostop -flusho pendin -nokerninfo + // -extproc + // iflags: -istrip icrnl -inlcr -igncr ixon -ixoff ixany imaxbel iutf8 + // -ignbrk brkint -inpck -ignpar -parmrk + // oflags: opost onlcr -oxtabs -onocr -onlret + // cflags: cread cs8 -parenb -parodd hupcl -clocal -cstopb -crtscts -dsrflow + // -dtrflow -mdmbuf + // cchars: discard = ^O; dsusp = ^Y; eof = ^D; eol = ; + // eol2 = ; erase = ^?; intr = ^C; kill = ^U; lnext = ^V; + // min = 1; quit = ^\\; reprint = ^R; start = ^Q; status = ^T; + // stop = ^S; susp = ^Z; time = 0; werase = ^W; + Attributes attr = new Attributes(); + attr.setLocalFlags(EnumSet.of( + LocalFlag.ICANON, + LocalFlag.ISIG, + LocalFlag.IEXTEN, + LocalFlag.ECHO, + LocalFlag.ECHOE, + LocalFlag.ECHOKE, + LocalFlag.ECHOCTL, + LocalFlag.PENDIN)); + attr.setInputFlags(EnumSet.of( + InputFlag.ICRNL, + InputFlag.IXON, + InputFlag.IXANY, + InputFlag.IMAXBEL, + InputFlag.IUTF8, + InputFlag.BRKINT)); + attr.setOutputFlags(EnumSet.of(OutputFlag.OPOST, OutputFlag.ONLCR)); + attr.setControlChar(ControlChar.VDISCARD, ctrl('O')); + attr.setControlChar(ControlChar.VDSUSP, ctrl('Y')); + attr.setControlChar(ControlChar.VEOF, ctrl('D')); + attr.setControlChar(ControlChar.VERASE, ctrl('?')); + attr.setControlChar(ControlChar.VINTR, ctrl('C')); + attr.setControlChar(ControlChar.VKILL, ctrl('U')); + attr.setControlChar(ControlChar.VLNEXT, ctrl('V')); + attr.setControlChar(ControlChar.VMIN, 1); + attr.setControlChar(ControlChar.VQUIT, ctrl('\\')); + attr.setControlChar(ControlChar.VREPRINT, ctrl('R')); + attr.setControlChar(ControlChar.VSTART, ctrl('Q')); + attr.setControlChar(ControlChar.VSTATUS, ctrl('T')); + attr.setControlChar(ControlChar.VSTOP, ctrl('S')); + attr.setControlChar(ControlChar.VSUSP, ctrl('Z')); + attr.setControlChar(ControlChar.VTIME, 0); + attr.setControlChar(ControlChar.VWERASE, ctrl('W')); + return attr; + } + + private static int ctrl(char c) { + return c == '?' ? 177 : c - 64; + } + public NonBlockingReader reader() { return slaveReader; } @@ -130,9 +173,7 @@ } public Attributes getAttributes() { - Attributes attr = new Attributes(); - attr.copy(attributes); - return attr; + return new Attributes(attributes); } public void setAttributes(Attributes attr) { @@ -149,9 +190,9 @@ size.copy(sz); } - @Override + @Override public void raise(Signal signal) { - Objects.requireNonNull(signal); + Objects.requireNonNull(signal); // Do not call clear() atm as this can cause // deadlock between reading / writing threads // TODO: any way to fix that ? @@ -214,7 +255,19 @@ raise(Signal.INFO); } } - if (c == '\r') { + if (attributes.getInputFlag(InputFlag.INORMEOL)) { + if (c == '\r') { + skipNextLf = true; + c = '\n'; + } else if (c == '\n') { + if (skipNextLf) { + skipNextLf = false; + return false; + } + } else { + skipNextLf = false; + } + } else if (c == '\r') { if (attributes.getInputFlag(InputFlag.IGNCR)) { return false; } @@ -273,6 +326,16 @@ } } + @Override + public TerminalProvider getProvider() { + return null; + } + + @Override + public SystemStream getSystemStream() { + return null; + } + private class FilteringOutputStream extends OutputStream { @Override public void write(int b) throws IOException { @@ -284,13 +347,12 @@ public void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); - } else if ((off < 0) || (off > b.length) || (len < 0) || - ((off + len) > b.length) || ((off + len) < 0)) { + } else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } - for (int i = 0 ; i < len ; i++) { + for (int i = 0; i < len; i++) { processOutputByte(b[off + i]); } flush(); diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/MouseSupport.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/MouseSupport.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/MouseSupport.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/MouseSupport.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,11 +8,6 @@ */ package jdk.internal.org.jline.terminal.impl; -import jdk.internal.org.jline.terminal.MouseEvent; -import jdk.internal.org.jline.terminal.Terminal; -import jdk.internal.org.jline.utils.InfoCmp; -import jdk.internal.org.jline.utils.InputStreamReader; - import java.io.EOFException; import java.io.IOError; import java.io.IOException; @@ -20,6 +15,11 @@ import java.util.EnumSet; import java.util.function.IntSupplier; +import jdk.internal.org.jline.terminal.MouseEvent; +import jdk.internal.org.jline.terminal.Terminal; +import jdk.internal.org.jline.utils.InfoCmp; +import jdk.internal.org.jline.utils.InputStreamReader; + public class MouseSupport { public static boolean hasMouseSupport(Terminal terminal) { @@ -78,7 +78,8 @@ case 0: button = MouseEvent.Button.Button1; if (last.getButton() == button - && (last.getType() == MouseEvent.Type.Pressed || last.getType() == MouseEvent.Type.Dragged)) { + && (last.getType() == MouseEvent.Type.Pressed + || last.getType() == MouseEvent.Type.Dragged)) { type = MouseEvent.Type.Dragged; } else { type = MouseEvent.Type.Pressed; @@ -87,7 +88,8 @@ case 1: button = MouseEvent.Button.Button2; if (last.getButton() == button - && (last.getType() == MouseEvent.Type.Pressed || last.getType() == MouseEvent.Type.Dragged)) { + && (last.getType() == MouseEvent.Type.Pressed + || last.getType() == MouseEvent.Type.Dragged)) { type = MouseEvent.Type.Dragged; } else { type = MouseEvent.Type.Pressed; @@ -96,7 +98,8 @@ case 2: button = MouseEvent.Button.Button3; if (last.getButton() == button - && (last.getType() == MouseEvent.Type.Pressed || last.getType() == MouseEvent.Type.Dragged)) { + && (last.getType() == MouseEvent.Type.Pressed + || last.getType() == MouseEvent.Type.Dragged)) { type = MouseEvent.Type.Dragged; } else { type = MouseEvent.Type.Pressed; @@ -134,5 +137,4 @@ throw new IOError(e); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/NativeSignalHandler.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/NativeSignalHandler.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/NativeSignalHandler.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/NativeSignalHandler.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -17,8 +17,7 @@ public static final NativeSignalHandler SIG_IGN = new NativeSignalHandler(); - private NativeSignalHandler() { - } + private NativeSignalHandler() {} public void handle(Signal signal) { throw new UnsupportedOperationException(); diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixPtyTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixPtyTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixPtyTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixPtyTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -38,15 +38,34 @@ private Thread outputPumpThread; private boolean paused = true; - public PosixPtyTerminal(String name, String type, Pty pty, InputStream in, OutputStream out, Charset encoding) throws IOException { + public PosixPtyTerminal(String name, String type, Pty pty, InputStream in, OutputStream out, Charset encoding) + throws IOException { this(name, type, pty, in, out, encoding, SignalHandler.SIG_DFL); } - public PosixPtyTerminal(String name, String type, Pty pty, InputStream in, OutputStream out, Charset encoding, SignalHandler signalHandler) throws IOException { + public PosixPtyTerminal( + String name, + String type, + Pty pty, + InputStream in, + OutputStream out, + Charset encoding, + SignalHandler signalHandler) + throws IOException { this(name, type, pty, in, out, encoding, signalHandler, false); } - public PosixPtyTerminal(String name, String type, Pty pty, InputStream in, OutputStream out, Charset encoding, SignalHandler signalHandler, boolean paused) throws IOException { + @SuppressWarnings("this-escape") + public PosixPtyTerminal( + String name, + String type, + Pty pty, + InputStream in, + OutputStream out, + Charset encoding, + SignalHandler signalHandler, + boolean paused) + throws IOException { super(name, type, pty, encoding, signalHandler); this.in = Objects.requireNonNull(in); this.out = Objects.requireNonNull(out); @@ -113,7 +132,7 @@ if (p1 != null) { p1.join(); } - if (p2 !=null) { + if (p2 != null) { p2.join(); } } @@ -167,7 +186,7 @@ private void pumpIn() { try { - for (;;) { + for (; ; ) { synchronized (lock) { if (paused) { inputPumpThread = null; @@ -193,7 +212,7 @@ private void pumpOut() { try { - for (;;) { + for (; ; ) { synchronized (lock) { if (paused) { outputPumpThread = null; @@ -221,5 +240,4 @@ // Ignore } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixSysTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixSysTerminal.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixSysTerminal.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/PosixSysTerminal.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -18,8 +18,9 @@ import java.util.Map; import java.util.function.Function; -import jdk.internal.org.jline.utils.NonBlocking; import jdk.internal.org.jline.terminal.spi.Pty; +import jdk.internal.org.jline.utils.FastBufferedOutputStream; +import jdk.internal.org.jline.utils.NonBlocking; import jdk.internal.org.jline.utils.NonBlockingInputStream; import jdk.internal.org.jline.utils.NonBlockingReader; import jdk.internal.org.jline.utils.ShutdownHooks; @@ -35,12 +36,14 @@ protected final Map nativeHandlers = new HashMap<>(); protected final Task closer; - public PosixSysTerminal(String name, String type, Pty pty, Charset encoding, - boolean nativeSignals, SignalHandler signalHandler, - Function inputStreamWrapper) throws IOException { + @SuppressWarnings("this-escape") + public PosixSysTerminal( + String name, String type, Pty pty, Charset encoding, boolean nativeSignals, SignalHandler signalHandler, + Function inputStreamWrapper) + throws IOException { super(name, type, pty, encoding, signalHandler); this.input = NonBlocking.nonBlocking(getName(), inputStreamWrapper.apply(pty.getSlaveInput())); - this.output = pty.getSlaveOutput(); + this.output = new FastBufferedOutputStream(pty.getSlaveOutput()); this.reader = NonBlocking.nonBlocking(getName(), input, encoding()); this.writer = new PrintWriter(new OutputStreamWriter(output, encoding())); parseInfoCmp(); @@ -98,5 +101,4 @@ // Do not call reader.close() reader.shutdown(); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecPty.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecPty.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecPty.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecPty.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2002-2016, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.terminal.impl.exec; + +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import jdk.internal.org.jline.terminal.Attributes; +import jdk.internal.org.jline.terminal.Attributes.ControlChar; +import jdk.internal.org.jline.terminal.Attributes.ControlFlag; +import jdk.internal.org.jline.terminal.Attributes.InputFlag; +import jdk.internal.org.jline.terminal.Attributes.LocalFlag; +import jdk.internal.org.jline.terminal.Attributes.OutputFlag; +import jdk.internal.org.jline.terminal.Size; +import jdk.internal.org.jline.terminal.impl.AbstractPty; +import jdk.internal.org.jline.terminal.spi.Pty; +import jdk.internal.org.jline.terminal.spi.SystemStream; +import jdk.internal.org.jline.terminal.spi.TerminalProvider; +import jdk.internal.org.jline.utils.OSUtils; + +import static jdk.internal.org.jline.utils.ExecHelper.exec; + +public class ExecPty extends AbstractPty implements Pty { + + private final String name; + + public static Pty current(TerminalProvider provider, SystemStream systemStream) throws IOException { + try { + String result = exec(true, OSUtils.TTY_COMMAND); + if (systemStream != SystemStream.Output && systemStream != SystemStream.Error) { + throw new IllegalArgumentException("systemStream should be Output or Error: " + systemStream); + } + return new ExecPty(provider, systemStream, result.trim()); + } catch (IOException e) { + throw new IOException("Not a tty", e); + } + } + + protected ExecPty(TerminalProvider provider, SystemStream systemStream, String name) { + super(provider, systemStream); + this.name = name; + } + + @Override + public void close() throws IOException {} + + public String getName() { + return name; + } + + @Override + public InputStream getMasterInput() { + throw new UnsupportedOperationException(); + } + + @Override + public OutputStream getMasterOutput() { + throw new UnsupportedOperationException(); + } + + @Override + protected InputStream doGetSlaveInput() throws IOException { + return systemStream != null ? new FileInputStream(FileDescriptor.in) : new FileInputStream(getName()); + } + + @Override + public OutputStream getSlaveOutput() throws IOException { + return systemStream == SystemStream.Output + ? new FileOutputStream(FileDescriptor.out) + : systemStream == SystemStream.Error + ? new FileOutputStream(FileDescriptor.err) + : new FileOutputStream(getName()); + } + + @Override + public Attributes getAttr() throws IOException { + String cfg = doGetConfig(); + return doGetAttr(cfg); + } + + @Override + protected void doSetAttr(Attributes attr) throws IOException { + List commands = getFlagsToSet(attr, getAttr()); + if (!commands.isEmpty()) { + commands.add(0, OSUtils.STTY_COMMAND); + if (systemStream == null) { + commands.add(1, OSUtils.STTY_F_OPTION); + commands.add(2, getName()); + } + try { + exec(systemStream != null, commands.toArray(new String[0])); + } catch (IOException e) { + // Handle partial failures with GNU stty, see #97 + if (e.toString().contains("unable to perform all requested operations")) { + commands = getFlagsToSet(attr, getAttr()); + if (!commands.isEmpty()) { + throw new IOException("Could not set the following flags: " + String.join(", ", commands), e); + } + } else { + throw e; + } + } + } + } + + protected List getFlagsToSet(Attributes attr, Attributes current) { + List commands = new ArrayList<>(); + for (InputFlag flag : InputFlag.values()) { + if (attr.getInputFlag(flag) != current.getInputFlag(flag) && flag != InputFlag.INORMEOL) { + commands.add((attr.getInputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (OutputFlag flag : OutputFlag.values()) { + if (attr.getOutputFlag(flag) != current.getOutputFlag(flag)) { + commands.add((attr.getOutputFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (ControlFlag flag : ControlFlag.values()) { + if (attr.getControlFlag(flag) != current.getControlFlag(flag)) { + commands.add((attr.getControlFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + for (LocalFlag flag : LocalFlag.values()) { + if (attr.getLocalFlag(flag) != current.getLocalFlag(flag)) { + commands.add((attr.getLocalFlag(flag) ? flag.name() : "-" + flag.name()).toLowerCase()); + } + } + String undef = System.getProperty("os.name").toLowerCase().startsWith("hp") ? "^-" : "undef"; + for (ControlChar cchar : ControlChar.values()) { + int v = attr.getControlChar(cchar); + if (v >= 0 && v != current.getControlChar(cchar)) { + String str = ""; + commands.add(cchar.name().toLowerCase().substring(1)); + if (cchar == ControlChar.VMIN || cchar == ControlChar.VTIME) { + commands.add(Integer.toString(v)); + } else if (v == 0) { + commands.add(undef); + } else { + if (v >= 128) { + v -= 128; + str += "M-"; + } + if (v < 32 || v == 127) { + v ^= 0x40; + str += "^"; + } + str += (char) v; + commands.add(str); + } + } + } + return commands; + } + + @Override + public Size getSize() throws IOException { + String cfg = doGetConfig(); + return doGetSize(cfg); + } + + protected String doGetConfig() throws IOException { + return systemStream != null + ? exec(true, OSUtils.STTY_COMMAND, "-a") + : exec(false, OSUtils.STTY_COMMAND, OSUtils.STTY_F_OPTION, getName(), "-a"); + } + + public static Attributes doGetAttr(String cfg) throws IOException { + Attributes attributes = new Attributes(); + for (InputFlag flag : InputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setInputFlag(flag, value); + } + } + for (OutputFlag flag : OutputFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setOutputFlag(flag, value); + } + } + for (ControlFlag flag : ControlFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setControlFlag(flag, value); + } + } + for (LocalFlag flag : LocalFlag.values()) { + Boolean value = doGetFlag(cfg, flag); + if (value != null) { + attributes.setLocalFlag(flag, value); + } + } + for (ControlChar cchar : ControlChar.values()) { + String name = cchar.name().toLowerCase().substring(1); + if ("reprint".endsWith(name)) { + name = "(?:reprint|rprnt)"; + } + Matcher matcher = + Pattern.compile("[\\s;]" + name + "\\s*=\\s*(.+?)[\\s;]").matcher(cfg); + if (matcher.find()) { + attributes.setControlChar( + cchar, parseControlChar(matcher.group(1).toUpperCase())); + } + } + return attributes; + } + + private static Boolean doGetFlag(String cfg, Enum flag) { + Matcher matcher = Pattern.compile("(?:^|[\\s;])(\\-?" + flag.name().toLowerCase() + ")(?:[\\s;]|$)") + .matcher(cfg); + return matcher.find() ? !matcher.group(1).startsWith("-") : null; + } + + static int parseControlChar(String str) { + // undef + if ("".equals(str)) { + return -1; + } + // del + if ("DEL".equalsIgnoreCase(str)) { + return 127; + } + // octal + if (str.charAt(0) == '0') { + return Integer.parseInt(str, 8); + } + // decimal + if (str.charAt(0) >= '1' && str.charAt(0) <= '9') { + return Integer.parseInt(str, 10); + } + // control char + if (str.charAt(0) == '^') { + if (str.charAt(1) == '?') { + return 127; + } else { + return str.charAt(1) - 64; + } + } else if (str.charAt(0) == 'M' && str.charAt(1) == '-') { + if (str.charAt(2) == '^') { + if (str.charAt(3) == '?') { + return 127 + 128; + } else { + return str.charAt(3) - 64 + 128; + } + } else { + return str.charAt(2) + 128; + } + } else { + return str.charAt(0); + } + } + + static Size doGetSize(String cfg) throws IOException { + return new Size(doGetInt("columns", cfg), doGetInt("rows", cfg)); + } + + static int doGetInt(String name, String cfg) throws IOException { + String[] patterns = new String[] { + "\\b([0-9]+)\\s+" + name + "\\b", "\\b" + name + "\\s+([0-9]+)\\b", "\\b" + name + "\\s*=\\s*([0-9]+)\\b" + }; + for (String pattern : patterns) { + Matcher matcher = Pattern.compile(pattern).matcher(cfg); + if (matcher.find()) { + return Integer.parseInt(matcher.group(1)); + } + } + throw new IOException("Unable to parse " + name); + } + + @Override + public void setSize(Size size) throws IOException { + if (systemStream != null) { + exec( + true, + OSUtils.STTY_COMMAND, + "columns", + Integer.toString(size.getColumns()), + "rows", + Integer.toString(size.getRows())); + } else { + exec( + false, + OSUtils.STTY_COMMAND, + OSUtils.STTY_F_OPTION, + getName(), + "columns", + Integer.toString(size.getColumns()), + "rows", + Integer.toString(size.getRows())); + } + } + + @Override + public String toString() { + return "ExecPty[" + getName() + (systemStream != null ? ", system]" : "]"); + } +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecTerminalProvider.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecTerminalProvider.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecTerminalProvider.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/impl/exec/ExecTerminalProvider.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, the original author or authors. + * Copyright (c) 2022, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -17,117 +17,249 @@ import java.nio.charset.Charset; import java.util.function.Function; +//import jdk.internal.org.jline.nativ.JLineLibrary; +//import jdk.internal.org.jline.nativ.JLineNativeLoader; import jdk.internal.org.jline.terminal.Attributes; import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.Terminal; -import jdk.internal.org.jline.terminal.impl.ExecPty; +import jdk.internal.org.jline.terminal.TerminalBuilder; import jdk.internal.org.jline.terminal.impl.ExternalTerminal; import jdk.internal.org.jline.terminal.impl.PosixSysTerminal; import jdk.internal.org.jline.terminal.spi.Pty; +import jdk.internal.org.jline.terminal.spi.SystemStream; import jdk.internal.org.jline.terminal.spi.TerminalProvider; import jdk.internal.org.jline.utils.ExecHelper; +import jdk.internal.org.jline.utils.Log; import jdk.internal.org.jline.utils.OSUtils; -public class ExecTerminalProvider implements TerminalProvider -{ +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_REDIRECT_PIPE_CREATION_MODE; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_REDIRECT_PIPE_CREATION_MODE_DEFAULT; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_REDIRECT_PIPE_CREATION_MODE_NATIVE; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_REDIRECT_PIPE_CREATION_MODE_REFLECTION; + +public class ExecTerminalProvider implements TerminalProvider { + + private static boolean warned; public String name() { - return "exec"; + return TerminalBuilder.PROP_PROVIDER_EXEC; } - public Pty current(Stream consoleStream) throws IOException { - return ExecPty.current(consoleStream); + public Pty current(SystemStream systemStream) throws IOException { + return ExecPty.current(this, systemStream); } @Override - public Terminal sysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding, - boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused, - Stream consoleStream, Function inputStreamWrapper) throws IOException { + public Terminal sysTerminal( + String name, + String type, + boolean ansiPassThrough, + Charset encoding, + boolean nativeSignals, + Terminal.SignalHandler signalHandler, + boolean paused, + SystemStream systemStream, + Function inputStreamWrapper) + throws IOException { if (OSUtils.IS_WINDOWS) { - return winSysTerminal(name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, consoleStream, inputStreamWrapper ); + return winSysTerminal( + name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, systemStream, inputStreamWrapper); } else { - return posixSysTerminal(name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, consoleStream, inputStreamWrapper ); + return posixSysTerminal( + name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, systemStream, inputStreamWrapper); } } - public Terminal winSysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding, - boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused, - Stream consoleStream, Function inputStreamWrapper ) throws IOException { + public Terminal winSysTerminal( + String name, + String type, + boolean ansiPassThrough, + Charset encoding, + boolean nativeSignals, + Terminal.SignalHandler signalHandler, + boolean paused, + SystemStream systemStream, + Function inputStreamWrapper) + throws IOException { if (OSUtils.IS_CYGWIN || OSUtils.IS_MSYSTEM) { - Pty pty = current(consoleStream); + Pty pty = current(systemStream); return new PosixSysTerminal(name, type, pty, encoding, nativeSignals, signalHandler, inputStreamWrapper); } else { return null; } } - public Terminal posixSysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding, - boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused, - Stream consoleStream, Function inputStreamWrapper) throws IOException { - Pty pty = current(consoleStream); + public Terminal posixSysTerminal( + String name, + String type, + boolean ansiPassThrough, + Charset encoding, + boolean nativeSignals, + Terminal.SignalHandler signalHandler, + boolean paused, + SystemStream systemStream, + Function inputStreamWrapper) + throws IOException { + Pty pty = current(systemStream); return new PosixSysTerminal(name, type, pty, encoding, nativeSignals, signalHandler, inputStreamWrapper); } @Override - public Terminal newTerminal(String name, String type, InputStream in, OutputStream out, - Charset encoding, Terminal.SignalHandler signalHandler, boolean paused, - Attributes attributes, Size size) throws IOException - { - return new ExternalTerminal(name, type, in, out, encoding, signalHandler, paused, attributes, size); + public Terminal newTerminal( + String name, + String type, + InputStream in, + OutputStream out, + Charset encoding, + Terminal.SignalHandler signalHandler, + boolean paused, + Attributes attributes, + Size size) + throws IOException { + return new ExternalTerminal(this, name, type, in, out, encoding, signalHandler, paused, attributes, size); } @Override - public boolean isSystemStream(Stream stream) { + public boolean isSystemStream(SystemStream stream) { try { - return isWindowsSystemStream(stream) || isPosixSystemStream(stream); + return isPosixSystemStream(stream) || isWindowsSystemStream(stream); } catch (Throwable t) { return false; } } - public boolean isWindowsSystemStream(Stream stream) { - return systemStreamName( stream ) != null; + public boolean isWindowsSystemStream(SystemStream stream) { + return systemStreamName(stream) != null; } - public boolean isPosixSystemStream(Stream stream) { + public boolean isPosixSystemStream(SystemStream stream) { try { Process p = new ProcessBuilder(OSUtils.TEST_COMMAND, "-t", Integer.toString(stream.ordinal())) - .inheritIO().start(); + .inheritIO() + .start(); return p.waitFor() == 0; } catch (Throwable t) { + Log.debug("ExecTerminalProvider failed 'test -t' for " + stream, t); // ignore } return false; } @Override - public String systemStreamName(Stream stream) { + public String systemStreamName(SystemStream stream) { try { - ProcessBuilder.Redirect input = stream == Stream.Input - ? ProcessBuilder.Redirect.INHERIT - : getRedirect(stream == Stream.Output ? FileDescriptor.out : FileDescriptor.err); - Process p = new ProcessBuilder(OSUtils.TTY_COMMAND).redirectInput(input).start(); + ProcessBuilder.Redirect input = stream == SystemStream.Input + ? ProcessBuilder.Redirect.INHERIT + : newDescriptor(stream == SystemStream.Output ? FileDescriptor.out : FileDescriptor.err); + Process p = + new ProcessBuilder(OSUtils.TTY_COMMAND).redirectInput(input).start(); String result = ExecHelper.waitAndCapture(p); if (p.exitValue() == 0) { return result.trim(); } } catch (Throwable t) { + if ("java.lang.reflect.InaccessibleObjectException" + .equals(t.getClass().getName()) + && !warned) { + Log.warn( + "The ExecTerminalProvider requires the JVM options: '--add-opens java.base/java.lang=ALL-UNNAMED'"); + warned = true; + } // ignore } return null; } - private ProcessBuilder.Redirect getRedirect(FileDescriptor fd) throws ReflectiveOperationException { - // This is not really allowed, but this is the only way to redirect the output or error stream - // to the input. This is definitely not something you'd usually want to do, but in the case of - // the `tty` utility, it provides a way to get - Class rpi = Class.forName("java.lang.ProcessBuilder$RedirectPipeImpl"); - Constructor cns = rpi.getDeclaredConstructor(); - cns.setAccessible(true); - ProcessBuilder.Redirect input = (ProcessBuilder.Redirect) cns.newInstance(); - Field f = rpi.getDeclaredField("fd"); - f.setAccessible(true); - f.set(input, fd); - return input; +// @Override +// public int systemStreamWidth(SystemStream stream) { +// try (ExecPty pty = new ExecPty(this, stream, null)) { +// return pty.getSize().getColumns(); +// } catch (Throwable t) { +// return -1; +// } +// } + + private static RedirectPipeCreator redirectPipeCreator; + + protected static ProcessBuilder.Redirect newDescriptor(FileDescriptor fd) { + if (redirectPipeCreator == null) { + String str = System.getProperty(PROP_REDIRECT_PIPE_CREATION_MODE, PROP_REDIRECT_PIPE_CREATION_MODE_DEFAULT); + String[] modes = str.split(","); + IllegalStateException ise = new IllegalStateException("Unable to create RedirectPipe"); + for (String mode : modes) { + try { + switch (mode) { + case PROP_REDIRECT_PIPE_CREATION_MODE_NATIVE: + redirectPipeCreator = null;//new NativeRedirectPipeCreator(); + break; + case PROP_REDIRECT_PIPE_CREATION_MODE_REFLECTION: + redirectPipeCreator = new ReflectionRedirectPipeCreator(); + break; + } + } catch (Throwable t) { + // ignore + ise.addSuppressed(t); + } + if (redirectPipeCreator != null) { + break; + } + } + if (redirectPipeCreator == null) { + throw ise; + } + } + return redirectPipeCreator.newRedirectPipe(fd); + } + + interface RedirectPipeCreator { + ProcessBuilder.Redirect newRedirectPipe(FileDescriptor fd); + } + + /** + * Reflection based file descriptor creator. + * This requires the following option + * --add-opens java.base/java.lang=ALL-UNNAMED + */ + static class ReflectionRedirectPipeCreator implements RedirectPipeCreator { + private final Constructor constructor; + private final Field fdField; + + @SuppressWarnings("unchecked") + ReflectionRedirectPipeCreator() throws Exception { + Class rpi = Class.forName("java.lang.ProcessBuilder$RedirectPipeImpl"); + constructor = (Constructor) rpi.getDeclaredConstructor(); + constructor.setAccessible(true); + fdField = rpi.getDeclaredField("fd"); + fdField.setAccessible(true); + } + + @Override + public ProcessBuilder.Redirect newRedirectPipe(FileDescriptor fd) { + try { + ProcessBuilder.Redirect input = constructor.newInstance(); + fdField.set(input, fd); + return input; + } catch (ReflectiveOperationException e) { + // This should not happen as the field has been set accessible + throw new IllegalStateException(e); + } + } + } + +// static class NativeRedirectPipeCreator implements RedirectPipeCreator { +// public NativeRedirectPipeCreator() { +// // Force load the library +// JLineNativeLoader.initialize(); +// } +// +// @Override +// public ProcessBuilder.Redirect newRedirectPipe(FileDescriptor fd) { +// return JLineLibrary.newRedirectPipe(fd); +// } +// } + + @Override + public String toString() { + return "TerminalProvider[" + name() + "]"; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/Pty.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/Pty.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/Pty.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/Pty.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -34,4 +34,7 @@ void setSize(Size size) throws IOException; + SystemStream getSystemStream(); + + TerminalProvider getProvider(); } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/SystemStream.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/SystemStream.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/SystemStream.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/SystemStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2023, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.terminal.spi; + +public enum SystemStream { + Input, + Output, + Error +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalExt.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalExt.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalExt.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalExt.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.terminal.spi; + +import jdk.internal.org.jline.terminal.Terminal; + +/** + * The {@code TerminalExt} interface is implemented by {@code Terminal}s + * and provides access to the Terminal's internals. + */ +public interface TerminalExt extends Terminal { + + /** + * Returns the {@code TerminalProvider} that created this terminal + * or {@code null} if the terminal was created with no provider. + */ + TerminalProvider getProvider(); + + /** + * The underlying system stream, may be {@link SystemStream#Output}, + * {@link SystemStream#Error}, or {@code null} if this terminal is not bound + * to a system stream. + */ + SystemStream getSystemStream(); +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalProvider.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalProvider.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalProvider.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/terminal/spi/TerminalProvider.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, the original author or authors. + * Copyright (c) 2022, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -11,10 +11,8 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.net.URL; import java.nio.charset.Charset; import java.util.Properties; -import java.util.ServiceLoader; import java.util.function.Function; import jdk.internal.org.jline.terminal.Attributes; @@ -22,30 +20,39 @@ import jdk.internal.org.jline.terminal.Terminal; import jdk.internal.org.jline.terminal.impl.exec.ExecTerminalProvider; -public interface TerminalProvider -{ - - enum Stream { - Input, - Output, - Error - } +public interface TerminalProvider { String name(); - Terminal sysTerminal(String name, String type, boolean ansiPassThrough, - Charset encoding, boolean nativeSignals, - Terminal.SignalHandler signalHandler, boolean paused, - Stream consoleStream, Function inputStreamWrapper) throws IOException; - - Terminal newTerminal(String name, String type, - InputStream masterInput, OutputStream masterOutput, - Charset encoding, Terminal.SignalHandler signalHandler, - boolean paused, Attributes attributes, Size size) throws IOException; + Terminal sysTerminal( + String name, + String type, + boolean ansiPassThrough, + Charset encoding, + boolean nativeSignals, + Terminal.SignalHandler signalHandler, + boolean paused, + SystemStream systemStream, + Function inputStreamWrapper) + throws IOException; + + Terminal newTerminal( + String name, + String type, + InputStream masterInput, + OutputStream masterOutput, + Charset encoding, + Terminal.SignalHandler signalHandler, + boolean paused, + Attributes attributes, + Size size) + throws IOException; - boolean isSystemStream(Stream stream); + boolean isSystemStream(SystemStream stream); - String systemStreamName(Stream stream); + String systemStreamName(SystemStream stream); + + //int systemStreamWidth(SystemStream stream); static TerminalProvider load(String name) throws IOException { switch (name) { @@ -62,7 +69,7 @@ if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } - InputStream is = cl.getResourceAsStream( "META-INF/services/org/jline/terminal/provider/" + name); + InputStream is = cl.getResourceAsStream("META-INF/services/org/jline/terminal/provider/" + name); if (is != null) { Properties props = new Properties(); try { @@ -71,14 +78,13 @@ if (className == null) { throw new IOException("No class defined in terminal provider file " + name); } - Class clazz = cl.loadClass( className ); + Class clazz = cl.loadClass(className); return (TerminalProvider) clazz.getConstructor().newInstance(); - } catch ( Exception e ) { - throw new IOException("Unable to load terminal provider " + name, e); + } catch (Exception e) { + throw new IOException("Unable to load terminal provider " + name + ": " + e.getMessage(), e); } } else { throw new IOException("Unable to find terminal provider " + name); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AnsiWriter.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AnsiWriter.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AnsiWriter.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AnsiWriter.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,17 +1,10 @@ /* - * Copyright (C) 2009-2018 the original author(s). + * Copyright (c) 2009-2018, the original author(s). * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * https://opensource.org/licenses/BSD-3-Clause */ package jdk.internal.org.jline.utils; @@ -252,12 +245,10 @@ * @throws IOException if no more non-null values left */ private int getNextOptionInt(Iterator optionsIterator) throws IOException { - for (;;) { - if (!optionsIterator.hasNext()) - throw new IllegalArgumentException(); + for (; ; ) { + if (!optionsIterator.hasNext()) throw new IllegalArgumentException(); Object arg = optionsIterator.next(); - if (arg != null) - return (Integer) arg; + if (arg != null) return (Integer) arg; } } @@ -346,27 +337,21 @@ int g = getNextOptionInt(optionsIterator); int b = getNextOptionInt(optionsIterator); if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) { - if (value == 38) - processSetForegroundColorExt(r, g, b); - else - processSetBackgroundColorExt(r, g, b); + if (value == 38) processSetForegroundColorExt(r, g, b); + else processSetBackgroundColorExt(r, g, b); } else { throw new IllegalArgumentException(); } - } - else if (arg2or5 == 5) { + } else if (arg2or5 == 5) { // 256 color style like `esc[38;5;m` int paletteIndex = getNextOptionInt(optionsIterator); if (paletteIndex >= 0 && paletteIndex <= 255) { - if (value == 38) - processSetForegroundColorExt(paletteIndex); - else - processSetBackgroundColorExt(paletteIndex); + if (value == 38) processSetForegroundColorExt(paletteIndex); + else processSetBackgroundColorExt(paletteIndex); } else { throw new IllegalArgumentException(); } - } - else { + } else { throw new IllegalArgumentException(); } } else { @@ -449,47 +434,41 @@ * Process CSI u ANSI code, corresponding to RCP \u2013 Restore Cursor Position * @throws IOException if an error occurs */ - protected void processRestoreCursorPosition() throws IOException { - } + protected void processRestoreCursorPosition() throws IOException {} /** * Process CSI s ANSI code, corresponding to SCP \u2013 Save Cursor Position * @throws IOException if an error occurs */ - protected void processSaveCursorPosition() throws IOException { - } + protected void processSaveCursorPosition() throws IOException {} /** * Process CSI s ANSI code, corresponding to IL \u2013 Insert Line * @param optionInt the option * @throws IOException if an error occurs */ - protected void processInsertLine(int optionInt) throws IOException { - } + protected void processInsertLine(int optionInt) throws IOException {} /** * Process CSI s ANSI code, corresponding to DL \u2013 Delete Line * @param optionInt the option * @throws IOException if an error occurs */ - protected void processDeleteLine(int optionInt) throws IOException { - } + protected void processDeleteLine(int optionInt) throws IOException {} /** * Process CSI n T ANSI code, corresponding to SD \u2013 Scroll Down * @param optionInt the option * @throws IOException if an error occurs */ - protected void processScrollDown(int optionInt) throws IOException { - } + protected void processScrollDown(int optionInt) throws IOException {} /** * Process CSI n U ANSI code, corresponding to SU \u2013 Scroll Up * @param optionInt the option * @throws IOException if an error occurs */ - protected void processScrollUp(int optionInt) throws IOException { - } + protected void processScrollUp(int optionInt) throws IOException {} protected static final int ERASE_SCREEN_TO_END = 0; protected static final int ERASE_SCREEN_TO_BEGINING = 1; @@ -500,8 +479,7 @@ * @param eraseOption the erase option * @throws IOException if an error occurs */ - protected void processEraseScreen(int eraseOption) throws IOException { - } + protected void processEraseScreen(int eraseOption) throws IOException {} protected static final int ERASE_LINE_TO_END = 0; protected static final int ERASE_LINE_TO_BEGINING = 1; @@ -512,25 +490,27 @@ * @param eraseOption the erase option * @throws IOException if an error occurs */ - protected void processEraseLine(int eraseOption) throws IOException { - } + protected void processEraseLine(int eraseOption) throws IOException {} + + protected static final int ATTRIBUTE_INTENSITY_BOLD = 1; // Intensity: Bold + protected static final int ATTRIBUTE_INTENSITY_FAINT = 2; // Intensity; Faint not widely supported + protected static final int ATTRIBUTE_ITALIC = 3; // Italic; on not widely supported. Sometimes treated as inverse. + protected static final int ATTRIBUTE_UNDERLINE = 4; // Underline; Single + protected static final int ATTRIBUTE_BLINK_SLOW = 5; // Blink; Slow less than 150 per minute + protected static final int ATTRIBUTE_BLINK_FAST = 6; // Blink; Rapid MS-DOS ANSI.SYS; 150 per minute or more + protected static final int ATTRIBUTE_NEGATIVE_ON = + 7; // Image; Negative inverse or reverse; swap foreground and background + protected static final int ATTRIBUTE_CONCEAL_ON = 8; // Conceal on + protected static final int ATTRIBUTE_UNDERLINE_DOUBLE = 21; // Underline; Double not widely supported + protected static final int ATTRIBUTE_INTENSITY_NORMAL = 22; // Intensity; Normal not bold and not faint + protected static final int ATTRIBUTE_UNDERLINE_OFF = 24; // Underline; None + protected static final int ATTRIBUTE_BLINK_OFF = 25; // Blink; off - protected static final int ATTRIBUTE_INTENSITY_BOLD = 1; // Intensity: Bold - protected static final int ATTRIBUTE_INTENSITY_FAINT = 2; // Intensity; Faint not widely supported - protected static final int ATTRIBUTE_ITALIC = 3; // Italic; on not widely supported. Sometimes treated as inverse. - protected static final int ATTRIBUTE_UNDERLINE = 4; // Underline; Single - protected static final int ATTRIBUTE_BLINK_SLOW = 5; // Blink; Slow less than 150 per minute - protected static final int ATTRIBUTE_BLINK_FAST = 6; // Blink; Rapid MS-DOS ANSI.SYS; 150 per minute or more - protected static final int ATTRIBUTE_NEGATIVE_ON = 7; // Image; Negative inverse or reverse; swap foreground and background - protected static final int ATTRIBUTE_CONCEAL_ON = 8; // Conceal on - protected static final int ATTRIBUTE_UNDERLINE_DOUBLE = 21; // Underline; Double not widely supported - protected static final int ATTRIBUTE_INTENSITY_NORMAL = 22; // Intensity; Normal not bold and not faint - protected static final int ATTRIBUTE_UNDERLINE_OFF = 24; // Underline; None - protected static final int ATTRIBUTE_BLINK_OFF = 25; // Blink; off @Deprecated protected static final int ATTRIBUTE_NEGATIVE_Off = 27; // Image; Positive + protected static final int ATTRIBUTE_NEGATIVE_OFF = 27; // Image; Positive - protected static final int ATTRIBUTE_CONCEAL_OFF = 28; // Reveal conceal off + protected static final int ATTRIBUTE_CONCEAL_OFF = 28; // Reveal conceal off /** * process SGR other than 0 (reset), 30-39 (foreground), @@ -546,8 +526,7 @@ * @see #processDefaultTextColor() * @see #processDefaultBackgroundColor() */ - protected void processSetAttribute(int attribute) throws IOException { - } + protected void processSetAttribute(int attribute) throws IOException {} protected static final int BLACK = 0; protected static final int RED = 1; @@ -584,8 +563,7 @@ * @param paletteIndex the text color in the palette * @throws IOException if an error occurs */ - protected void processSetForegroundColorExt(int paletteIndex) throws IOException { - } + protected void processSetForegroundColorExt(int paletteIndex) throws IOException {} /** * process SGR 38 corresponding to extended set text color (foreground) @@ -625,8 +603,7 @@ * @param paletteIndex the background color in the palette * @throws IOException if an error occurs */ - protected void processSetBackgroundColorExt(int paletteIndex) throws IOException { - } + protected void processSetBackgroundColorExt(int paletteIndex) throws IOException {} /** * process SGR 48 corresponding to extended set background color @@ -644,22 +621,19 @@ * process SGR 39 corresponding to Default text color (foreground) * @throws IOException if an error occurs */ - protected void processDefaultTextColor() throws IOException { - } + protected void processDefaultTextColor() throws IOException {} /** * process SGR 49 corresponding to Default background color * @throws IOException if an error occurs */ - protected void processDefaultBackgroundColor() throws IOException { - } + protected void processDefaultBackgroundColor() throws IOException {} /** * process SGR 0 corresponding to Reset / Normal * @throws IOException if an error occurs */ - protected void processAttributeRest() throws IOException { - } + protected void processAttributeRest() throws IOException {} /** * process CSI n ; m H corresponding to CUP \u2013 Cursor Position or @@ -668,24 +642,21 @@ * @param col the column * @throws IOException if an error occurs */ - protected void processCursorTo(int row, int col) throws IOException { - } + protected void processCursorTo(int row, int col) throws IOException {} /** * process CSI n G corresponding to CHA \u2013 Cursor Horizontal Absolute * @param x the column * @throws IOException if an error occurs */ - protected void processCursorToColumn(int x) throws IOException { - } + protected void processCursorToColumn(int x) throws IOException {} /** * process CSI n F corresponding to CPL \u2013 Cursor Previous Line * @param count line count * @throws IOException if an error occurs */ - protected void processCursorUpLine(int count) throws IOException { - } + protected void processCursorUpLine(int count) throws IOException {} /** * process CSI n E corresponding to CNL \u2013 Cursor Next Line @@ -704,8 +675,7 @@ * @param count the count * @throws IOException if an error occurs */ - protected void processCursorLeft(int count) throws IOException { - } + protected void processCursorLeft(int count) throws IOException {} /** * process CSI n C corresponding to CUF \u2013 Cursor Forward @@ -724,19 +694,16 @@ * @param count the count * @throws IOException if an error occurs */ - protected void processCursorDown(int count) throws IOException { - } + protected void processCursorDown(int count) throws IOException {} /** * process CSI n A corresponding to CUU \u2013 Cursor Up * @param count the count * @throws IOException if an error occurs */ - protected void processCursorUp(int count) throws IOException { - } + protected void processCursorUp(int count) throws IOException {} - protected void processUnknownExtension(ArrayList options, int command) { - } + protected void processUnknownExtension(ArrayList options, int command) {} /** * process OSC 0;text BEL corresponding to Change Window and Icon label @@ -751,23 +718,20 @@ * process OSC 1;text BEL corresponding to Change Icon label * @param name the icon name */ - protected void processChangeIconName(String name) { - } + protected void processChangeIconName(String name) {} /** * process OSC 2;text BEL corresponding to Change Window title * @param title the title */ - protected void processChangeWindowTitle(String title) { - } + protected void processChangeWindowTitle(String title) {} /** * Process unknown OSC command. * @param command the command * @param param the param */ - protected void processUnknownOperatingSystemCommand(int command, String param) { - } + protected void processUnknownOperatingSystemCommand(int command, String param) {} /** * Process character set sequence. @@ -781,17 +745,13 @@ return true; } - protected void processCharsetSelect(int set, char seq) { - } + protected void processCharsetSelect(int set, char seq) {} private int optionInt(ArrayList options, int index) { - if (options.size() <= index) - throw new IllegalArgumentException(); + if (options.size() <= index) throw new IllegalArgumentException(); Object value = options.get(index); - if (value == null) - throw new IllegalArgumentException(); - if (!value.getClass().equals(Integer.class)) - throw new IllegalArgumentException(); + if (value == null) throw new IllegalArgumentException(); + if (!value.getClass().equals(Integer.class)) throw new IllegalArgumentException(); return (Integer) value; } @@ -828,5 +788,4 @@ flush(); super.close(); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedCharSequence.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedCharSequence.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedCharSequence.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedCharSequence.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -15,6 +15,7 @@ import jdk.internal.org.jline.terminal.impl.AbstractWindowsTerminal; import jdk.internal.org.jline.utils.InfoCmp.Capability; +import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_DISABLE_ALTERNATE_CHARSET; import static jdk.internal.org.jline.utils.AttributedStyle.BG_COLOR; import static jdk.internal.org.jline.utils.AttributedStyle.BG_COLOR_EXP; import static jdk.internal.org.jline.utils.AttributedStyle.FG_COLOR; @@ -30,12 +31,11 @@ import static jdk.internal.org.jline.utils.AttributedStyle.F_FOREGROUND; import static jdk.internal.org.jline.utils.AttributedStyle.F_FOREGROUND_IND; import static jdk.internal.org.jline.utils.AttributedStyle.F_FOREGROUND_RGB; +import static jdk.internal.org.jline.utils.AttributedStyle.F_HIDDEN; import static jdk.internal.org.jline.utils.AttributedStyle.F_INVERSE; import static jdk.internal.org.jline.utils.AttributedStyle.F_ITALIC; import static jdk.internal.org.jline.utils.AttributedStyle.F_UNDERLINE; -import static jdk.internal.org.jline.utils.AttributedStyle.F_HIDDEN; import static jdk.internal.org.jline.utils.AttributedStyle.MASK; -import static jdk.internal.org.jline.terminal.TerminalBuilder.PROP_DISABLE_ALTERNATE_CHARSET; public abstract class AttributedCharSequence implements CharSequence { @@ -120,6 +120,7 @@ char c = charAt(i); if (altIn != null && altOut != null) { char pc = c; + // @spotless:off switch (c) { case '\u2518': c = 'j'; break; case '\u2510': c = 'k'; break; @@ -133,15 +134,16 @@ case '\u252C': c = 'w'; break; case '\u2502': c = 'x'; break; } + // @spotless:on boolean oldalt = alt; alt = c != pc; if (oldalt ^ alt) { sb.append(alt ? altIn : altOut); } } - long s = styleCodeAt(i) & ~F_HIDDEN; // The hidden flag does not change the ansi styles + long s = styleCodeAt(i) & ~F_HIDDEN; // The hidden flag does not change the ansi styles if (style != s) { - long d = (style ^ s) & MASK; + long d = (style ^ s) & MASK; long fg = (s & F_FOREGROUND) != 0 ? s & (FG_COLOR | F_FOREGROUND) : 0; long bg = (s & F_BACKGROUND) != 0 ? s & (BG_COLOR | F_BACKGROUND) : 0; if (s == 0) { @@ -172,16 +174,16 @@ if (fg > 0) { int rounded = -1; if ((fg & F_FOREGROUND_RGB) != 0) { - int r = (int)(fg >> (FG_COLOR_EXP + 16)) & 0xFF; - int g = (int)(fg >> (FG_COLOR_EXP + 8)) & 0xFF; - int b = (int)(fg >> FG_COLOR_EXP) & 0xFF; + int r = (int) (fg >> (FG_COLOR_EXP + 16)) & 0xFF; + int g = (int) (fg >> (FG_COLOR_EXP + 8)) & 0xFF; + int b = (int) (fg >> FG_COLOR_EXP) & 0xFF; if (colors >= HIGH_COLORS) { first = attr(sb, "38;2;" + r + ";" + g + ";" + b, first); } else { rounded = palette.round(r, g, b); } } else if ((fg & F_FOREGROUND_IND) != 0) { - rounded = palette.round((int)(fg >> FG_COLOR_EXP) & 0xFF); + rounded = palette.round((int) (fg >> FG_COLOR_EXP) & 0xFF); } if (rounded >= 0) { if (colors >= HIGH_COLORS && force == ForceMode.ForceTrueColors) { @@ -211,16 +213,16 @@ if (bg > 0) { int rounded = -1; if ((bg & F_BACKGROUND_RGB) != 0) { - int r = (int)(bg >> (BG_COLOR_EXP + 16)) & 0xFF; - int g = (int)(bg >> (BG_COLOR_EXP + 8)) & 0xFF; - int b = (int)(bg >> BG_COLOR_EXP) & 0xFF; + int r = (int) (bg >> (BG_COLOR_EXP + 16)) & 0xFF; + int g = (int) (bg >> (BG_COLOR_EXP + 8)) & 0xFF; + int b = (int) (bg >> BG_COLOR_EXP) & 0xFF; if (colors >= HIGH_COLORS) { first = attr(sb, "48;2;" + r + ";" + g + ";" + b, first); } else { rounded = palette.round(r, g, b); } } else if ((bg & F_BACKGROUND_IND) != 0) { - rounded = palette.round((int)(bg >> BG_COLOR_EXP) & 0xFF); + rounded = palette.round((int) (bg >> BG_COLOR_EXP) & 0xFF); } if (rounded >= 0) { if (colors >= HIGH_COLORS && force == ForceMode.ForceTrueColors) { @@ -243,8 +245,7 @@ background = bg; } if ((d & (F_BOLD | F_FAINT)) != 0) { - if ( (d & F_BOLD) != 0 && (s & F_BOLD) == 0 - || (d & F_FAINT) != 0 && (s & F_FAINT) == 0) { + if ((d & F_BOLD) != 0 && (s & F_BOLD) == 0 || (d & F_FAINT) != 0 && (s & F_FAINT) == 0) { first = attr(sb, "22", first); } if ((d & F_BOLD) != 0 && (s & F_BOLD) != 0) { @@ -360,8 +361,7 @@ int len = length(); for (int cur = 0; cur < len; ) { int cp = codePointAt(cur); - if (!isHidden(cur)) - cols += WCWidth.wcwidth(cp); + if (!isHidden(cur)) cols += WCWidth.wcwidth(cp); cur += Character.charCount(cp); } return cols; @@ -382,8 +382,7 @@ int end = begin; while (end < this.length()) { int cp = codePointAt(end); - if (cp == '\n') - break; + if (cp == '\n') break; int w = isHidden(end) ? 0 : WCWidth.wcwidth(cp); if (col + w > stop) { break; @@ -407,7 +406,7 @@ int cp = codePointAt(cur); int w = isHidden(cur) ? 0 : WCWidth.wcwidth(cp); if (cp == '\n') { - strings.add(subSequence(beg, includeNewlines ? cur+1 : cur)); + strings.add(subSequence(beg, includeNewlines ? cur + 1 : cur)); beg = cur + 1; col = 0; } else if ((col += w) > columns) { @@ -429,5 +428,4 @@ public AttributedString toAttributedString() { return substring(0, length()); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedString.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedString.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedString.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedString.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -15,6 +15,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import jdk.internal.org.jline.terminal.Terminal; + /** * Attributed string. * Instances of this class are immutables. @@ -103,11 +105,28 @@ } public static AttributedString fromAnsi(String ansi, List tabs) { + return fromAnsi(ansi, tabs, null, null); + } + + public static AttributedString fromAnsi(String ansi, Terminal terminal) { + String alternateIn, alternateOut; + if (!DISABLE_ALTERNATE_CHARSET) { + alternateIn = Curses.tputs(terminal.getStringCapability(InfoCmp.Capability.enter_alt_charset_mode)); + alternateOut = Curses.tputs(terminal.getStringCapability(InfoCmp.Capability.exit_alt_charset_mode)); + } else { + alternateIn = null; + alternateOut = null; + } + return fromAnsi(ansi, Arrays.asList(0), alternateIn, alternateOut); + } + + public static AttributedString fromAnsi(String ansi, List tabs, String altIn, String altOut) { if (ansi == null) { return null; } return new AttributedStringBuilder(ansi.length()) .tabs(tabs) + .altCharset(altIn, altOut) .ansiAppend(ansi) .toAttributedString(); } @@ -116,9 +135,7 @@ if (ansi == null) { return null; } - return new AttributedStringBuilder(ansi.length()) - .ansiAppend(ansi) - .toString(); + return new AttributedStringBuilder(ansi.length()).ansiAppend(ansi).toString(); } @Override @@ -162,7 +179,7 @@ } result = matcher.find(); } while (result); - return new AttributedString(buffer, newstyle, start , end); + return new AttributedString(buffer, newstyle, start, end); } return this; } @@ -179,15 +196,16 @@ private boolean arrEq(char[] a1, char[] a2, int s1, int s2, int l) { for (int i = 0; i < l; i++) { - if (a1[s1+i] != a2[s2+i]) { + if (a1[s1 + i] != a2[s2 + i]) { return false; } } return true; } + private boolean arrEq(long[] a1, long[] a2, int s1, int s2, int l) { for (int i = 0; i < l; i++) { - if (a1[s1+i] != a2[s2+i]) { + if (a1[s1 + i] != a2[s2 + i]) { return false; } } @@ -221,5 +239,4 @@ } return sb.toAttributedString(); } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStringBuilder.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStringBuilder.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStringBuilder.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStringBuilder.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -27,6 +27,9 @@ private long[] style; private int length; private TabStops tabs = new TabStops(0); + private char[] altIn; + private char[] altOut; + private boolean inAltCharset; private int lastLineLength = 0; private AttributedStyle current = AttributedStyle.DEFAULT; @@ -81,10 +84,7 @@ @Override public AttributedString subSequence(int start, int end) { return new AttributedString( - Arrays.copyOfRange(buffer, start, end), - Arrays.copyOfRange(style, start, end), - 0, - end - start); + Arrays.copyOfRange(buffer, start, end), Arrays.copyOfRange(style, start, end), 0, end - start); } @Override @@ -108,6 +108,14 @@ return append(Character.toString(c)); } + public AttributedStringBuilder append(char c, int repeat) { + AttributedString s = new AttributedString(Character.toString(c), current); + while (repeat-- > 0) { + append(s); + } + return this; + } + public AttributedStringBuilder append(CharSequence csq, AttributedStyle style) { return append(new AttributedString(csq, style)); } @@ -117,12 +125,12 @@ return this; } - public AttributedStringBuilder style(Function style) { + public AttributedStringBuilder style(Function style) { current = style.apply(current); return this; } - public AttributedStringBuilder styled(Function style, CharSequence cs) { + public AttributedStringBuilder styled(Function style, CharSequence cs) { return styled(style, sb -> sb.append(cs)); } @@ -130,7 +138,8 @@ return styled(s -> style, sb -> sb.append(cs)); } - public AttributedStringBuilder styled(Function style, Consumer consumer) { + public AttributedStringBuilder styled( + Function style, Consumer consumer) { AttributedStyle prev = current; current = style.apply(prev); consumer.accept(this); @@ -338,23 +347,90 @@ // This is not a SGR code, so ignore ansiState = 0; } - } else if (c == '\t' && tabs.defined()) { - insertTab(current); } else { - ensureCapacity(length + 1); - buffer[length] = c; - style[length] = this.current.getStyle(); - if (c == '\n') { - lastLineLength = 0; + if (ansiState >= 1) { + ensureCapacity(length + 1); + buffer[length++] = 27; + if (ansiState >= 2) { + ensureCapacity(length + 1); + buffer[length++] = '['; + } + ansiState = 0; + } + if (c == '\t' && tabs.defined()) { + insertTab(current); } else { - lastLineLength++; + ensureCapacity(length + 1); + if (inAltCharset) { + switch (c) { + case 'j': + c = '\u2518'; + break; + case 'k': + c = '\u2510'; + break; + case 'l': + c = '\u250C'; + break; + case 'm': + c = '\u2514'; + break; + case 'n': + c = '\u253C'; + break; + case 'q': + c = '\u2500'; + break; + case 't': + c = '\u251C'; + break; + case 'u': + c = '\u2524'; + break; + case 'v': + c = '\u2534'; + break; + case 'w': + c = '\u252C'; + break; + case 'x': + c = '\u2502'; + break; + } + } + buffer[length] = c; + style[length] = this.current.getStyle(); + if (c == '\n') { + lastLineLength = 0; + } else { + lastLineLength++; + } + length++; + if (altIn != null && altOut != null) { + char[] alt = inAltCharset ? altOut : altIn; + if (equals(buffer, length - alt.length, alt, 0, alt.length)) { + inAltCharset = !inAltCharset; + length -= alt.length; + } + } } - length++; } } return this; } + private static boolean equals(char[] a, int aFromIndex, char[] b, int bFromIndex, int length) { + if (aFromIndex < 0 || bFromIndex < 0 || aFromIndex + length > a.length || bFromIndex + length > b.length) { + return false; + } + for (int i = 0; i < length; i++) { + if (a[aFromIndex + i] != b[bFromIndex + i]) { + return false; + } + } + return true; + } + protected void insertTab(AttributedStyle s) { int nb = tabs.spaces(lastLineLength); ensureCapacity(length + nb); @@ -393,6 +469,15 @@ return this; } + public AttributedStringBuilder altCharset(String altIn, String altOut) { + if (length > 0) { + throw new IllegalStateException("Cannot change alternative charset after appending text"); + } + this.altIn = altIn != null ? altIn.toCharArray() : null; + this.altOut = altOut != null ? altOut.toCharArray() : null; + return this; + } + public AttributedStringBuilder styleMatches(Pattern pattern, AttributedStyle s) { Matcher matcher = pattern.matcher(this); while (matcher.find()) { @@ -416,7 +501,7 @@ return this; } - private class TabStops { + private static class TabStops { private List tabs = new ArrayList<>(); private int lastStop = 0; private int lastSize = 0; @@ -428,7 +513,7 @@ public TabStops(List tabs) { this.tabs = tabs; int p = 0; - for (int s: tabs) { + for (int s : tabs) { if (s <= p) { continue; } @@ -447,7 +532,7 @@ if (lastLineLength >= lastStop) { out = lastSize - (lastLineLength - lastStop) % lastSize; } else { - for (int s: tabs) { + for (int s : tabs) { if (s > lastLineLength) { out = s - lastLineLength; break; @@ -456,7 +541,5 @@ } return out; } - } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStyle.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStyle.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStyle.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/AttributedStyle.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2021, the original author or authors. + * Copyright (c) 2002-2021, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -15,39 +15,39 @@ */ public class AttributedStyle { - public static final int BLACK = 0; - public static final int RED = 1; - public static final int GREEN = 2; - public static final int YELLOW = 3; - public static final int BLUE = 4; - public static final int MAGENTA = 5; - public static final int CYAN = 6; - public static final int WHITE = 7; - - public static final int BRIGHT = 8; - - static final long F_BOLD = 0x00000001; - static final long F_FAINT = 0x00000002; - static final long F_ITALIC = 0x00000004; - static final long F_UNDERLINE = 0x00000008; - static final long F_BLINK = 0x00000010; - static final long F_INVERSE = 0x00000020; - static final long F_CONCEAL = 0x00000040; - static final long F_CROSSED_OUT = 0x00000080; - static final long F_FOREGROUND_IND = 0x00000100; - static final long F_FOREGROUND_RGB = 0x00000200; - static final long F_FOREGROUND = F_FOREGROUND_IND | F_FOREGROUND_RGB; - static final long F_BACKGROUND_IND = 0x00000400; - static final long F_BACKGROUND_RGB = 0x00000800; - static final long F_BACKGROUND = F_BACKGROUND_IND | F_BACKGROUND_RGB; - static final long F_HIDDEN = 0x00001000; - - static final long MASK = 0x00001FFF; - - static final int FG_COLOR_EXP = 15; - static final int BG_COLOR_EXP = 39; - static final long FG_COLOR = 0xFFFFFFL << FG_COLOR_EXP; - static final long BG_COLOR = 0xFFFFFFL << BG_COLOR_EXP; + public static final int BLACK = 0; + public static final int RED = 1; + public static final int GREEN = 2; + public static final int YELLOW = 3; + public static final int BLUE = 4; + public static final int MAGENTA = 5; + public static final int CYAN = 6; + public static final int WHITE = 7; + + public static final int BRIGHT = 8; + + static final long F_BOLD = 0x00000001; + static final long F_FAINT = 0x00000002; + static final long F_ITALIC = 0x00000004; + static final long F_UNDERLINE = 0x00000008; + static final long F_BLINK = 0x00000010; + static final long F_INVERSE = 0x00000020; + static final long F_CONCEAL = 0x00000040; + static final long F_CROSSED_OUT = 0x00000080; + static final long F_FOREGROUND_IND = 0x00000100; + static final long F_FOREGROUND_RGB = 0x00000200; + static final long F_FOREGROUND = F_FOREGROUND_IND | F_FOREGROUND_RGB; + static final long F_BACKGROUND_IND = 0x00000400; + static final long F_BACKGROUND_RGB = 0x00000800; + static final long F_BACKGROUND = F_BACKGROUND_IND | F_BACKGROUND_RGB; + static final long F_HIDDEN = 0x00001000; + + static final long MASK = 0x00001FFF; + + static final int FG_COLOR_EXP = 15; + static final int BG_COLOR_EXP = 39; + static final long FG_COLOR = 0xFFFFFFL << FG_COLOR_EXP; + static final long BG_COLOR = 0xFFFFFFL << BG_COLOR_EXP; public static final AttributedStyle DEFAULT = new AttributedStyle(); public static final AttributedStyle BOLD = DEFAULT.bold(); @@ -70,8 +70,9 @@ public AttributedStyle(long style, long mask) { this.style = style; - this.mask = mask & MASK | ((style & F_FOREGROUND) != 0 ? FG_COLOR : 0) - | ((style & F_BACKGROUND) != 0 ? BG_COLOR : 0); + this.mask = mask & MASK + | ((style & F_FOREGROUND) != 0 ? FG_COLOR : 0) + | ((style & F_BACKGROUND) != 0 ? BG_COLOR : 0); } public AttributedStyle bold() { @@ -176,7 +177,9 @@ } public AttributedStyle foreground(int color) { - return new AttributedStyle(style & ~FG_COLOR | F_FOREGROUND_IND | (((long) color << FG_COLOR_EXP) & FG_COLOR), mask | F_FOREGROUND_IND); + return new AttributedStyle( + style & ~FG_COLOR | F_FOREGROUND_IND | (((long) color << FG_COLOR_EXP) & FG_COLOR), + mask | F_FOREGROUND_IND); } public AttributedStyle foreground(int r, int g, int b) { @@ -184,7 +187,9 @@ } public AttributedStyle foregroundRgb(int color) { - return new AttributedStyle(style & ~FG_COLOR | F_FOREGROUND_RGB | ((((long) color & 0xFFFFFF) << FG_COLOR_EXP) & FG_COLOR), mask | F_FOREGROUND_RGB); + return new AttributedStyle( + style & ~FG_COLOR | F_FOREGROUND_RGB | ((((long) color & 0xFFFFFF) << FG_COLOR_EXP) & FG_COLOR), + mask | F_FOREGROUND_RGB); } public AttributedStyle foregroundOff() { @@ -196,7 +201,9 @@ } public AttributedStyle background(int color) { - return new AttributedStyle(style & ~BG_COLOR | F_BACKGROUND_IND | (((long) color << BG_COLOR_EXP) & BG_COLOR), mask | F_BACKGROUND_IND); + return new AttributedStyle( + style & ~BG_COLOR | F_BACKGROUND_IND | (((long) color << BG_COLOR_EXP) & BG_COLOR), + mask | F_BACKGROUND_IND); } public AttributedStyle background(int r, int g, int b) { @@ -204,7 +211,9 @@ } public AttributedStyle backgroundRgb(int color) { - return new AttributedStyle(style & ~BG_COLOR | F_BACKGROUND_RGB | ((((long) color & 0xFFFFFF) << BG_COLOR_EXP) & BG_COLOR), mask | F_BACKGROUND_RGB); + return new AttributedStyle( + style & ~BG_COLOR | F_BACKGROUND_RGB | ((((long) color & 0xFFFFFF) << BG_COLOR_EXP) & BG_COLOR), + mask | F_BACKGROUND_RGB); } public AttributedStyle backgroundOff() { @@ -249,7 +258,6 @@ AttributedStyle that = (AttributedStyle) o; if (style != that.style) return false; return mask == that.mask; - } @Override @@ -266,10 +274,6 @@ @Override public String toString() { - return "AttributedStyle{" + - "style=" + style + - ", mask=" + mask + - ", ansi=" + toAnsi() + - '}'; + return "AttributedStyle{" + "style=" + style + ", mask=" + mask + ", ansi=" + toAnsi() + '}'; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ClosedException.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ClosedException.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ClosedException.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ClosedException.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -14,8 +14,7 @@ private static final long serialVersionUID = 3085420657077696L; - public ClosedException() { - } + public ClosedException() {} public ClosedException(String message) { super(message); diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ColorPalette.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ColorPalette.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ColorPalette.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ColorPalette.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -21,7 +21,8 @@ */ public class ColorPalette { - public static final String XTERM_INITC = "\\E]4;%p1%d;rgb\\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\\E\\\\"; + public static final String XTERM_INITC = + "\\E]4;%p1%d;rgb\\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\\E\\\\"; public static final ColorPalette DEFAULT = new ColorPalette(); @@ -41,6 +42,7 @@ this(terminal, null); } + @SuppressWarnings("this-escape") public ColorPalette(Terminal terminal, String distance) throws IOException { this.terminal = terminal; this.distanceName = distance; @@ -245,10 +247,13 @@ if (rgb.size() != 3) { return null; } - double r = Integer.parseInt(rgb.get(0), 16) / ((1 << (4 * rgb.get(0).length())) - 1.0); - double g = Integer.parseInt(rgb.get(1), 16) / ((1 << (4 * rgb.get(1).length())) - 1.0); - double b = Integer.parseInt(rgb.get(2), 16) / ((1 << (4 * rgb.get(2).length())) - 1.0); - palette[idx] = (int)((Math.round(r * 255) << 16) + (Math.round(g * 255) << 8) + Math.round(b * 255)); + double r = Integer.parseInt(rgb.get(0), 16) + / ((1 << (4 * rgb.get(0).length())) - 1.0); + double g = Integer.parseInt(rgb.get(1), 16) + / ((1 << (4 * rgb.get(1).length())) - 1.0); + double b = Integer.parseInt(rgb.get(2), 16) + / ((1 << (4 * rgb.get(2).length())) - 1.0); + palette[idx] = (int) ((Math.round(r * 255) << 16) + (Math.round(g * 255) << 8) + Math.round(b * 255)); black &= palette[idx] == 0; } if (black) { @@ -256,7 +261,13 @@ } } int max = 256; - while (max > 0 && palette[--max] == 0); + while (max > 0 && palette[--max] == 0) + ; return Arrays.copyOfRange(palette, 0, max + 1); } + + @Override + public String toString() { + return "ColorPalette[" + "length=" + getLength() + ", " + "distance='" + getDist() + "\']"; + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Colors.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Colors.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Colors.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Colors.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -21,6 +21,8 @@ public class Colors { + // @spotless:off + /** * Default 256 colors palette */ @@ -111,24 +113,26 @@ 0x2e2e2e, 0x5c5c5c, 0x737373, 0x8b8b8b, 0xa2a2a2, 0xb9b9b9, 0xd0d0d0, 0xe7e7e7, }; + // @spotless:on + /** D50 illuminant for CAM color spaces */ - public static final double[] D50 = new double[] { 96.422f, 100.0f, 82.521f }; + public static final double[] D50 = new double[] {96.422f, 100.0f, 82.521f}; /** D65 illuminant for CAM color spaces */ - public static final double[] D65 = new double[] { 95.047, 100.0, 108.883 }; + public static final double[] D65 = new double[] {95.047, 100.0, 108.883}; /** Average surrounding for CAM color spaces */ - public static final double[] averageSurrounding = new double[] { 1.0, 0.690, 1.0 }; + public static final double[] averageSurrounding = new double[] {1.0, 0.690, 1.0}; /** Dim surrounding for CAM color spaces */ - public static final double[] dimSurrounding = new double[] { 0.9, 0.590, 0.9 }; + public static final double[] dimSurrounding = new double[] {0.9, 0.590, 0.9}; /** Dark surrounding for CAM color spaces */ - public static final double[] darkSurrounding = new double[] { 0.8, 0.525, 0.8 }; + public static final double[] darkSurrounding = new double[] {0.8, 0.525, 0.8}; /** sRGB encoding environment */ - public static final double[] sRGB_encoding_environment = vc(D50, 64.0, 64.0/5, dimSurrounding); + public static final double[] sRGB_encoding_environment = vc(D50, 64.0, 64.0 / 5, dimSurrounding); /** sRGB typical environment */ - public static final double[] sRGB_typical_environment = vc(D50, 200.0, 200.0/5, averageSurrounding); + public static final double[] sRGB_typical_environment = vc(D50, 200.0, 200.0 / 5, averageSurrounding); /** Adobe RGB environment */ - public static final double[] AdobeRGB_environment = vc(D65, 160.0, 160.0/5, averageSurrounding); + public static final double[] AdobeRGB_environment = vc(D65, 160.0, 160.0 / 5, averageSurrounding); private static int[] COLORS_256 = DEFAULT_COLORS_256; @@ -149,8 +153,9 @@ if (COLOR_NAMES == null) { Map colors = new LinkedHashMap<>(); try (InputStream is = InfoCmp.class.getResourceAsStream("colors.txt"); - BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - br.lines().map(String::trim) + BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + br.lines() + .map(String::trim) .filter(s -> !s.startsWith("#")) .filter(s -> !s.isEmpty()) .forEachOrdered(s -> { @@ -206,7 +211,7 @@ if (dist == null) { dist = System.getProperty(PROP_COLOR_DISTANCE, "cie76"); } - return doGetDistance(dist); + return new NamedDistance(dist, doGetDistance(dist)); } private static Distance doGetDistance(String dist) { @@ -216,7 +221,7 @@ double[] c1 = rgb(p1); double[] c2 = rgb(p2); double rmean = (c1[0] + c2[0]) / 2.0; - double[] w = { 2.0 + rmean, 4.0, 3.0 - rmean }; + double[] w = {2.0 + rmean, 4.0, 3.0 - rmean}; return scalar(c1, c2, w); }; } @@ -228,7 +233,7 @@ } if (dist.matches("lab\\(([0-9]+(\\.[0-9]+)?),([0-9]+(\\.[0-9]+)?)\\)")) { double[] w = getWeights(dist); - return (p1, p2) -> scalar(rgb2cielab(p1), rgb2cielab(p2), new double[] { w[0], w[1], w[1] }); + return (p1, p2) -> scalar(rgb2cielab(p1), rgb2cielab(p2), new double[] {w[0], w[1], w[1]}); } if (dist.equals("cie94")) { return (p1, p2) -> cie94(rgb2cielab(p1), rgb2cielab(p2)); @@ -251,7 +256,7 @@ double[] c1 = camlab(p1, sRGB_typical_environment); double[] c2 = camlab(p2, sRGB_typical_environment); double[] w = getWeights(dist); - return scalar(c1, c2, new double[] { w[0], w[1], w[1] }); + return scalar(c1, c2, new double[] {w[0], w[1], w[1]}); }; } if (dist.matches("camlch")) { @@ -273,20 +278,37 @@ } private static double[] getWeights(String dist) { - String[] weights = dist.substring(dist.indexOf('(') + 1, dist.length() - 1).split(","); + String[] weights = + dist.substring(dist.indexOf('(') + 1, dist.length() - 1).split(","); return Stream.of(weights).mapToDouble(Double::parseDouble).toArray(); } private static double scalar(double[] c1, double[] c2, double[] w) { - return sqr((c1[0] - c2[0]) * w[0]) - + sqr((c1[1] - c2[1]) * w[1]) - + sqr((c1[2] - c2[2]) * w[2]); + return sqr((c1[0] - c2[0]) * w[0]) + sqr((c1[1] - c2[1]) * w[1]) + sqr((c1[2] - c2[2]) * w[2]); } private static double scalar(double[] c1, double[] c2) { - return sqr(c1[0] - c2[0]) - + sqr(c1[1] - c2[1]) - + sqr(c1[2] - c2[2]); + return sqr(c1[0] - c2[0]) + sqr(c1[1] - c2[1]) + sqr(c1[2] - c2[2]); + } + + private static class NamedDistance implements Distance { + private final String name; + private final Distance delegate; + + public NamedDistance(String name, Distance delegate) { + this.name = name; + this.delegate = delegate; + } + + @Override + public double compute(int c1, int c2) { + return delegate.compute(c1, c2); + } + + @Override + public String toString() { + return name; + } } private static final int L = 0; @@ -325,7 +347,7 @@ double c_star_average_ab = (c_star_1_ab + c_star_2_ab) / 2.0; double c_star_average_ab_pot_3 = c_star_average_ab * c_star_average_ab * c_star_average_ab; double c_star_average_ab_pot_7 = c_star_average_ab_pot_3 * c_star_average_ab_pot_3 * c_star_average_ab; - double G = 0.5 * (1.0 - Math.sqrt(c_star_average_ab_pot_7 / (c_star_average_ab_pot_7 + 6103515625.0))); //25^7 + double G = 0.5 * (1.0 - Math.sqrt(c_star_average_ab_pot_7 / (c_star_average_ab_pot_7 + 6103515625.0))); // 25^7 double a1_prime = (1.0 + G) * lab1[A]; double a2_prime = (1.0 + G) * lab2[A]; double C_prime_1 = Math.sqrt(a1_prime * a1_prime + lab1[B] * lab1[B]); @@ -365,16 +387,18 @@ + 0.24 * Math.cos(Math.toRadians(h_prime_average * 2.0)) + 0.32 * Math.cos(Math.toRadians(h_prime_average * 3.0 + 6.0)) - 0.20 * Math.cos(Math.toRadians(h_prime_average * 4.0 - 63.0)); - double S_L = 1.0 + ((0.015 * L_prime_average_minus_50_square) / Math.sqrt(20.0 + L_prime_average_minus_50_square)); + double S_L = + 1.0 + ((0.015 * L_prime_average_minus_50_square) / Math.sqrt(20.0 + L_prime_average_minus_50_square)); double S_C = 1.0 + 0.045 * C_prime_average; double S_H = 1.0 + 0.015 * T * C_prime_average; double h_prime_average_minus_275_div_25 = (h_prime_average - 275.0) / (25.0); - double h_prime_average_minus_275_div_25_square = h_prime_average_minus_275_div_25 * h_prime_average_minus_275_div_25; + double h_prime_average_minus_275_div_25_square = + h_prime_average_minus_275_div_25 * h_prime_average_minus_275_div_25; double delta_theta = 30.0 * Math.exp(-h_prime_average_minus_275_div_25_square); double C_prime_average_pot_3 = C_prime_average * C_prime_average * C_prime_average; double C_prime_average_pot_7 = C_prime_average_pot_3 * C_prime_average_pot_3 * C_prime_average; - double R_C = 2.0 * Math.sqrt(C_prime_average_pot_7 / (C_prime_average_pot_7 + 6103515625.0)); //25^7 - double R_T = - Math.sin(Math.toRadians(2.0 * delta_theta)) * R_C; + double R_C = 2.0 * Math.sqrt(C_prime_average_pot_7 / (C_prime_average_pot_7 + 6103515625.0)); // 25^7 + double R_T = -Math.sin(Math.toRadians(2.0 * delta_theta)) * R_C; double dLKlsl = delta_L_prime / (kl * S_L); double dCkcsc = delta_C_prime / (kc * S_C); double dHkhsh = delta_H_prime / (kh * S_H); @@ -392,11 +416,11 @@ double sM = ((1.0 / 0.0228) * Math.log(1.0 + 0.0228 * lch[1])); double a = sM * Math.cos(Math.toRadians(lch[2])); double b = sM * Math.sin(Math.toRadians(lch[2])); - return new double[] {sJ, a, b }; + return new double[] {sJ, a, b}; } static double camlch(double[] c1, double[] c2) { - return camlch(c1, c2, new double[] { 1.0, 1.0, 1.0 }); + return camlch(c1, c2, new double[] {1.0, 1.0, 1.0}); } static double camlch(double[] c1, double[] c2, double[] w) { @@ -414,18 +438,16 @@ private static double hueDifference(double hue1, double hue2, double c) { double difference = (hue2 - hue1) % c; double ch = c / 2; - if (difference > ch) - difference -= c; - if (difference < -ch) - difference += c; + if (difference > ch) difference -= c; + if (difference < -ch) difference += c; return difference; } private static double[] rgb(int color) { int r = (color >> 16) & 0xFF; - int g = (color >> 8) & 0xFF; - int b = (color >> 0) & 0xFF; - return new double[] { r / 255.0, g / 255.0, b / 255.0 }; + int g = (color >> 8) & 0xFF; + int b = (color >> 0) & 0xFF; + return new double[] {r / 255.0, g / 255.0, b / 255.0}; } static double[] rgb2xyz(int color) { @@ -454,13 +476,13 @@ static double[] lch2lab(double[] lch) { double toRad = Math.PI / 180; - return new double[] { lch[0], lch[1] * Math.cos(lch[2] * toRad), lch[1] * Math.sin(lch[2] * toRad) }; + return new double[] {lch[0], lch[1] * Math.cos(lch[2] * toRad), lch[1] * Math.sin(lch[2] * toRad)}; } private static double[] xyz2camlch(double[] xyz, double[] vc) { double[] XYZ = new double[] {xyz[0] * 100.0, xyz[1] * 100.0, xyz[2] * 100.0}; double[] cam = forwardTransform(XYZ, vc); - return new double[] { cam[J], cam[M], cam[h] }; + return new double[] {cam[J], cam[M], cam[h]}; } /** Lightness */ @@ -478,12 +500,12 @@ /** Hue */ public static final int h = 6; - /** CIECAM02 appearance correlates */ private static double[] forwardTransform(double[] XYZ, double[] vc) { // calculate sharpened cone response double[] RGB = forwardPreAdaptationConeResponse(XYZ); - // calculate corresponding (sharpened) cone response considering various luminance level and surround conditions in D + // calculate corresponding (sharpened) cone response considering various luminance level and surround conditions + // in D double[] RGB_c = forwardPostAdaptationConeResponse(RGB, vc); // calculate HPE equal area cone fundamentals double[] RGBPrime = CAT02toHPE(RGB_c); @@ -501,37 +523,40 @@ // calculate eccentricity double e = ((12500.0 / 13.0) * vc[VC_N_C] * vc[VC_N_CB]) * (Math.cos(Math.toRadians(h) + 2.0) + 3.8); // get t - double t = e * Math.sqrt(Math.pow(a, 2.0) + Math.pow(b, 2.0)) / (RGBPrime_a[0] + RGBPrime_a[1] + 1.05 * RGBPrime_a[2]); + double t = e + * Math.sqrt(Math.pow(a, 2.0) + Math.pow(b, 2.0)) + / (RGBPrime_a[0] + RGBPrime_a[1] + 1.05 * RGBPrime_a[2]); // calculate brightness double Q = (4.0 / vc[VC_C]) * Math.sqrt(J / 100.0) * (vc[VC_A_W] + 4.0) * Math.pow(vc[VC_F_L], 0.25); // calculate the correlates of chroma, colorfulness, and saturation - double C = Math.signum(t) * Math.pow(Math.abs(t), 0.9) * Math.sqrt(J / 100.0) * Math.pow(1.64- Math.pow(0.29, vc[VC_N]), 0.73); + double C = Math.signum(t) + * Math.pow(Math.abs(t), 0.9) + * Math.sqrt(J / 100.0) + * Math.pow(1.64 - Math.pow(0.29, vc[VC_N]), 0.73); double M = C * Math.pow(vc[VC_F_L], 0.25); double s = 100.0 * Math.sqrt(M / Q); // calculate hue composition double H = calculateH(h); - return new double[] { J, Q, C, M, s, H, h }; + return new double[] {J, Q, C, M, s, H, h}; } private static double calculateH(double h) { - if (h < 20.14) - h = h + 360; + if (h < 20.14) h = h + 360; double i; - if (h >= 20.14 && h < 90.0) { // index i = 1 + if (h >= 20.14 && h < 90.0) { // index i = 1 i = (h - 20.14) / 0.8; return 100.0 * i / (i + (90 - h) / 0.7); } else if (h < 164.25) { // index i = 2 i = (h - 90) / 0.7; return 100.0 + 100.0 * i / (i + (164.25 - h) / 1); - } else if (h < 237.53) { // index i = 3 + } else if (h < 237.53) { // index i = 3 i = (h - 164.25) / 1.0; return 200.0 + 100.0 * i / (i + (237.53 - h) / 1.2); - } else if (h <= 380.14) { // index i = 4 + } else if (h <= 380.14) { // index i = 4 i = (h - 237.53) / 1.2; double H = 300.0 + 100.0 * i / (i + (380.14 - h) / 0.8); // don't use 400 if we can use 0 - if (H <= 400.0 && H >= 399.999) - H = 0; + if (H <= 400.0 && H >= 399.999) H = 0; return H; } else { throw new IllegalArgumentException("h outside assumed range 0..360: " + h); @@ -540,8 +565,8 @@ private static double[] forwardResponseCompression(double[] RGB, double[] vc) { double[] result = new double[3]; - for(int channel = 0; channel < RGB.length; channel++) { - if(RGB[channel] >= 0) { + for (int channel = 0; channel < RGB.length; channel++) { + if (RGB[channel] >= 0) { double n = Math.pow(vc[VC_F_L] * RGB[channel] / 100.0, 0.42); result[channel] = 400.0 * n / (n + 27.13) + 0.1; } else { @@ -553,22 +578,22 @@ } private static double[] forwardPostAdaptationConeResponse(double[] RGB, double[] vc) { - return new double[] { vc[VC_D_RGB_R] * RGB[0], vc[VC_D_RGB_G] * RGB[1], vc[VC_D_RGB_B] * RGB[2] }; + return new double[] {vc[VC_D_RGB_R] * RGB[0], vc[VC_D_RGB_G] * RGB[1], vc[VC_D_RGB_B] * RGB[2]}; } public static double[] CAT02toHPE(double[] RGB) { double[] RGBPrime = new double[3]; - RGBPrime[0] = 0.7409792 * RGB[0] + 0.2180250 * RGB[1] + 0.0410058 * RGB[2]; - RGBPrime[1] = 0.2853532 * RGB[0] + 0.6242014 * RGB[1] + 0.0904454 * RGB[2]; + RGBPrime[0] = 0.7409792 * RGB[0] + 0.2180250 * RGB[1] + 0.0410058 * RGB[2]; + RGBPrime[1] = 0.2853532 * RGB[0] + 0.6242014 * RGB[1] + 0.0904454 * RGB[2]; RGBPrime[2] = -0.0096280 * RGB[0] - 0.0056980 * RGB[1] + 1.0153260 * RGB[2]; return RGBPrime; } private static double[] forwardPreAdaptationConeResponse(double[] XYZ) { double[] RGB = new double[3]; - RGB[0] = 0.7328 * XYZ[0] + 0.4296 * XYZ[1] - 0.1624 * XYZ[2]; + RGB[0] = 0.7328 * XYZ[0] + 0.4296 * XYZ[1] - 0.1624 * XYZ[2]; RGB[1] = -0.7036 * XYZ[0] + 1.6975 * XYZ[1] + 0.0061 * XYZ[2]; - RGB[2] = 0.0030 * XYZ[0] + 0.0136 * XYZ[1] + 0.9834 * XYZ[2]; + RGB[2] = 0.0030 * XYZ[0] + 0.0136 * XYZ[1] + 0.9834 * XYZ[2]; return RGB; } @@ -581,8 +606,8 @@ static final int VC_Z_W = 2; static final int VC_L_A = 3; static final int VC_Y_B = 4; - static final int VC_F = 5; - static final int VC_C = 6; + static final int VC_F = 5; + static final int VC_C = 6; static final int VC_N_C = 7; static final int VC_Z = 8; @@ -607,33 +632,33 @@ vc[VC_N_C] = surrounding[SUR_N_C]; double[] RGB_w = forwardPreAdaptationConeResponse(xyz_w); - double D = Math.max(0.0, Math.min(1.0, vc[VC_F] * (1.0 - (1.0 / 3.6) * Math.pow(Math.E, (-L_A - 42.0) / 92.0)))); + double D = + Math.max(0.0, Math.min(1.0, vc[VC_F] * (1.0 - (1.0 / 3.6) * Math.pow(Math.E, (-L_A - 42.0) / 92.0)))); double Yw = xyz_w[1]; double[] RGB_c = new double[] { - (D * Yw / RGB_w[0]) + (1.0 - D), - (D * Yw / RGB_w[1]) + (1.0 - D), - (D * Yw / RGB_w[2]) + (1.0 - D), + (D * Yw / RGB_w[0]) + (1.0 - D), (D * Yw / RGB_w[1]) + (1.0 - D), (D * Yw / RGB_w[2]) + (1.0 - D), }; // calculate increase in brightness and colorfulness caused by brighter viewing environments double L_Ax5 = 5.0 * L_A; double k = 1.0 / (L_Ax5 + 1.0); double kpow4 = Math.pow(k, 4.0); - vc[VC_F_L] = 0.2 * kpow4 * (L_Ax5) + 0.1 * Math.pow(1.0 - kpow4, 2.0) * Math.pow(L_Ax5, 1.0/3.0); + vc[VC_F_L] = 0.2 * kpow4 * (L_Ax5) + 0.1 * Math.pow(1.0 - kpow4, 2.0) * Math.pow(L_Ax5, 1.0 / 3.0); // calculate response compression on J and C caused by background lightness. vc[VC_N] = Y_b / Yw; vc[VC_Z] = 1.48 + Math.sqrt(vc[VC_N]); vc[VC_N_BB] = 0.725 * Math.pow(1.0 / vc[VC_N], 0.2); - vc[VC_N_CB] = vc[VC_N_BB]; // chromatic contrast factors (calculate increase in J, Q, and C caused by dark backgrounds) + vc[VC_N_CB] = vc[ + VC_N_BB]; // chromatic contrast factors (calculate increase in J, Q, and C caused by dark backgrounds) // calculate achromatic response to white double[] RGB_wc = new double[] {RGB_c[0] * RGB_w[0], RGB_c[1] * RGB_w[1], RGB_c[2] * RGB_w[2]}; double[] RGBPrime_w = CAT02toHPE(RGB_wc); double[] RGBPrime_aw = new double[3]; - for(int channel = 0; channel < RGBPrime_w.length; channel++) { - if(RGBPrime_w[channel] >= 0) { + for (int channel = 0; channel < RGBPrime_w.length; channel++) { + if (RGBPrime_w[channel] >= 0) { double n = Math.pow(vc[VC_F_L] * RGBPrime_w[channel] / 100.0, 0.42); RGBPrime_aw[channel] = 400.0 * n / (n + 27.13) + 0.1; } else { @@ -660,7 +685,7 @@ double x = vr * 0.4124564 + vg * 0.3575761 + vb * 0.1804375; double y = vr * 0.2126729 + vg * 0.7151522 + vb * 0.0721750; double z = vr * 0.0193339 + vg * 0.1191920 + vb * 0.9503041; - return new double[] { x, y, z }; + return new double[] {x, y, z}; } private static double pivotRgb(double n) { @@ -674,11 +699,12 @@ double l = 116.0 * fy - 16.0; double a = 500.0 * (fx - fy); double b = 200.0 * (fy - fz); - return new double[] { l, a, b }; + return new double[] {l, a, b}; } private static final double epsilon = 216.0 / 24389.0; private static final double kappa = 24389.0 / 27.0; + private static double pivotXyz(double n) { return n > epsilon ? Math.cbrt(n) : (kappa * n + 16) / 116; } @@ -686,5 +712,4 @@ private static double sqr(double n) { return n * n; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Curses.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Curses.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Curses.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Curses.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -29,8 +29,7 @@ private static final int IFTE_THEN = 2; private static final int IFTE_ELSE = 3; - private Curses() { - } + private Curses() {} /** * Print the given terminal capabilities @@ -95,9 +94,9 @@ case 'n': out.append('\n'); break; -// case 'l': -// rawPrint('\l'); -// break; + // case 'l': + // rawPrint('\l'); + // break; case 'r': if (exec) { out.append('\r'); @@ -138,7 +137,7 @@ case '^': ch = str.charAt(index++); if (exec) { - out.append((char)(ch - '@')); + out.append((char) (ch - '@')); } break; case '%': @@ -195,7 +194,8 @@ break; case '{': int start = index; - while (str.charAt(index++) != '}') ; + while (str.charAt(index++) != '}') + ; if (exec) { int v = Integer.parseInt(str.substring(start, index - 1)); stack.push(v); @@ -364,10 +364,18 @@ int cnv; while ("-+# ".indexOf(ch) >= 0) { switch (ch) { - case '-': left = true; break; - case '+': plus = true; break; - case '#': alternate = true; break; - case ' ': space = true; break; + case '-': + left = true; + break; + case '+': + plus = true; + break; + case '#': + alternate = true; + break; + case ' ': + space = true; + break; } ch = str.charAt(index++); } @@ -473,5 +481,4 @@ return Integer.parseInt(pop.toString()); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/DiffHelper.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/DiffHelper.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/DiffHelper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/DiffHelper.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -25,7 +25,9 @@ * which means: delete "Hello", add "Goodbye" and keep " world." */ public enum Operation { - DELETE, INSERT, EQUAL + DELETE, + INSERT, + EQUAL } /** @@ -86,16 +88,13 @@ && text1.charAt(commonStart) == text2.charAt(commonStart) && text1.styleAt(commonStart).equals(text2.styleAt(commonStart))) { if (text1.isHidden(commonStart)) { - if (startHiddenRange < 0) - startHiddenRange = commonStart; - } else - startHiddenRange = -1; + if (startHiddenRange < 0) startHiddenRange = commonStart; + } else startHiddenRange = -1; commonStart++; } if (startHiddenRange >= 0 - && ((l1 > commonStart && text1.isHidden(commonStart)) - || (l2 > commonStart && text2.isHidden(commonStart)))) - commonStart = startHiddenRange; + && ((l1 > commonStart && text1.isHidden(commonStart)) + || (l2 > commonStart && text2.isHidden(commonStart)))) commonStart = startHiddenRange; startHiddenRange = -1; int commonEnd = 0; @@ -103,32 +102,24 @@ && text1.charAt(l1 - commonEnd - 1) == text2.charAt(l2 - commonEnd - 1) && text1.styleAt(l1 - commonEnd - 1).equals(text2.styleAt(l2 - commonEnd - 1))) { if (text1.isHidden(l1 - commonEnd - 1)) { - if (startHiddenRange < 0) - startHiddenRange = commonEnd; - } else - startHiddenRange = -1; + if (startHiddenRange < 0) startHiddenRange = commonEnd; + } else startHiddenRange = -1; commonEnd++; } - if (startHiddenRange >= 0) - commonEnd = startHiddenRange; + if (startHiddenRange >= 0) commonEnd = startHiddenRange; LinkedList diffs = new LinkedList<>(); if (commonStart > 0) { - diffs.add(new Diff(DiffHelper.Operation.EQUAL, - text1.subSequence(0, commonStart))); + diffs.add(new Diff(DiffHelper.Operation.EQUAL, text1.subSequence(0, commonStart))); } if (l2 > commonStart + commonEnd) { - diffs.add(new Diff(DiffHelper.Operation.INSERT, - text2.subSequence(commonStart, l2 - commonEnd))); + diffs.add(new Diff(DiffHelper.Operation.INSERT, text2.subSequence(commonStart, l2 - commonEnd))); } if (l1 > commonStart + commonEnd) { - diffs.add(new Diff(DiffHelper.Operation.DELETE, - text1.subSequence(commonStart, l1 - commonEnd))); + diffs.add(new Diff(DiffHelper.Operation.DELETE, text1.subSequence(commonStart, l1 - commonEnd))); } if (commonEnd > 0) { - diffs.add(new Diff(DiffHelper.Operation.EQUAL, - text1.subSequence(l1 - commonEnd, l1))); + diffs.add(new Diff(DiffHelper.Operation.EQUAL, text1.subSequence(l1 - commonEnd, l1))); } return diffs; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Display.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Display.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Display.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Display.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -37,8 +37,8 @@ protected final boolean fullScreen; protected List oldLines = Collections.emptyList(); protected int cursorPos; - private int columns; - private int columns1; // columns+1 + protected int columns; + protected int columns1; // columns+1 protected int rows; protected boolean reset; protected boolean delayLineWrap; @@ -49,15 +49,15 @@ protected final boolean delayedWrapAtEol; protected final boolean cursorDownIsNewLine; + @SuppressWarnings("this-escape") public Display(Terminal terminal, boolean fullscreen) { this.terminal = terminal; this.fullScreen = fullscreen; this.canScroll = can(Capability.insert_line, Capability.parm_insert_line) - && can(Capability.delete_line, Capability.parm_delete_line); + && can(Capability.delete_line, Capability.parm_delete_line); this.wrapAtEol = terminal.getBooleanCapability(Capability.auto_right_margin); - this.delayedWrapAtEol = this.wrapAtEol - && terminal.getBooleanCapability(Capability.eat_newline_glitch); + this.delayedWrapAtEol = this.wrapAtEol && terminal.getBooleanCapability(Capability.eat_newline_glitch); this.cursorDownIsNewLine = "\n".equals(Curses.tputs(terminal.getStringCapability(Capability.cursor_down))); } @@ -69,18 +69,22 @@ public boolean delayLineWrap() { return delayLineWrap; } - public void setDelayLineWrap(boolean v) { delayLineWrap = v; } + + public void setDelayLineWrap(boolean v) { + delayLineWrap = v; + } public void resize(int rows, int columns) { if (rows == 0 || columns == 0) { - columns = Integer.MAX_VALUE - 1; + columns = 1; rows = 1; } if (this.rows != rows || this.columns != columns) { this.rows = rows; this.columns = columns; this.columns1 = columns + 1; - oldLines = AttributedString.join(AttributedString.EMPTY, oldLines).columnSplitLength(columns, true, delayLineWrap()); + oldLines = AttributedString.join(AttributedString.EMPTY, oldLines) + .columnSplitLength(columns, true, delayLineWrap()); } } @@ -128,7 +132,8 @@ // If dumb display, get rid of ansi sequences now Integer cols = terminal.getNumericCapability(Capability.max_colors); if (cols == null || cols < 8) { - newLines = newLines.stream().map(s -> new AttributedString(s.toString())) + newLines = newLines.stream() + .map(s -> new AttributedString(s.toString())) .collect(Collectors.toList()); } @@ -138,12 +143,13 @@ int nbFooters = 0; // Find common headers and footers int l = newLines.size(); - while (nbHeaders < l - && Objects.equals(newLines.get(nbHeaders), oldLines.get(nbHeaders))) { + while (nbHeaders < l && Objects.equals(newLines.get(nbHeaders), oldLines.get(nbHeaders))) { nbHeaders++; } while (nbFooters < l - nbHeaders - 1 - && Objects.equals(newLines.get(newLines.size() - nbFooters - 1), oldLines.get(oldLines.size() - nbFooters - 1))) { + && Objects.equals( + newLines.get(newLines.size() - nbFooters - 1), + oldLines.get(oldLines.size() - nbFooters - 1))) { nbFooters++; } List o1 = newLines.subList(nbHeaders, newLines.size() - nbFooters); @@ -190,18 +196,14 @@ int numLines = Math.min(rows, Math.max(oldLines.size(), newLines.size())); boolean wrapNeeded = false; while (lineIndex < numLines) { - AttributedString oldLine = - lineIndex < oldLines.size() ? oldLines.get(lineIndex) - : AttributedString.NEWLINE; - AttributedString newLine = - lineIndex < newLines.size() ? newLines.get(lineIndex) - : AttributedString.NEWLINE; + AttributedString oldLine = lineIndex < oldLines.size() ? oldLines.get(lineIndex) : AttributedString.NEWLINE; + AttributedString newLine = lineIndex < newLines.size() ? newLines.get(lineIndex) : AttributedString.NEWLINE; currentPos = lineIndex * columns1; int curCol = currentPos; int oldLength = oldLine.length(); int newLength = newLine.length(); - boolean oldNL = oldLength > 0 && oldLine.charAt(oldLength-1)=='\n'; - boolean newNL = newLength > 0 && newLine.charAt(newLength-1)=='\n'; + boolean oldNL = oldLength > 0 && oldLine.charAt(oldLength - 1) == '\n'; + boolean newNL = newLength > 0 && newLine.charAt(newLength - 1) == '\n'; if (oldNL) { oldLength--; oldLine = oldLine.substring(0, oldLength); @@ -210,9 +212,7 @@ newLength--; newLine = newLine.substring(0, newLength); } - if (wrapNeeded - && lineIndex == (cursorPos + 1) / columns1 - && lineIndex < newLines.size()) { + if (wrapNeeded && lineIndex == (cursorPos + 1) / columns1 && lineIndex < newLines.size()) { // move from right margin to next line's left margin cursorPos++; if (newLength == 0 || newLine.isHidden(0)) { @@ -250,8 +250,7 @@ } break; case INSERT: - if (i <= diffs.size() - 2 - && diffs.get(i + 1).operation == DiffHelper.Operation.EQUAL) { + if (i <= diffs.size() - 2 && diffs.get(i + 1).operation == DiffHelper.Operation.EQUAL) { cursorPos = moveVisualCursorTo(currentPos); if (insertChars(width)) { rawPrint(diff.text); @@ -282,8 +281,7 @@ if (currentPos - curCol >= columns) { continue; } - if (i <= diffs.size() - 2 - && diffs.get(i + 1).operation == DiffHelper.Operation.EQUAL) { + if (i <= diffs.size() - 2 && diffs.get(i + 1).operation == DiffHelper.Operation.EQUAL) { if (currentPos + diffs.get(i + 1).text.columnLength() < columns) { moveVisualCursorTo(currentPos); if (deleteChars(width)) { @@ -305,25 +303,23 @@ } } lineIndex++; - boolean newWrap = ! newNL && lineIndex < newLines.size(); - if (targetCursorPos + 1 == lineIndex * columns1 - && (newWrap || ! delayLineWrap)) - targetCursorPos++; + boolean newWrap = !newNL && lineIndex < newLines.size(); + if (targetCursorPos + 1 == lineIndex * columns1 && (newWrap || !delayLineWrap)) targetCursorPos++; boolean atRight = (cursorPos - curCol) % columns1 == columns; wrapNeeded = false; if (this.delayedWrapAtEol) { - boolean oldWrap = ! oldNL && lineIndex < oldLines.size(); - if (newWrap != oldWrap && ! (oldWrap && cleared)) { - moveVisualCursorTo(lineIndex*columns1-1, newLines); - if (newWrap) - wrapNeeded = true; - else - terminal.puts(Capability.clr_eol); + boolean oldWrap = !oldNL && lineIndex < oldLines.size(); + if (newWrap != oldWrap && !(oldWrap && cleared)) { + moveVisualCursorTo(lineIndex * columns1 - 1, newLines); + if (newWrap) wrapNeeded = true; + else terminal.puts(Capability.clr_eol); } } else if (atRight) { if (this.wrapAtEol) { - terminal.writer().write(" \b"); - cursorPos++; + if (!fullScreen || (fullScreen && lineIndex < numLines)) { + terminal.writer().write(" \b"); + cursorPos++; + } } else { terminal.puts(Capability.carriage_return); // CR / not newline. cursorPos = curCol; @@ -358,8 +354,7 @@ } protected boolean can(Capability single, Capability multi) { - return terminal.getStringCapability(single) != null - || terminal.getStringCapability(multi) != null; + return terminal.getStringCapability(single) != null || terminal.getStringCapability(multi) != null; } protected boolean perform(Capability single, Capability multi, int nb) { @@ -405,7 +400,7 @@ } } } - return max != 0 ? new int[] { start1, start2, max } : null; + return max != 0 ? new int[] {start1, start2, max} : null; } /* @@ -413,8 +408,7 @@ * We're at the right margin if {@code (cursorPos % columns1) == columns}. * This method knows how to move both *from* and *to* the right margin. */ - protected void moveVisualCursorTo(int targetPos, - List newLines) { + protected void moveVisualCursorTo(int targetPos, List newLines) { if (cursorPos != targetPos) { boolean atRight = (targetPos % columns1) == columns; moveVisualCursorTo(targetPos - (atRight ? 1 : 0)); @@ -422,12 +416,11 @@ // There is no portable way to move to the right margin // except by writing a character in the right-most column. int row = targetPos / columns1; - AttributedString lastChar = row >= newLines.size() ? AttributedString.EMPTY - : newLines.get(row).columnSubSequence(columns-1, columns); - if (lastChar.length() == 0) - rawPrint((int) ' '); - else - rawPrint(lastChar); + AttributedString lastChar = row >= newLines.size() + ? AttributedString.EMPTY + : newLines.get(row).columnSubSequence(columns - 1, columns); + if (lastChar.length() == 0) rawPrint((int) ' '); + else rawPrint(lastChar); cursorPos++; } } @@ -499,5 +492,4 @@ public int wcwidth(String str) { return str != null ? AttributedString.fromAnsi(str).columnLength() : 0; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ExecHelper.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ExecHelper.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ExecHelper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ExecHelper.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -22,8 +22,7 @@ */ public final class ExecHelper { - private ExecHelper() { - } + private ExecHelper() {} public static String exec(boolean redirectInput, final String... cmd) throws IOException { Objects.requireNonNull(cmd); @@ -31,7 +30,7 @@ Log.trace("Running: ", cmd); ProcessBuilder pb = new ProcessBuilder(cmd); if (OSUtils.IS_AIX) { - Map env = pb.environment(); + Map env = pb.environment(); env.put("PATH", "/opt/freeware/bin:" + env.get("PATH")); env.put("LANG", "C"); env.put("LC_ALL", "C"); @@ -90,4 +89,3 @@ } } } - diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/FastBufferedOutputStream.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/FastBufferedOutputStream.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/FastBufferedOutputStream.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/FastBufferedOutputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2009-2023, the original author(s). + * + * This software is distributable under the BSD license. See the terms of the + * BSD license in the documentation provided with this software. + * + * https://opensource.org/licenses/BSD-3-Clause + */ +package jdk.internal.org.jline.utils; + +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * A simple buffering output stream with no synchronization. + */ +public class FastBufferedOutputStream extends FilterOutputStream { + + protected final byte[] buf = new byte[8192]; + protected int count; + + public FastBufferedOutputStream(OutputStream out) { + super(out); + } + + @Override + public void write(int b) throws IOException { + if (count >= buf.length) { + flushBuffer(); + } + buf[count++] = (byte) b; + } + + @Override + public void write(byte b[], int off, int len) throws IOException { + if (len >= buf.length) { + flushBuffer(); + out.write(b, off, len); + return; + } + if (len > buf.length - count) { + flushBuffer(); + } + System.arraycopy(b, off, buf, count, len); + count += len; + } + + private void flushBuffer() throws IOException { + if (count > 0) { + out.write(buf, 0, count); + count = 0; + } + } + + @Override + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } +} diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InfoCmp.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InfoCmp.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InfoCmp.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InfoCmp.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2019, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -28,476 +28,474 @@ private static final Map CAPS = new HashMap<>(); - private InfoCmp() { - } + private InfoCmp() {} @SuppressWarnings("unused") public enum Capability { - - auto_left_margin, // auto_left_margin, bw, bw - auto_right_margin, // auto_right_margin, am, am - back_color_erase, // back_color_erase, bce, ut - can_change, // can_change, ccc, cc - ceol_standout_glitch, // ceol_standout_glitch, xhp, xs - col_addr_glitch, // col_addr_glitch, xhpa, YA - cpi_changes_res, // cpi_changes_res, cpix, YF - cr_cancels_micro_mode, // cr_cancels_micro_mode, crxm, YB - dest_tabs_magic_smso, // dest_tabs_magic_smso, xt, xt - eat_newline_glitch, // eat_newline_glitch, xenl, xn - erase_overstrike, // erase_overstrike, eo, eo - generic_type, // generic_type, gn, gn - hard_copy, // hard_copy, hc, hc - hard_cursor, // hard_cursor, chts, HC - has_meta_key, // has_meta_key, km, km - has_print_wheel, // has_print_wheel, daisy, YC - has_status_line, // has_status_line, hs, hs - hue_lightness_saturation, // hue_lightness_saturation, hls, hl - insert_null_glitch, // insert_null_glitch, in, in - lpi_changes_res, // lpi_changes_res, lpix, YG - memory_above, // memory_above, da, da - memory_below, // memory_below, db, db - move_insert_mode, // move_insert_mode, mir, mi - move_standout_mode, // move_standout_mode, msgr, ms - needs_xon_xoff, // needs_xon_xoff, nxon, nx - no_esc_ctlc, // no_esc_ctlc, xsb, xb - no_pad_char, // no_pad_char, npc, NP - non_dest_scroll_region, // non_dest_scroll_region, ndscr, ND - non_rev_rmcup, // non_rev_rmcup, nrrmc, NR - over_strike, // over_strike, os, os - prtr_silent, // prtr_silent, mc5i, 5i - row_addr_glitch, // row_addr_glitch, xvpa, YD - semi_auto_right_margin, // semi_auto_right_margin, sam, YE - status_line_esc_ok, // status_line_esc_ok, eslok, es - tilde_glitch, // tilde_glitch, hz, hz - transparent_underline, // transparent_underline, ul, ul - xon_xoff, // xon_xoff, xon, xo - columns, // columns, cols, co - init_tabs, // init_tabs, it, it - label_height, // label_height, lh, lh - label_width, // label_width, lw, lw - lines, // lines, lines, li - lines_of_memory, // lines_of_memory, lm, lm - magic_cookie_glitch, // magic_cookie_glitch, xmc, sg - max_attributes, // max_attributes, ma, ma - max_colors, // max_colors, colors, Co - max_pairs, // max_pairs, pairs, pa - maximum_windows, // maximum_windows, wnum, MW - no_color_video, // no_color_video, ncv, NC - num_labels, // num_labels, nlab, Nl - padding_baud_rate, // padding_baud_rate, pb, pb - virtual_terminal, // virtual_terminal, vt, vt - width_status_line, // width_status_line, wsl, ws - bit_image_entwining, // bit_image_entwining, bitwin, Yo - bit_image_type, // bit_image_type, bitype, Yp - buffer_capacity, // buffer_capacity, bufsz, Ya - buttons, // buttons, btns, BT - dot_horz_spacing, // dot_horz_spacing, spinh, Yc - dot_vert_spacing, // dot_vert_spacing, spinv, Yb - max_micro_address, // max_micro_address, maddr, Yd - max_micro_jump, // max_micro_jump, mjump, Ye - micro_col_size, // micro_col_size, mcs, Yf - micro_line_size, // micro_line_size, mls, Yg - number_of_pins, // number_of_pins, npins, Yh - output_res_char, // output_res_char, orc, Yi - output_res_horz_inch, // output_res_horz_inch, orhi, Yk - output_res_line, // output_res_line, orl, Yj - output_res_vert_inch, // output_res_vert_inch, orvi, Yl - print_rate, // print_rate, cps, Ym - wide_char_size, // wide_char_size, widcs, Yn - acs_chars, // acs_chars, acsc, ac - back_tab, // back_tab, cbt, bt - bell, // bell, bel, bl - carriage_return, // carriage_return, cr, cr - change_char_pitch, // change_char_pitch, cpi, ZA - change_line_pitch, // change_line_pitch, lpi, ZB - change_res_horz, // change_res_horz, chr, ZC - change_res_vert, // change_res_vert, cvr, ZD - change_scroll_region, // change_scroll_region, csr, cs - char_padding, // char_padding, rmp, rP - clear_all_tabs, // clear_all_tabs, tbc, ct - clear_margins, // clear_margins, mgc, MC - clear_screen, // clear_screen, clear, cl - clr_bol, // clr_bol, el1, cb - clr_eol, // clr_eol, el, ce - clr_eos, // clr_eos, ed, cd - column_address, // column_address, hpa, ch - command_character, // command_character, cmdch, CC - create_window, // create_window, cwin, CW - cursor_address, // cursor_address, cup, cm - cursor_down, // cursor_down, cud1, do - cursor_home, // cursor_home, home, ho - cursor_invisible, // cursor_invisible, civis, vi - cursor_left, // cursor_left, cub1, le - cursor_mem_address, // cursor_mem_address, mrcup, CM - cursor_normal, // cursor_normal, cnorm, ve - cursor_right, // cursor_right, cuf1, nd - cursor_to_ll, // cursor_to_ll, ll, ll - cursor_up, // cursor_up, cuu1, up - cursor_visible, // cursor_visible, cvvis, vs - define_char, // define_char, defc, ZE - delete_character, // delete_character, dch1, dc - delete_line, // delete_line, dl1, dl - dial_phone, // dial_phone, dial, DI - dis_status_line, // dis_status_line, dsl, ds - display_clock, // display_clock, dclk, DK - down_half_line, // down_half_line, hd, hd - ena_acs, // ena_acs, enacs, eA - enter_alt_charset_mode, // enter_alt_charset_mode, smacs, as - enter_am_mode, // enter_am_mode, smam, SA - enter_blink_mode, // enter_blink_mode, blink, mb - enter_bold_mode, // enter_bold_mode, bold, md - enter_ca_mode, // enter_ca_mode, smcup, ti - enter_delete_mode, // enter_delete_mode, smdc, dm - enter_dim_mode, // enter_dim_mode, dim, mh - enter_doublewide_mode, // enter_doublewide_mode, swidm, ZF - enter_draft_quality, // enter_draft_quality, sdrfq, ZG - enter_insert_mode, // enter_insert_mode, smir, im - enter_italics_mode, // enter_italics_mode, sitm, ZH - enter_leftward_mode, // enter_leftward_mode, slm, ZI - enter_micro_mode, // enter_micro_mode, smicm, ZJ - enter_near_letter_quality, // enter_near_letter_quality, snlq, ZK - enter_normal_quality, // enter_normal_quality, snrmq, ZL - enter_protected_mode, // enter_protected_mode, prot, mp - enter_reverse_mode, // enter_reverse_mode, rev, mr - enter_secure_mode, // enter_secure_mode, invis, mk - enter_shadow_mode, // enter_shadow_mode, sshm, ZM - enter_standout_mode, // enter_standout_mode, smso, so - enter_subscript_mode, // enter_subscript_mode, ssubm, ZN - enter_superscript_mode, // enter_superscript_mode, ssupm, ZO - enter_underline_mode, // enter_underline_mode, smul, us - enter_upward_mode, // enter_upward_mode, sum, ZP - enter_xon_mode, // enter_xon_mode, smxon, SX - erase_chars, // erase_chars, ech, ec - exit_alt_charset_mode, // exit_alt_charset_mode, rmacs, ae - exit_am_mode, // exit_am_mode, rmam, RA - exit_attribute_mode, // exit_attribute_mode, sgr0, me - exit_ca_mode, // exit_ca_mode, rmcup, te - exit_delete_mode, // exit_delete_mode, rmdc, ed - exit_doublewide_mode, // exit_doublewide_mode, rwidm, ZQ - exit_insert_mode, // exit_insert_mode, rmir, ei - exit_italics_mode, // exit_italics_mode, ritm, ZR - exit_leftward_mode, // exit_leftward_mode, rlm, ZS - exit_micro_mode, // exit_micro_mode, rmicm, ZT - exit_shadow_mode, // exit_shadow_mode, rshm, ZU - exit_standout_mode, // exit_standout_mode, rmso, se - exit_subscript_mode, // exit_subscript_mode, rsubm, ZV - exit_superscript_mode, // exit_superscript_mode, rsupm, ZW - exit_underline_mode, // exit_underline_mode, rmul, ue - exit_upward_mode, // exit_upward_mode, rum, ZX - exit_xon_mode, // exit_xon_mode, rmxon, RX - fixed_pause, // fixed_pause, pause, PA - flash_hook, // flash_hook, hook, fh - flash_screen, // flash_screen, flash, vb - form_feed, // form_feed, ff, ff - from_status_line, // from_status_line, fsl, fs - goto_window, // goto_window, wingo, WG - hangup, // hangup, hup, HU - init_1string, // init_1string, is1, i1 - init_2string, // init_2string, is2, is - init_3string, // init_3string, is3, i3 - init_file, // init_file, if, if - init_prog, // init_prog, iprog, iP - initialize_color, // initialize_color, initc, Ic - initialize_pair, // initialize_pair, initp, Ip - insert_character, // insert_character, ich1, ic - insert_line, // insert_line, il1, al - insert_padding, // insert_padding, ip, ip - key_a1, // key_a1, ka1, K1 - key_a3, // key_a3, ka3, K3 - key_b2, // key_b2, kb2, K2 - key_backspace, // key_backspace, kbs, kb - key_beg, // key_beg, kbeg, @1 - key_btab, // key_btab, kcbt, kB - key_c1, // key_c1, kc1, K4 - key_c3, // key_c3, kc3, K5 - key_cancel, // key_cancel, kcan, @2 - key_catab, // key_catab, ktbc, ka - key_clear, // key_clear, kclr, kC - key_close, // key_close, kclo, @3 - key_command, // key_command, kcmd, @4 - key_copy, // key_copy, kcpy, @5 - key_create, // key_create, kcrt, @6 - key_ctab, // key_ctab, kctab, kt - key_dc, // key_dc, kdch1, kD - key_dl, // key_dl, kdl1, kL - key_down, // key_down, kcud1, kd - key_eic, // key_eic, krmir, kM - key_end, // key_end, kend, @7 - key_enter, // key_enter, kent, @8 - key_eol, // key_eol, kel, kE - key_eos, // key_eos, ked, kS - key_exit, // key_exit, kext, @9 - key_f0, // key_f0, kf0, k0 - key_f1, // key_f1, kf1, k1 - key_f10, // key_f10, kf10, k; - key_f11, // key_f11, kf11, F1 - key_f12, // key_f12, kf12, F2 - key_f13, // key_f13, kf13, F3 - key_f14, // key_f14, kf14, F4 - key_f15, // key_f15, kf15, F5 - key_f16, // key_f16, kf16, F6 - key_f17, // key_f17, kf17, F7 - key_f18, // key_f18, kf18, F8 - key_f19, // key_f19, kf19, F9 - key_f2, // key_f2, kf2, k2 - key_f20, // key_f20, kf20, FA - key_f21, // key_f21, kf21, FB - key_f22, // key_f22, kf22, FC - key_f23, // key_f23, kf23, FD - key_f24, // key_f24, kf24, FE - key_f25, // key_f25, kf25, FF - key_f26, // key_f26, kf26, FG - key_f27, // key_f27, kf27, FH - key_f28, // key_f28, kf28, FI - key_f29, // key_f29, kf29, FJ - key_f3, // key_f3, kf3, k3 - key_f30, // key_f30, kf30, FK - key_f31, // key_f31, kf31, FL - key_f32, // key_f32, kf32, FM - key_f33, // key_f33, kf33, FN - key_f34, // key_f34, kf34, FO - key_f35, // key_f35, kf35, FP - key_f36, // key_f36, kf36, FQ - key_f37, // key_f37, kf37, FR - key_f38, // key_f38, kf38, FS - key_f39, // key_f39, kf39, FT - key_f4, // key_f4, kf4, k4 - key_f40, // key_f40, kf40, FU - key_f41, // key_f41, kf41, FV - key_f42, // key_f42, kf42, FW - key_f43, // key_f43, kf43, FX - key_f44, // key_f44, kf44, FY - key_f45, // key_f45, kf45, FZ - key_f46, // key_f46, kf46, Fa - key_f47, // key_f47, kf47, Fb - key_f48, // key_f48, kf48, Fc - key_f49, // key_f49, kf49, Fd - key_f5, // key_f5, kf5, k5 - key_f50, // key_f50, kf50, Fe - key_f51, // key_f51, kf51, Ff - key_f52, // key_f52, kf52, Fg - key_f53, // key_f53, kf53, Fh - key_f54, // key_f54, kf54, Fi - key_f55, // key_f55, kf55, Fj - key_f56, // key_f56, kf56, Fk - key_f57, // key_f57, kf57, Fl - key_f58, // key_f58, kf58, Fm - key_f59, // key_f59, kf59, Fn - key_f6, // key_f6, kf6, k6 - key_f60, // key_f60, kf60, Fo - key_f61, // key_f61, kf61, Fp - key_f62, // key_f62, kf62, Fq - key_f63, // key_f63, kf63, Fr - key_f7, // key_f7, kf7, k7 - key_f8, // key_f8, kf8, k8 - key_f9, // key_f9, kf9, k9 - key_find, // key_find, kfnd, @0 - key_help, // key_help, khlp, %1 - key_home, // key_home, khome, kh - key_ic, // key_ic, kich1, kI - key_il, // key_il, kil1, kA - key_left, // key_left, kcub1, kl - key_ll, // key_ll, kll, kH - key_mark, // key_mark, kmrk, %2 - key_message, // key_message, kmsg, %3 - key_move, // key_move, kmov, %4 - key_next, // key_next, knxt, %5 - key_npage, // key_npage, knp, kN - key_open, // key_open, kopn, %6 - key_options, // key_options, kopt, %7 - key_ppage, // key_ppage, kpp, kP - key_previous, // key_previous, kprv, %8 - key_print, // key_print, kprt, %9 - key_redo, // key_redo, krdo, %0 - key_reference, // key_reference, kref, &1 - key_refresh, // key_refresh, krfr, &2 - key_replace, // key_replace, krpl, &3 - key_restart, // key_restart, krst, &4 - key_resume, // key_resume, kres, &5 - key_right, // key_right, kcuf1, kr - key_save, // key_save, ksav, &6 - key_sbeg, // key_sbeg, kBEG, &9 - key_scancel, // key_scancel, kCAN, &0 - key_scommand, // key_scommand, kCMD, *1 - key_scopy, // key_scopy, kCPY, *2 - key_screate, // key_screate, kCRT, *3 - key_sdc, // key_sdc, kDC, *4 - key_sdl, // key_sdl, kDL, *5 - key_select, // key_select, kslt, *6 - key_send, // key_send, kEND, *7 - key_seol, // key_seol, kEOL, *8 - key_sexit, // key_sexit, kEXT, *9 - key_sf, // key_sf, kind, kF - key_sfind, // key_sfind, kFND, *0 - key_shelp, // key_shelp, kHLP, #1 - key_shome, // key_shome, kHOM, #2 - key_sic, // key_sic, kIC, #3 - key_sleft, // key_sleft, kLFT, #4 - key_smessage, // key_smessage, kMSG, %a - key_smove, // key_smove, kMOV, %b - key_snext, // key_snext, kNXT, %c - key_soptions, // key_soptions, kOPT, %d - key_sprevious, // key_sprevious, kPRV, %e - key_sprint, // key_sprint, kPRT, %f - key_sr, // key_sr, kri, kR - key_sredo, // key_sredo, kRDO, %g - key_sreplace, // key_sreplace, kRPL, %h - key_sright, // key_sright, kRIT, %i - key_srsume, // key_srsume, kRES, %j - key_ssave, // key_ssave, kSAV, !1 - key_ssuspend, // key_ssuspend, kSPD, !2 - key_stab, // key_stab, khts, kT - key_sundo, // key_sundo, kUND, !3 - key_suspend, // key_suspend, kspd, &7 - key_undo, // key_undo, kund, &8 - key_up, // key_up, kcuu1, ku - keypad_local, // keypad_local, rmkx, ke - keypad_xmit, // keypad_xmit, smkx, ks - lab_f0, // lab_f0, lf0, l0 - lab_f1, // lab_f1, lf1, l1 - lab_f10, // lab_f10, lf10, la - lab_f2, // lab_f2, lf2, l2 - lab_f3, // lab_f3, lf3, l3 - lab_f4, // lab_f4, lf4, l4 - lab_f5, // lab_f5, lf5, l5 - lab_f6, // lab_f6, lf6, l6 - lab_f7, // lab_f7, lf7, l7 - lab_f8, // lab_f8, lf8, l8 - lab_f9, // lab_f9, lf9, l9 - label_format, // label_format, fln, Lf - label_off, // label_off, rmln, LF - label_on, // label_on, smln, LO - meta_off, // meta_off, rmm, mo - meta_on, // meta_on, smm, mm - micro_column_address, // micro_column_address, mhpa, ZY - micro_down, // micro_down, mcud1, ZZ - micro_left, // micro_left, mcub1, Za - micro_right, // micro_right, mcuf1, Zb - micro_row_address, // micro_row_address, mvpa, Zc - micro_up, // micro_up, mcuu1, Zd - newline, // newline, nel, nw - order_of_pins, // order_of_pins, porder, Ze - orig_colors, // orig_colors, oc, oc - orig_pair, // orig_pair, op, op - pad_char, // pad_char, pad, pc - parm_dch, // parm_dch, dch, DC - parm_delete_line, // parm_delete_line, dl, DL - parm_down_cursor, // parm_down_cursor, cud, DO - parm_down_micro, // parm_down_micro, mcud, Zf - parm_ich, // parm_ich, ich, IC - parm_index, // parm_index, indn, SF - parm_insert_line, // parm_insert_line, il, AL - parm_left_cursor, // parm_left_cursor, cub, LE - parm_left_micro, // parm_left_micro, mcub, Zg - parm_right_cursor, // parm_right_cursor, cuf, RI - parm_right_micro, // parm_right_micro, mcuf, Zh - parm_rindex, // parm_rindex, rin, SR - parm_up_cursor, // parm_up_cursor, cuu, UP - parm_up_micro, // parm_up_micro, mcuu, Zi - pkey_key, // pkey_key, pfkey, pk - pkey_local, // pkey_local, pfloc, pl - pkey_xmit, // pkey_xmit, pfx, px - plab_norm, // plab_norm, pln, pn - print_screen, // print_screen, mc0, ps - prtr_non, // prtr_non, mc5p, pO - prtr_off, // prtr_off, mc4, pf - prtr_on, // prtr_on, mc5, po - pulse, // pulse, pulse, PU - quick_dial, // quick_dial, qdial, QD - remove_clock, // remove_clock, rmclk, RC - repeat_char, // repeat_char, rep, rp - req_for_input, // req_for_input, rfi, RF - reset_1string, // reset_1string, rs1, r1 - reset_2string, // reset_2string, rs2, r2 - reset_3string, // reset_3string, rs3, r3 - reset_file, // reset_file, rf, rf - restore_cursor, // restore_cursor, rc, rc - row_address, // row_address, vpa, cv - save_cursor, // save_cursor, sc, sc - scroll_forward, // scroll_forward, ind, sf - scroll_reverse, // scroll_reverse, ri, sr - select_char_set, // select_char_set, scs, Zj - set_attributes, // set_attributes, sgr, sa - set_background, // set_background, setb, Sb - set_bottom_margin, // set_bottom_margin, smgb, Zk - set_bottom_margin_parm, // set_bottom_margin_parm, smgbp, Zl - set_clock, // set_clock, sclk, SC - set_color_pair, // set_color_pair, scp, sp - set_foreground, // set_foreground, setf, Sf - set_left_margin, // set_left_margin, smgl, ML - set_left_margin_parm, // set_left_margin_parm, smglp, Zm - set_right_margin, // set_right_margin, smgr, MR - set_right_margin_parm, // set_right_margin_parm, smgrp, Zn - set_tab, // set_tab, hts, st - set_top_margin, // set_top_margin, smgt, Zo - set_top_margin_parm, // set_top_margin_parm, smgtp, Zp - set_window, // set_window, wind, wi - start_bit_image, // start_bit_image, sbim, Zq - start_char_set_def, // start_char_set_def, scsd, Zr - stop_bit_image, // stop_bit_image, rbim, Zs - stop_char_set_def, // stop_char_set_def, rcsd, Zt - subscript_characters, // subscript_characters, subcs, Zu - superscript_characters, // superscript_characters, supcs, Zv - tab, // tab, ht, ta - these_cause_cr, // these_cause_cr, docr, Zw - to_status_line, // to_status_line, tsl, ts - tone, // tone, tone, TO - underline_char, // underline_char, uc, uc - up_half_line, // up_half_line, hu, hu - user0, // user0, u0, u0 - user1, // user1, u1, u1 - user2, // user2, u2, u2 - user3, // user3, u3, u3 - user4, // user4, u4, u4 - user5, // user5, u5, u5 - user6, // user6, u6, u6 - user7, // user7, u7, u7 - user8, // user8, u8, u8 - user9, // user9, u9, u9 - wait_tone, // wait_tone, wait, WA - xoff_character, // xoff_character, xoffc, XF - xon_character, // xon_character, xonc, XN - zero_motion, // zero_motion, zerom, Zx - alt_scancode_esc, // alt_scancode_esc, scesa, S8 - bit_image_carriage_return, // bit_image_carriage_return, bicr, Yv - bit_image_newline, // bit_image_newline, binel, Zz - bit_image_repeat, // bit_image_repeat, birep, Xy - char_set_names, // char_set_names, csnm, Zy - code_set_init, // code_set_init, csin, ci - color_names, // color_names, colornm, Yw - define_bit_image_region, // define_bit_image_region, defbi, Yx - device_type, // device_type, devt, dv - display_pc_char, // display_pc_char, dispc, S1 - end_bit_image_region, // end_bit_image_region, endbi, Yy - enter_pc_charset_mode, // enter_pc_charset_mode, smpch, S2 - enter_scancode_mode, // enter_scancode_mode, smsc, S4 - exit_pc_charset_mode, // exit_pc_charset_mode, rmpch, S3 - exit_scancode_mode, // exit_scancode_mode, rmsc, S5 - get_mouse, // get_mouse, getm, Gm - key_mouse, // key_mouse, kmous, Km - mouse_info, // mouse_info, minfo, Mi - pc_term_options, // pc_term_options, pctrm, S6 - pkey_plab, // pkey_plab, pfxl, xl - req_mouse_pos, // req_mouse_pos, reqmp, RQ - scancode_escape, // scancode_escape, scesc, S7 - set0_des_seq, // set0_des_seq, s0ds, s0 - set1_des_seq, // set1_des_seq, s1ds, s1 - set2_des_seq, // set2_des_seq, s2ds, s2 - set3_des_seq, // set3_des_seq, s3ds, s3 - set_a_background, // set_a_background, setab, AB - set_a_foreground, // set_a_foreground, setaf, AF - set_color_band, // set_color_band, setcolor, Yz - set_lr_margin, // set_lr_margin, smglr, ML - set_page_length, // set_page_length, slines, YZ - set_tb_margin, // set_tb_margin, smgtb, MT - enter_horizontal_hl_mode, // enter_horizontal_hl_mode, ehhlm, Xh - enter_left_hl_mode, // enter_left_hl_mode, elhlm, Xl - enter_low_hl_mode, // enter_low_hl_mode, elohlm, Xo - enter_right_hl_mode, // enter_right_hl_mode, erhlm, Xr - enter_top_hl_mode, // enter_top_hl_mode, ethlm, Xt - enter_vertical_hl_mode, // enter_vertical_hl_mode, evhlm, Xv - set_a_attributes, // set_a_attributes, sgr1, sA - set_pglen_inch, // set_pglen_inch, slength, sL) + auto_left_margin, // auto_left_margin, bw, bw + auto_right_margin, // auto_right_margin, am, am + back_color_erase, // back_color_erase, bce, ut + can_change, // can_change, ccc, cc + ceol_standout_glitch, // ceol_standout_glitch, xhp, xs + col_addr_glitch, // col_addr_glitch, xhpa, YA + cpi_changes_res, // cpi_changes_res, cpix, YF + cr_cancels_micro_mode, // cr_cancels_micro_mode, crxm, YB + dest_tabs_magic_smso, // dest_tabs_magic_smso, xt, xt + eat_newline_glitch, // eat_newline_glitch, xenl, xn + erase_overstrike, // erase_overstrike, eo, eo + generic_type, // generic_type, gn, gn + hard_copy, // hard_copy, hc, hc + hard_cursor, // hard_cursor, chts, HC + has_meta_key, // has_meta_key, km, km + has_print_wheel, // has_print_wheel, daisy, YC + has_status_line, // has_status_line, hs, hs + hue_lightness_saturation, // hue_lightness_saturation, hls, hl + insert_null_glitch, // insert_null_glitch, in, in + lpi_changes_res, // lpi_changes_res, lpix, YG + memory_above, // memory_above, da, da + memory_below, // memory_below, db, db + move_insert_mode, // move_insert_mode, mir, mi + move_standout_mode, // move_standout_mode, msgr, ms + needs_xon_xoff, // needs_xon_xoff, nxon, nx + no_esc_ctlc, // no_esc_ctlc, xsb, xb + no_pad_char, // no_pad_char, npc, NP + non_dest_scroll_region, // non_dest_scroll_region, ndscr, ND + non_rev_rmcup, // non_rev_rmcup, nrrmc, NR + over_strike, // over_strike, os, os + prtr_silent, // prtr_silent, mc5i, 5i + row_addr_glitch, // row_addr_glitch, xvpa, YD + semi_auto_right_margin, // semi_auto_right_margin, sam, YE + status_line_esc_ok, // status_line_esc_ok, eslok, es + tilde_glitch, // tilde_glitch, hz, hz + transparent_underline, // transparent_underline, ul, ul + xon_xoff, // xon_xoff, xon, xo + columns, // columns, cols, co + init_tabs, // init_tabs, it, it + label_height, // label_height, lh, lh + label_width, // label_width, lw, lw + lines, // lines, lines, li + lines_of_memory, // lines_of_memory, lm, lm + magic_cookie_glitch, // magic_cookie_glitch, xmc, sg + max_attributes, // max_attributes, ma, ma + max_colors, // max_colors, colors, Co + max_pairs, // max_pairs, pairs, pa + maximum_windows, // maximum_windows, wnum, MW + no_color_video, // no_color_video, ncv, NC + num_labels, // num_labels, nlab, Nl + padding_baud_rate, // padding_baud_rate, pb, pb + virtual_terminal, // virtual_terminal, vt, vt + width_status_line, // width_status_line, wsl, ws + bit_image_entwining, // bit_image_entwining, bitwin, Yo + bit_image_type, // bit_image_type, bitype, Yp + buffer_capacity, // buffer_capacity, bufsz, Ya + buttons, // buttons, btns, BT + dot_horz_spacing, // dot_horz_spacing, spinh, Yc + dot_vert_spacing, // dot_vert_spacing, spinv, Yb + max_micro_address, // max_micro_address, maddr, Yd + max_micro_jump, // max_micro_jump, mjump, Ye + micro_col_size, // micro_col_size, mcs, Yf + micro_line_size, // micro_line_size, mls, Yg + number_of_pins, // number_of_pins, npins, Yh + output_res_char, // output_res_char, orc, Yi + output_res_horz_inch, // output_res_horz_inch, orhi, Yk + output_res_line, // output_res_line, orl, Yj + output_res_vert_inch, // output_res_vert_inch, orvi, Yl + print_rate, // print_rate, cps, Ym + wide_char_size, // wide_char_size, widcs, Yn + acs_chars, // acs_chars, acsc, ac + back_tab, // back_tab, cbt, bt + bell, // bell, bel, bl + carriage_return, // carriage_return, cr, cr + change_char_pitch, // change_char_pitch, cpi, ZA + change_line_pitch, // change_line_pitch, lpi, ZB + change_res_horz, // change_res_horz, chr, ZC + change_res_vert, // change_res_vert, cvr, ZD + change_scroll_region, // change_scroll_region, csr, cs + char_padding, // char_padding, rmp, rP + clear_all_tabs, // clear_all_tabs, tbc, ct + clear_margins, // clear_margins, mgc, MC + clear_screen, // clear_screen, clear, cl + clr_bol, // clr_bol, el1, cb + clr_eol, // clr_eol, el, ce + clr_eos, // clr_eos, ed, cd + column_address, // column_address, hpa, ch + command_character, // command_character, cmdch, CC + create_window, // create_window, cwin, CW + cursor_address, // cursor_address, cup, cm + cursor_down, // cursor_down, cud1, do + cursor_home, // cursor_home, home, ho + cursor_invisible, // cursor_invisible, civis, vi + cursor_left, // cursor_left, cub1, le + cursor_mem_address, // cursor_mem_address, mrcup, CM + cursor_normal, // cursor_normal, cnorm, ve + cursor_right, // cursor_right, cuf1, nd + cursor_to_ll, // cursor_to_ll, ll, ll + cursor_up, // cursor_up, cuu1, up + cursor_visible, // cursor_visible, cvvis, vs + define_char, // define_char, defc, ZE + delete_character, // delete_character, dch1, dc + delete_line, // delete_line, dl1, dl + dial_phone, // dial_phone, dial, DI + dis_status_line, // dis_status_line, dsl, ds + display_clock, // display_clock, dclk, DK + down_half_line, // down_half_line, hd, hd + ena_acs, // ena_acs, enacs, eA + enter_alt_charset_mode, // enter_alt_charset_mode, smacs, as + enter_am_mode, // enter_am_mode, smam, SA + enter_blink_mode, // enter_blink_mode, blink, mb + enter_bold_mode, // enter_bold_mode, bold, md + enter_ca_mode, // enter_ca_mode, smcup, ti + enter_delete_mode, // enter_delete_mode, smdc, dm + enter_dim_mode, // enter_dim_mode, dim, mh + enter_doublewide_mode, // enter_doublewide_mode, swidm, ZF + enter_draft_quality, // enter_draft_quality, sdrfq, ZG + enter_insert_mode, // enter_insert_mode, smir, im + enter_italics_mode, // enter_italics_mode, sitm, ZH + enter_leftward_mode, // enter_leftward_mode, slm, ZI + enter_micro_mode, // enter_micro_mode, smicm, ZJ + enter_near_letter_quality, // enter_near_letter_quality, snlq, ZK + enter_normal_quality, // enter_normal_quality, snrmq, ZL + enter_protected_mode, // enter_protected_mode, prot, mp + enter_reverse_mode, // enter_reverse_mode, rev, mr + enter_secure_mode, // enter_secure_mode, invis, mk + enter_shadow_mode, // enter_shadow_mode, sshm, ZM + enter_standout_mode, // enter_standout_mode, smso, so + enter_subscript_mode, // enter_subscript_mode, ssubm, ZN + enter_superscript_mode, // enter_superscript_mode, ssupm, ZO + enter_underline_mode, // enter_underline_mode, smul, us + enter_upward_mode, // enter_upward_mode, sum, ZP + enter_xon_mode, // enter_xon_mode, smxon, SX + erase_chars, // erase_chars, ech, ec + exit_alt_charset_mode, // exit_alt_charset_mode, rmacs, ae + exit_am_mode, // exit_am_mode, rmam, RA + exit_attribute_mode, // exit_attribute_mode, sgr0, me + exit_ca_mode, // exit_ca_mode, rmcup, te + exit_delete_mode, // exit_delete_mode, rmdc, ed + exit_doublewide_mode, // exit_doublewide_mode, rwidm, ZQ + exit_insert_mode, // exit_insert_mode, rmir, ei + exit_italics_mode, // exit_italics_mode, ritm, ZR + exit_leftward_mode, // exit_leftward_mode, rlm, ZS + exit_micro_mode, // exit_micro_mode, rmicm, ZT + exit_shadow_mode, // exit_shadow_mode, rshm, ZU + exit_standout_mode, // exit_standout_mode, rmso, se + exit_subscript_mode, // exit_subscript_mode, rsubm, ZV + exit_superscript_mode, // exit_superscript_mode, rsupm, ZW + exit_underline_mode, // exit_underline_mode, rmul, ue + exit_upward_mode, // exit_upward_mode, rum, ZX + exit_xon_mode, // exit_xon_mode, rmxon, RX + fixed_pause, // fixed_pause, pause, PA + flash_hook, // flash_hook, hook, fh + flash_screen, // flash_screen, flash, vb + form_feed, // form_feed, ff, ff + from_status_line, // from_status_line, fsl, fs + goto_window, // goto_window, wingo, WG + hangup, // hangup, hup, HU + init_1string, // init_1string, is1, i1 + init_2string, // init_2string, is2, is + init_3string, // init_3string, is3, i3 + init_file, // init_file, if, if + init_prog, // init_prog, iprog, iP + initialize_color, // initialize_color, initc, Ic + initialize_pair, // initialize_pair, initp, Ip + insert_character, // insert_character, ich1, ic + insert_line, // insert_line, il1, al + insert_padding, // insert_padding, ip, ip + key_a1, // key_a1, ka1, K1 + key_a3, // key_a3, ka3, K3 + key_b2, // key_b2, kb2, K2 + key_backspace, // key_backspace, kbs, kb + key_beg, // key_beg, kbeg, @1 + key_btab, // key_btab, kcbt, kB + key_c1, // key_c1, kc1, K4 + key_c3, // key_c3, kc3, K5 + key_cancel, // key_cancel, kcan, @2 + key_catab, // key_catab, ktbc, ka + key_clear, // key_clear, kclr, kC + key_close, // key_close, kclo, @3 + key_command, // key_command, kcmd, @4 + key_copy, // key_copy, kcpy, @5 + key_create, // key_create, kcrt, @6 + key_ctab, // key_ctab, kctab, kt + key_dc, // key_dc, kdch1, kD + key_dl, // key_dl, kdl1, kL + key_down, // key_down, kcud1, kd + key_eic, // key_eic, krmir, kM + key_end, // key_end, kend, @7 + key_enter, // key_enter, kent, @8 + key_eol, // key_eol, kel, kE + key_eos, // key_eos, ked, kS + key_exit, // key_exit, kext, @9 + key_f0, // key_f0, kf0, k0 + key_f1, // key_f1, kf1, k1 + key_f10, // key_f10, kf10, k; + key_f11, // key_f11, kf11, F1 + key_f12, // key_f12, kf12, F2 + key_f13, // key_f13, kf13, F3 + key_f14, // key_f14, kf14, F4 + key_f15, // key_f15, kf15, F5 + key_f16, // key_f16, kf16, F6 + key_f17, // key_f17, kf17, F7 + key_f18, // key_f18, kf18, F8 + key_f19, // key_f19, kf19, F9 + key_f2, // key_f2, kf2, k2 + key_f20, // key_f20, kf20, FA + key_f21, // key_f21, kf21, FB + key_f22, // key_f22, kf22, FC + key_f23, // key_f23, kf23, FD + key_f24, // key_f24, kf24, FE + key_f25, // key_f25, kf25, FF + key_f26, // key_f26, kf26, FG + key_f27, // key_f27, kf27, FH + key_f28, // key_f28, kf28, FI + key_f29, // key_f29, kf29, FJ + key_f3, // key_f3, kf3, k3 + key_f30, // key_f30, kf30, FK + key_f31, // key_f31, kf31, FL + key_f32, // key_f32, kf32, FM + key_f33, // key_f33, kf33, FN + key_f34, // key_f34, kf34, FO + key_f35, // key_f35, kf35, FP + key_f36, // key_f36, kf36, FQ + key_f37, // key_f37, kf37, FR + key_f38, // key_f38, kf38, FS + key_f39, // key_f39, kf39, FT + key_f4, // key_f4, kf4, k4 + key_f40, // key_f40, kf40, FU + key_f41, // key_f41, kf41, FV + key_f42, // key_f42, kf42, FW + key_f43, // key_f43, kf43, FX + key_f44, // key_f44, kf44, FY + key_f45, // key_f45, kf45, FZ + key_f46, // key_f46, kf46, Fa + key_f47, // key_f47, kf47, Fb + key_f48, // key_f48, kf48, Fc + key_f49, // key_f49, kf49, Fd + key_f5, // key_f5, kf5, k5 + key_f50, // key_f50, kf50, Fe + key_f51, // key_f51, kf51, Ff + key_f52, // key_f52, kf52, Fg + key_f53, // key_f53, kf53, Fh + key_f54, // key_f54, kf54, Fi + key_f55, // key_f55, kf55, Fj + key_f56, // key_f56, kf56, Fk + key_f57, // key_f57, kf57, Fl + key_f58, // key_f58, kf58, Fm + key_f59, // key_f59, kf59, Fn + key_f6, // key_f6, kf6, k6 + key_f60, // key_f60, kf60, Fo + key_f61, // key_f61, kf61, Fp + key_f62, // key_f62, kf62, Fq + key_f63, // key_f63, kf63, Fr + key_f7, // key_f7, kf7, k7 + key_f8, // key_f8, kf8, k8 + key_f9, // key_f9, kf9, k9 + key_find, // key_find, kfnd, @0 + key_help, // key_help, khlp, %1 + key_home, // key_home, khome, kh + key_ic, // key_ic, kich1, kI + key_il, // key_il, kil1, kA + key_left, // key_left, kcub1, kl + key_ll, // key_ll, kll, kH + key_mark, // key_mark, kmrk, %2 + key_message, // key_message, kmsg, %3 + key_move, // key_move, kmov, %4 + key_next, // key_next, knxt, %5 + key_npage, // key_npage, knp, kN + key_open, // key_open, kopn, %6 + key_options, // key_options, kopt, %7 + key_ppage, // key_ppage, kpp, kP + key_previous, // key_previous, kprv, %8 + key_print, // key_print, kprt, %9 + key_redo, // key_redo, krdo, %0 + key_reference, // key_reference, kref, &1 + key_refresh, // key_refresh, krfr, &2 + key_replace, // key_replace, krpl, &3 + key_restart, // key_restart, krst, &4 + key_resume, // key_resume, kres, &5 + key_right, // key_right, kcuf1, kr + key_save, // key_save, ksav, &6 + key_sbeg, // key_sbeg, kBEG, &9 + key_scancel, // key_scancel, kCAN, &0 + key_scommand, // key_scommand, kCMD, *1 + key_scopy, // key_scopy, kCPY, *2 + key_screate, // key_screate, kCRT, *3 + key_sdc, // key_sdc, kDC, *4 + key_sdl, // key_sdl, kDL, *5 + key_select, // key_select, kslt, *6 + key_send, // key_send, kEND, *7 + key_seol, // key_seol, kEOL, *8 + key_sexit, // key_sexit, kEXT, *9 + key_sf, // key_sf, kind, kF + key_sfind, // key_sfind, kFND, *0 + key_shelp, // key_shelp, kHLP, #1 + key_shome, // key_shome, kHOM, #2 + key_sic, // key_sic, kIC, #3 + key_sleft, // key_sleft, kLFT, #4 + key_smessage, // key_smessage, kMSG, %a + key_smove, // key_smove, kMOV, %b + key_snext, // key_snext, kNXT, %c + key_soptions, // key_soptions, kOPT, %d + key_sprevious, // key_sprevious, kPRV, %e + key_sprint, // key_sprint, kPRT, %f + key_sr, // key_sr, kri, kR + key_sredo, // key_sredo, kRDO, %g + key_sreplace, // key_sreplace, kRPL, %h + key_sright, // key_sright, kRIT, %i + key_srsume, // key_srsume, kRES, %j + key_ssave, // key_ssave, kSAV, !1 + key_ssuspend, // key_ssuspend, kSPD, !2 + key_stab, // key_stab, khts, kT + key_sundo, // key_sundo, kUND, !3 + key_suspend, // key_suspend, kspd, &7 + key_undo, // key_undo, kund, &8 + key_up, // key_up, kcuu1, ku + keypad_local, // keypad_local, rmkx, ke + keypad_xmit, // keypad_xmit, smkx, ks + lab_f0, // lab_f0, lf0, l0 + lab_f1, // lab_f1, lf1, l1 + lab_f10, // lab_f10, lf10, la + lab_f2, // lab_f2, lf2, l2 + lab_f3, // lab_f3, lf3, l3 + lab_f4, // lab_f4, lf4, l4 + lab_f5, // lab_f5, lf5, l5 + lab_f6, // lab_f6, lf6, l6 + lab_f7, // lab_f7, lf7, l7 + lab_f8, // lab_f8, lf8, l8 + lab_f9, // lab_f9, lf9, l9 + label_format, // label_format, fln, Lf + label_off, // label_off, rmln, LF + label_on, // label_on, smln, LO + meta_off, // meta_off, rmm, mo + meta_on, // meta_on, smm, mm + micro_column_address, // micro_column_address, mhpa, ZY + micro_down, // micro_down, mcud1, ZZ + micro_left, // micro_left, mcub1, Za + micro_right, // micro_right, mcuf1, Zb + micro_row_address, // micro_row_address, mvpa, Zc + micro_up, // micro_up, mcuu1, Zd + newline, // newline, nel, nw + order_of_pins, // order_of_pins, porder, Ze + orig_colors, // orig_colors, oc, oc + orig_pair, // orig_pair, op, op + pad_char, // pad_char, pad, pc + parm_dch, // parm_dch, dch, DC + parm_delete_line, // parm_delete_line, dl, DL + parm_down_cursor, // parm_down_cursor, cud, DO + parm_down_micro, // parm_down_micro, mcud, Zf + parm_ich, // parm_ich, ich, IC + parm_index, // parm_index, indn, SF + parm_insert_line, // parm_insert_line, il, AL + parm_left_cursor, // parm_left_cursor, cub, LE + parm_left_micro, // parm_left_micro, mcub, Zg + parm_right_cursor, // parm_right_cursor, cuf, RI + parm_right_micro, // parm_right_micro, mcuf, Zh + parm_rindex, // parm_rindex, rin, SR + parm_up_cursor, // parm_up_cursor, cuu, UP + parm_up_micro, // parm_up_micro, mcuu, Zi + pkey_key, // pkey_key, pfkey, pk + pkey_local, // pkey_local, pfloc, pl + pkey_xmit, // pkey_xmit, pfx, px + plab_norm, // plab_norm, pln, pn + print_screen, // print_screen, mc0, ps + prtr_non, // prtr_non, mc5p, pO + prtr_off, // prtr_off, mc4, pf + prtr_on, // prtr_on, mc5, po + pulse, // pulse, pulse, PU + quick_dial, // quick_dial, qdial, QD + remove_clock, // remove_clock, rmclk, RC + repeat_char, // repeat_char, rep, rp + req_for_input, // req_for_input, rfi, RF + reset_1string, // reset_1string, rs1, r1 + reset_2string, // reset_2string, rs2, r2 + reset_3string, // reset_3string, rs3, r3 + reset_file, // reset_file, rf, rf + restore_cursor, // restore_cursor, rc, rc + row_address, // row_address, vpa, cv + save_cursor, // save_cursor, sc, sc + scroll_forward, // scroll_forward, ind, sf + scroll_reverse, // scroll_reverse, ri, sr + select_char_set, // select_char_set, scs, Zj + set_attributes, // set_attributes, sgr, sa + set_background, // set_background, setb, Sb + set_bottom_margin, // set_bottom_margin, smgb, Zk + set_bottom_margin_parm, // set_bottom_margin_parm, smgbp, Zl + set_clock, // set_clock, sclk, SC + set_color_pair, // set_color_pair, scp, sp + set_foreground, // set_foreground, setf, Sf + set_left_margin, // set_left_margin, smgl, ML + set_left_margin_parm, // set_left_margin_parm, smglp, Zm + set_right_margin, // set_right_margin, smgr, MR + set_right_margin_parm, // set_right_margin_parm, smgrp, Zn + set_tab, // set_tab, hts, st + set_top_margin, // set_top_margin, smgt, Zo + set_top_margin_parm, // set_top_margin_parm, smgtp, Zp + set_window, // set_window, wind, wi + start_bit_image, // start_bit_image, sbim, Zq + start_char_set_def, // start_char_set_def, scsd, Zr + stop_bit_image, // stop_bit_image, rbim, Zs + stop_char_set_def, // stop_char_set_def, rcsd, Zt + subscript_characters, // subscript_characters, subcs, Zu + superscript_characters, // superscript_characters, supcs, Zv + tab, // tab, ht, ta + these_cause_cr, // these_cause_cr, docr, Zw + to_status_line, // to_status_line, tsl, ts + tone, // tone, tone, TO + underline_char, // underline_char, uc, uc + up_half_line, // up_half_line, hu, hu + user0, // user0, u0, u0 + user1, // user1, u1, u1 + user2, // user2, u2, u2 + user3, // user3, u3, u3 + user4, // user4, u4, u4 + user5, // user5, u5, u5 + user6, // user6, u6, u6 + user7, // user7, u7, u7 + user8, // user8, u8, u8 + user9, // user9, u9, u9 + wait_tone, // wait_tone, wait, WA + xoff_character, // xoff_character, xoffc, XF + xon_character, // xon_character, xonc, XN + zero_motion, // zero_motion, zerom, Zx + alt_scancode_esc, // alt_scancode_esc, scesa, S8 + bit_image_carriage_return, // bit_image_carriage_return, bicr, Yv + bit_image_newline, // bit_image_newline, binel, Zz + bit_image_repeat, // bit_image_repeat, birep, Xy + char_set_names, // char_set_names, csnm, Zy + code_set_init, // code_set_init, csin, ci + color_names, // color_names, colornm, Yw + define_bit_image_region, // define_bit_image_region, defbi, Yx + device_type, // device_type, devt, dv + display_pc_char, // display_pc_char, dispc, S1 + end_bit_image_region, // end_bit_image_region, endbi, Yy + enter_pc_charset_mode, // enter_pc_charset_mode, smpch, S2 + enter_scancode_mode, // enter_scancode_mode, smsc, S4 + exit_pc_charset_mode, // exit_pc_charset_mode, rmpch, S3 + exit_scancode_mode, // exit_scancode_mode, rmsc, S5 + get_mouse, // get_mouse, getm, Gm + key_mouse, // key_mouse, kmous, Km + mouse_info, // mouse_info, minfo, Mi + pc_term_options, // pc_term_options, pctrm, S6 + pkey_plab, // pkey_plab, pfxl, xl + req_mouse_pos, // req_mouse_pos, reqmp, RQ + scancode_escape, // scancode_escape, scesc, S7 + set0_des_seq, // set0_des_seq, s0ds, s0 + set1_des_seq, // set1_des_seq, s1ds, s1 + set2_des_seq, // set2_des_seq, s2ds, s2 + set3_des_seq, // set3_des_seq, s3ds, s3 + set_a_background, // set_a_background, setab, AB + set_a_foreground, // set_a_foreground, setaf, AF + set_color_band, // set_color_band, setcolor, Yz + set_lr_margin, // set_lr_margin, smglr, ML + set_page_length, // set_page_length, slines, YZ + set_tb_margin, // set_tb_margin, smgtb, MT + enter_horizontal_hl_mode, // enter_horizontal_hl_mode, ehhlm, Xh + enter_left_hl_mode, // enter_left_hl_mode, elhlm, Xl + enter_low_hl_mode, // enter_low_hl_mode, elohlm, Xo + enter_right_hl_mode, // enter_right_hl_mode, erhlm, Xr + enter_top_hl_mode, // enter_top_hl_mode, ethlm, Xt + enter_vertical_hl_mode, // enter_vertical_hl_mode, evhlm, Xv + set_a_attributes, // set_a_attributes, sgr1, sA + set_pglen_inch, // set_pglen_inch, slength, sL) ; public String[] getNames() { @@ -515,8 +513,9 @@ public static Map getCapabilitiesByName() { Map capabilities = new LinkedHashMap<>(); try (InputStream is = InfoCmp.class.getResourceAsStream("capabilities.txt"); - BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - br.lines().map(String::trim) + BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + br.lines() + .map(String::trim) .filter(s -> !s.startsWith("#")) .filter(s -> !s.isEmpty()) .forEach(s -> { @@ -539,9 +538,7 @@ CAPS.putIfAbsent(terminal, caps); } - public static String getInfoCmp( - String terminal - ) throws IOException, InterruptedException { + public static String getInfoCmp(String terminal) throws IOException, InterruptedException { String caps = getLoadedInfoCmp(terminal); if (caps == null) { Process p = new ProcessBuilder(OSUtils.INFOCMP_COMMAND, terminal).start(); @@ -563,8 +560,7 @@ String capabilities, Set bools, Map ints, - Map strings - ) { + Map strings) { Map capsByName = getCapabilitiesByName(); String[] lines = capabilities.split("\n"); for (int i = 1; i < lines.length; i++) { @@ -609,7 +605,7 @@ static String loadDefaultInfoCmp(String name) { try (InputStream is = InfoCmp.class.getResourceAsStream(name + ".caps"); - BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { return br.lines().collect(Collectors.joining("\n", "", "\n")); } catch (IOException e) { throw new IOError(e); @@ -617,11 +613,23 @@ } static { - for (String s : Arrays.asList("dumb", "dumb-color", "ansi", "xterm", "xterm-256color", - "windows", "windows-256color", "windows-conemu", "windows-vtp", - "screen", "screen-256color", "rxvt-unicode", "rxvt-unicode-256color", "rxvt-basic", "rxvt")) { + for (String s : Arrays.asList( + "dumb", + "dumb-color", + "ansi", + "xterm", + "xterm-256color", + "windows", + "windows-256color", + "windows-conemu", + "windows-vtp", + "screen", + "screen-256color", + "rxvt-unicode", + "rxvt-unicode-256color", + "rxvt-basic", + "rxvt")) { setDefaultInfoCmp(s, () -> loadDefaultInfoCmp(s)); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InputStreamReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InputStreamReader.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InputStreamReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/InputStreamReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -22,7 +22,6 @@ import java.nio.charset.MalformedInputException; import java.nio.charset.UnmappableCharacterException; - /** * * NOTE for JLine: the default InputStreamReader that comes from the JRE @@ -66,9 +65,10 @@ public InputStreamReader(InputStream in) { super(in); this.in = in; - decoder = Charset.defaultCharset().newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); + decoder = Charset.defaultCharset() + .newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); bytes.limit(0); } @@ -87,20 +87,19 @@ * @throws UnsupportedEncodingException * if the encoding specified by {@code enc} cannot be found. */ - public InputStreamReader(InputStream in, final String enc) - throws UnsupportedEncodingException { + public InputStreamReader(InputStream in, final String enc) throws UnsupportedEncodingException { super(in); if (enc == null) { throw new NullPointerException(); } this.in = in; try { - decoder = Charset.forName(enc).newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); + decoder = Charset.forName(enc) + .newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); } catch (IllegalArgumentException e) { - throw (UnsupportedEncodingException) - new UnsupportedEncodingException(enc).initCause(e); + throw (UnsupportedEncodingException) new UnsupportedEncodingException(enc).initCause(e); } bytes.limit(0); } @@ -134,9 +133,9 @@ public InputStreamReader(InputStream in, Charset charset) { super(in); this.in = in; - decoder = charset.newDecoder().onMalformedInput( - CodingErrorAction.REPLACE).onUnmappableCharacter( - CodingErrorAction.REPLACE); + decoder = charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); bytes.limit(0); } @@ -257,8 +256,7 @@ // fill the buffer if needed if (needInput) { try { - if ((in.available() == 0) - && (out.position() > offset)) { + if ((in.available() == 0) && (out.position() > offset)) { // we could return the result without blocking read break; } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Levenshtein.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Levenshtein.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Levenshtein.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Levenshtein.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -49,9 +49,8 @@ return distance(lhs, rhs, 1, 1, 1, 1); } - public static int distance(CharSequence source, CharSequence target, - int deleteCost, int insertCost, - int replaceCost, int swapCost) { + public static int distance( + CharSequence source, CharSequence target, int deleteCost, int insertCost, int replaceCost, int swapCost) { /* * Required to facilitate the premise to the algorithm that two swaps of the * same character are never required for optimality. @@ -115,5 +114,4 @@ } return table[source.length() - 1][target.length() - 1]; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Log.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Log.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Log.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Log.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -73,8 +73,7 @@ } } out.print("]"); - } - else { + } else { out.print(message); } } @@ -84,11 +83,10 @@ // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // PrintStream ps = new PrintStream(baos); // for (int i = 0; i < messages.length; i++) { -// // Special handling for the last message if its a throwable, render its stack on the next line +// // Special handling for the last message if it's a throwable, render its stack on the next line // if (i + 1 == messages.length && messages[i] instanceof Throwable) { // cause = (Throwable) messages[i]; -// } -// else { +// } else { // render(ps, messages[i]); // } // } @@ -122,5 +120,4 @@ // static boolean isEnabled(Level level) { // return logger.isLoggable(level); // } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlocking.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlocking.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlocking.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlocking.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -84,8 +84,7 @@ @Override public int available() { - return (int) (reader.available() * this.encoder.averageBytesPerChar()) - + bytes.remaining(); + return (int) (reader.available() * this.encoder.averageBytesPerChar()) + bytes.remaining(); } @Override @@ -124,7 +123,6 @@ return READ_EXPIRED; } } - } private static class NonBlockingInputStreamReader extends NonBlockingReader { @@ -135,10 +133,12 @@ private final CharBuffer chars; public NonBlockingInputStreamReader(NonBlockingInputStream inputStream, Charset encoding) { - this(inputStream, - (encoding != null ? encoding : Charset.defaultCharset()).newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE)); + this( + inputStream, + (encoding != null ? encoding : Charset.defaultCharset()) + .newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE)); } public NonBlockingInputStreamReader(NonBlockingInputStream input, CharsetDecoder decoder) { @@ -201,8 +201,8 @@ bytes.position(0); bytes.limit(0); } - int nb = input.readBuffered(bytes.array(), bytes.limit(), - bytes.capacity() - bytes.limit(), t.timeout()); + int nb = input.readBuffered( + bytes.array(), bytes.limit(), bytes.capacity() - bytes.limit(), t.timeout()); if (nb < 0) { return nb; } @@ -227,5 +227,4 @@ input.close(); } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStream.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStream.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -74,7 +74,7 @@ if (c == EOF) { return EOF; } - b[off] = (byte)c; + b[off] = (byte) c; return 1; } @@ -115,9 +115,7 @@ * thread is currently blocked waiting for I/O it may not actually * shut down until the I/O is received. */ - public void shutdown() { - } + public void shutdown() {} public abstract int read(long timeout, boolean isPeek) throws IOException; - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStreamImpl.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStreamImpl.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStreamImpl.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingInputStreamImpl.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -26,17 +26,15 @@ * the thread that handles blocking I/O. * */ -public class NonBlockingInputStreamImpl - extends NonBlockingInputStream -{ - private InputStream in; // The actual input stream - private int b = READ_EXPIRED; // Recently read byte - - private String name; - private boolean threadIsReading = false; - private IOException exception = null; - private long threadDelay = 60 * 1000; - private Thread thread; +public class NonBlockingInputStreamImpl extends NonBlockingInputStream { + private InputStream in; // The actual input stream + private int b = READ_EXPIRED; // Recently read byte + + private String name; + private boolean threadIsReading = false; + private IOException exception = null; + private long threadDelay = 60 * 1000; + private Thread thread; /** * Creates a NonBlockingReader out of a normal blocking @@ -97,8 +95,7 @@ if (exception != null) { assert b == READ_EXPIRED; IOException toBeThrown = exception; - if (!isPeek) - exception = null; + if (!isPeek) exception = null; throw toBeThrown; } @@ -109,11 +106,9 @@ */ if (b >= -1) { assert exception == null; - } - else if (!isPeek && timeout <= 0L && !threadIsReading) { + } else if (!isPeek && timeout <= 0L && !threadIsReading) { b = in.read(); - } - else { + } else { /* * If the thread isn't reading already, then ask it to do so. */ @@ -128,14 +123,13 @@ * now we play the waiting game. */ Timeout t = new Timeout(timeout); - while (!t.elapsed()) { + while (!t.elapsed()) { try { if (Thread.interrupted()) { throw new InterruptedException(); } wait(t.timeout()); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { exception = (IOException) new InterruptedIOException().initCause(e); } @@ -143,8 +137,7 @@ assert b == READ_EXPIRED; IOException toBeThrown = exception; - if (!isPeek) - exception = null; + if (!isPeek) exception = null; throw toBeThrown; } @@ -168,7 +161,7 @@ return ret; } - private void run () { + private void run() { Log.debug("NonBlockingInputStream start"); boolean needToRead; @@ -236,5 +229,4 @@ } } } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpInputStream.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpInputStream.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpInputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpInputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -57,11 +57,7 @@ throw new InterruptedIOException(); } } - return buffer.hasRemaining() - ? 0 - : closed - ? EOF - : READ_EXPIRED; + return buffer.hasRemaining() ? 0 : closed ? EOF : READ_EXPIRED; } private static boolean rewind(ByteBuffer buffer, ByteBuffer other) { @@ -167,7 +163,7 @@ @Override public void write(int b) throws IOException { - NonBlockingPumpInputStream.this.write(new byte[] { (byte) b }, 0, 1); + NonBlockingPumpInputStream.this.write(new byte[] {(byte) b}, 0, 1); } @Override @@ -184,7 +180,5 @@ public void close() throws IOException { NonBlockingPumpInputStream.this.close(); } - } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpReader.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingPumpReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -121,7 +121,7 @@ try { if (timeout > 0) { if (!notEmpty.await(timeout, TimeUnit.MILLISECONDS)) { - throw new IOException( "Timeout reading" ); + throw new IOException("Timeout reading"); } } else { notEmpty.await(); @@ -207,14 +207,11 @@ } @Override - public void flush() throws IOException { - } + public void flush() throws IOException {} @Override public void close() throws IOException { NonBlockingPumpReader.this.close(); } - } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReader.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -23,8 +23,7 @@ * thread is currently blocked waiting for I/O it will not actually * shut down until the I/O is received. */ - public void shutdown() { - } + public void shutdown() {} @Override public int read() throws IOException { @@ -109,5 +108,4 @@ * @throws IOException if anything wrong happens */ protected abstract int read(long timeout, boolean isPeek) throws IOException; - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReaderImpl.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReaderImpl.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReaderImpl.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/NonBlockingReaderImpl.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -28,19 +28,17 @@ * @since 2.7 * @author Scott C. Gray <scottgray1@gmail.com> */ -public class NonBlockingReaderImpl - extends NonBlockingReader -{ +public class NonBlockingReaderImpl extends NonBlockingReader { public static final int READ_EXPIRED = -2; - private Reader in; // The actual input stream - private int ch = READ_EXPIRED; // Recently read character + private Reader in; // The actual input stream + private int ch = READ_EXPIRED; // Recently read character - private String name; - private boolean threadIsReading = false; - private IOException exception = null; - private long threadDelay = 60 * 1000; - private Thread thread; + private String name; + private boolean threadIsReading = false; + private IOException exception = null; + private long threadDelay = 60 * 1000; + private Thread thread; /** * Creates a NonBlockingReader out of a normal blocking @@ -135,8 +133,7 @@ if (exception != null) { assert ch == READ_EXPIRED; IOException toBeThrown = exception; - if (!isPeek) - exception = null; + if (!isPeek) exception = null; throw toBeThrown; } @@ -147,11 +144,9 @@ */ if (ch >= -1) { assert exception == null; - } - else if (!isPeek && timeout <= 0L && !threadIsReading) { + } else if (!isPeek && timeout <= 0L && !threadIsReading) { ch = in.read(); - } - else { + } else { /* * If the thread isn't reading already, then ask it to do so. */ @@ -166,14 +161,13 @@ * now we play the waiting game. */ Timeout t = new Timeout(timeout); - while (!t.elapsed()) { + while (!t.elapsed()) { try { if (Thread.interrupted()) { throw new InterruptedException(); } wait(t.timeout()); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { exception = (IOException) new InterruptedIOException().initCause(e); } @@ -181,8 +175,7 @@ assert ch == READ_EXPIRED; IOException toBeThrown = exception; - if (!isPeek) - exception = null; + if (!isPeek) exception = null; throw toBeThrown; } @@ -206,7 +199,7 @@ return ret; } - private void run () { + private void run() { Log.debug("NonBlockingReader start"); boolean needToRead; @@ -245,12 +238,12 @@ IOException failure = null; try { charRead = in.read(); -// if (charRead < 0) { -// continue; -// } + // if (charRead < 0) { + // continue; + // } } catch (IOException e) { failure = e; -// charRead = -1; + // charRead = -1; } /* diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/OSUtils.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/OSUtils.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/OSUtils.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/OSUtils.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -9,16 +9,23 @@ package jdk.internal.org.jline.utils; import java.io.File; -import java.nio.file.Files; -import java.nio.file.Paths; public class OSUtils { - public static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().contains("win"); + public static final boolean IS_LINUX = + System.getProperty("os.name").toLowerCase().contains("linux"); - public static final boolean IS_CYGWIN = IS_WINDOWS - && System.getenv("PWD") != null - && System.getenv("PWD").startsWith("/"); + public static final boolean IS_WINDOWS = + System.getProperty("os.name").toLowerCase().contains("win"); + + public static final boolean IS_OSX = + System.getProperty("os.name").toLowerCase().contains("mac"); + + public static final boolean IS_AIX = + System.getProperty("os.name").toLowerCase().contains("aix"); + + public static final boolean IS_CYGWIN = + IS_WINDOWS && System.getenv("PWD") != null && System.getenv("PWD").startsWith("/"); @Deprecated public static final boolean IS_MINGW = IS_WINDOWS @@ -28,7 +35,7 @@ public static final boolean IS_MSYSTEM = IS_WINDOWS && System.getenv("MSYSTEM") != null && (System.getenv("MSYSTEM").startsWith("MINGW") - || System.getenv("MSYSTEM").equals("MSYS")); + || System.getenv("MSYSTEM").equals("MSYS")); public static final boolean IS_WSL = System.getenv("WSL_DISTRO_NAME") != null; @@ -36,11 +43,7 @@ public static final boolean IS_WSL2 = IS_WSL && !IS_WSL1; - public static final boolean IS_CONEMU = IS_WINDOWS - && System.getenv("ConEmuPID") != null; - - public static final boolean IS_OSX = System.getProperty("os.name").toLowerCase().contains("mac"); - public static final boolean IS_AIX = System.getProperty("os.name").equals("AIX"); + public static final boolean IS_CONEMU = IS_WINDOWS && System.getenv("ConEmuPID") != null; public static String TTY_COMMAND; public static String STTY_COMMAND; @@ -48,64 +51,57 @@ public static String INFOCMP_COMMAND; public static String TEST_COMMAND; + private static boolean isExecutable(File f) { + return f.canExecute() && !f.isDirectory(); + } + static { - String tty; - String stty; - String sttyfopt; - String infocmp; - String test; - if (OSUtils.IS_CYGWIN || OSUtils.IS_MSYSTEM) { - tty = null; - stty = null; - sttyfopt = null; - infocmp = null; - test = null; - String path = System.getenv("PATH"); - if (path != null) { - String[] paths = path.split(";"); - for (String p : paths) { - if (tty == null && new File(p, "tty.exe").exists()) { - tty = new File(p, "tty.exe").getAbsolutePath(); - } - if (stty == null && new File(p, "stty.exe").exists()) { - stty = new File(p, "stty.exe").getAbsolutePath(); - } - if (infocmp == null && new File(p, "infocmp.exe").exists()) { - infocmp = new File(p, "infocmp.exe").getAbsolutePath(); - } - if (test == null && new File(p, "test.exe").exists()) { - test = new File(p, "test.exe").getAbsolutePath(); - } + boolean cygwinOrMsys = OSUtils.IS_CYGWIN || OSUtils.IS_MSYSTEM; + String suffix = cygwinOrMsys ? ".exe" : ""; + String tty = null; + String stty = null; + String sttyfopt = null; + String infocmp = null; + String test = null; + String path = System.getenv("PATH"); + if (path != null) { + String[] paths = path.split(File.pathSeparator); + for (String p : paths) { + File ttyFile = new File(p, "tty" + suffix); + if (tty == null && isExecutable(ttyFile)) { + tty = ttyFile.getAbsolutePath(); + } + File sttyFile = new File(p, "stty" + suffix); + if (stty == null && isExecutable(sttyFile)) { + stty = sttyFile.getAbsolutePath(); + } + File infocmpFile = new File(p, "infocmp" + suffix); + if (infocmp == null && isExecutable(infocmpFile)) { + infocmp = infocmpFile.getAbsolutePath(); + } + File testFile = new File(p, "test" + suffix); + if (test == null && isExecutable(testFile)) { + test = testFile.getAbsolutePath(); } } - if (tty == null) { - tty = "tty.exe"; - } - if (stty == null) { - stty = "stty.exe"; - } - if (infocmp == null) { - infocmp = "infocmp.exe"; - } - if (test == null) { - test = "test.exe"; - } - } else { - tty = "tty"; - stty = IS_OSX ? "/bin/stty" : "stty"; - sttyfopt = IS_OSX ? "-f" : "-F"; - infocmp = "infocmp"; - test = isTestCommandValid("/usr/bin/test") ? "/usr/bin/test" - : "/bin/test"; } + if (tty == null) { + tty = "tty" + suffix; + } + if (stty == null) { + stty = "stty" + suffix; + } + if (infocmp == null) { + infocmp = "infocmp" + suffix; + } + if (test == null) { + test = "test" + suffix; + } + sttyfopt = IS_OSX ? "-f" : "-F"; TTY_COMMAND = tty; STTY_COMMAND = stty; STTY_F_OPTION = sttyfopt; INFOCMP_COMMAND = infocmp; TEST_COMMAND = test; } - - private static boolean isTestCommandValid(String command) { - return Files.isExecutable(Paths.get(command)); - } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/PumpReader.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/PumpReader.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/PumpReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/PumpReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -378,7 +378,6 @@ public void close() throws IOException { reader.close(); } - } private static class InputStream extends java.io.InputStream { @@ -464,7 +463,5 @@ public void close() throws IOException { reader.close(); } - } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ShutdownHooks.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ShutdownHooks.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ShutdownHooks.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/ShutdownHooks.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -18,8 +18,7 @@ * @author Jason Dillon * @since 2.7 */ -public final class ShutdownHooks -{ +public final class ShutdownHooks { private static final List tasks = new ArrayList<>(); private static Thread hook; @@ -29,8 +28,7 @@ // Install the hook thread if needed if (hook == null) { - hook = addHook(new Thread("JLine Shutdown Hook") - { + hook = addHook(new Thread("JLine Shutdown Hook") { @Override public void run() { runTasks(); @@ -53,8 +51,7 @@ Log.debug("Running task: ", task); try { task.run(); - } - catch (Throwable e) { + } catch (Throwable e) { Log.warn("Task failed", e); } } @@ -91,8 +88,7 @@ try { Runtime.getRuntime().removeShutdownHook(thread); - } - catch (IllegalStateException e) { + } catch (IllegalStateException e) { // The VM is shutting down, not a big deal; ignore } } @@ -100,8 +96,7 @@ /** * Essentially a {@link Runnable} which allows running to throw an exception. */ - public interface Task - { + public interface Task { void run() throws Exception; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Signals.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Signals.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Signals.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Signals.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2020, the original author or authors. + * Copyright (c) 2002-2020, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -21,8 +21,7 @@ */ public final class Signals { - private Signals() { - } + private Signals() {} /** * @@ -41,8 +40,8 @@ try { Class signalHandlerClass = Class.forName("sun.misc.SignalHandler"); // Implement signal handler - Object signalHandler = Proxy.newProxyInstance(loader, - new Class[]{signalHandlerClass}, (proxy, method, args) -> { + Object signalHandler = + Proxy.newProxyInstance(loader, new Class[] {signalHandlerClass}, (proxy, method, args) -> { // only method we are proxying is handle() if (method.getDeclaringClass() == Object.class) { if ("toString".equals(method.getName())) { @@ -101,8 +100,7 @@ return null; } Class signalHandlerClass = Class.forName("sun.misc.SignalHandler"); - return signalClass.getMethod("handle", signalClass, signalHandlerClass) - .invoke(null, signal, handler); + return signalClass.getMethod("handle", signalClass, signalHandlerClass).invoke(null, signal, handler); } @SuppressWarnings("") @@ -120,5 +118,4 @@ } return handler != null ? handler.toString() : "null"; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Status.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Status.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Status.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Status.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2019, the original author or authors. + * Copyright (c) 2002-2019, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -8,187 +8,266 @@ */ package jdk.internal.org.jline.utils; -import java.util.Objects; -import java.util.Collections; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.Terminal; import jdk.internal.org.jline.terminal.impl.AbstractTerminal; import jdk.internal.org.jline.utils.InfoCmp.Capability; -import jdk.internal.org.jline.terminal.Size; public class Status { - protected final AbstractTerminal terminal; + protected final Terminal terminal; protected final boolean supported; - protected List oldLines = Collections.emptyList(); - protected List linesToRestore = Collections.emptyList(); - protected int rows; - protected int columns; - protected boolean force; protected boolean suspended = false; protected AttributedString borderString; protected int border = 0; + protected Display display; + protected List lines = Collections.emptyList(); + protected int scrollRegion; public static Status getStatus(Terminal terminal) { return getStatus(terminal, true); } - public static Status getStatus(Terminal terminal, boolean create) { - return terminal instanceof AbstractTerminal - ? ((AbstractTerminal) terminal).getStatus(create) - : null; + public static Optional getExistingStatus(Terminal terminal) { + return Optional.ofNullable(getStatus(terminal, false)); } + public static Status getStatus(Terminal terminal, boolean create) { + return terminal instanceof AbstractTerminal ? ((AbstractTerminal) terminal).getStatus(create) : null; + } - public Status(AbstractTerminal terminal) { + @SuppressWarnings("this-escape") + public Status(Terminal terminal) { this.terminal = Objects.requireNonNull(terminal, "terminal can not be null"); this.supported = terminal.getStringCapability(Capability.change_scroll_region) != null - && terminal.getStringCapability(Capability.save_cursor) != null - && terminal.getStringCapability(Capability.restore_cursor) != null - && terminal.getStringCapability(Capability.cursor_address) != null; + && terminal.getStringCapability(Capability.save_cursor) != null + && terminal.getStringCapability(Capability.restore_cursor) != null + && terminal.getStringCapability(Capability.cursor_address) != null; if (supported) { - char borderChar = '\u2700'; - AttributedStringBuilder bb = new AttributedStringBuilder(); - for (int i = 0; i < 200; i++) { - bb.append(borderChar); - } - borderString = bb.toAttributedString(); + display = new MovingCursorDisplay(terminal); resize(); + display.reset(); + scrollRegion = display.rows - 1; } } + public void close() { + terminal.puts(Capability.save_cursor); + terminal.puts(Capability.change_scroll_region, 0, display.rows - 1); + terminal.puts(Capability.restore_cursor); + terminal.flush(); + } + public void setBorder(boolean border) { this.border = border ? 1 : 0; } public void resize() { - Size size = terminal.getSize(); - this.rows = size.getRows(); - this.columns = size.getColumns(); - this.force = true; + resize(terminal.getSize()); } - public void reset() { - this.force = true; + public void resize(Size size) { + display.resize(size.getRows(), size.getColumns()); } - public void hardReset() { - if (suspended) { - return; + public void reset() { + if (supported) { + display.reset(); + scrollRegion = display.rows; + terminal.puts(Capability.change_scroll_region, 0, scrollRegion); } - List lines = new ArrayList<>(oldLines); - int b = border; - update(null); - border = b; - update(lines); } public void redraw() { if (suspended) { return; } - update(oldLines); + update(lines); } - public void clear() { - privateClear(oldLines.size()); + public void hide() { + update(Collections.emptyList()); } - private void clearAll() { - int b = border; - border = 0; - privateClear(oldLines.size() + b); + public void update(List lines) { + update(lines, true); } - private void privateClear(int statusSize) { - List as = new ArrayList<>(); - for (int i = 0; i < statusSize; i++) { - as.add(new AttributedString("")); - } - if (!as.isEmpty()) { - update(as); - } - } + private final AttributedString ellipsis = + new AttributedStringBuilder().append("\u2026", AttributedStyle.INVERSE).toAttributedString(); - public void update(List lines) { + /** + * Returns true if the cursor may be misplaced and should + * be updated. + */ + public void update(List lines, boolean flush) { if (!supported) { return; } - if (lines == null) { - lines = Collections.emptyList(); - } + this.lines = new ArrayList<>(lines); if (suspended) { - linesToRestore = new ArrayList<>(lines); return; } - if (lines.isEmpty()) { - clearAll(); + + lines = new ArrayList<>(lines); + // add border + int rows = display.rows; + int columns = display.columns; + if (border == 1 && !lines.isEmpty() && rows > 1) { + lines.add(0, getBorderString(columns)); } - if (oldLines.equals(lines) && !force) { - return; + // trim or complete lines to the full width + for (int i = 0; i < lines.size(); i++) { + AttributedString str = lines.get(i); + if (str.columnLength() > columns) { + str = new AttributedStringBuilder(columns) + .append(lines.get(i).columnSubSequence(0, columns - ellipsis.columnLength())) + .append(ellipsis) + .toAttributedString(); + } else if (str.columnLength() < columns) { + str = new AttributedStringBuilder(columns) + .append(str) + .append(' ', columns - str.columnLength()) + .toAttributedString(); + } + lines.set(i, str); } - int statusSize = lines.size() + (lines.size() == 0 ? 0 : border); - int nb = statusSize - oldLines.size() - (oldLines.size() == 0 ? 0 : border); - if (nb > 0) { - for (int i = 0; i < nb; i++) { + + List oldLines = this.display.oldLines; + + int newScrollRegion = display.rows - 1 - lines.size(); + // Update the scroll region if needed. + // Note that settings the scroll region usually moves the cursor, so we need to get ready for that. + if (newScrollRegion < scrollRegion) { + // We need to scroll up to grow the status bar + terminal.puts(Capability.save_cursor); + for (int i = newScrollRegion; i < scrollRegion; i++) { terminal.puts(Capability.cursor_down); } - for (int i = 0; i < nb; i++) { + terminal.puts(Capability.change_scroll_region, 0, newScrollRegion); + terminal.puts(Capability.restore_cursor); + for (int i = newScrollRegion; i < scrollRegion; i++) { terminal.puts(Capability.cursor_up); } - } - terminal.puts(Capability.save_cursor); - terminal.puts(Capability.cursor_address, rows - statusSize, 0); - if (!terminal.puts(Capability.clr_eos)) { - for (int i = rows - statusSize; i < rows; i++) { - terminal.puts(Capability.cursor_address, i, 0); + scrollRegion = newScrollRegion; + } else if (newScrollRegion > scrollRegion) { + terminal.puts(Capability.save_cursor); + terminal.puts(Capability.change_scroll_region, 0, newScrollRegion); + terminal.puts(Capability.restore_cursor); + scrollRegion = newScrollRegion; + } + + // if the display has more lines, we need to add empty ones to make sure they will be erased + List toDraw = new ArrayList<>(lines); + int nbToDraw = toDraw.size(); + int nbOldLines = oldLines.size(); + if (nbOldLines > nbToDraw) { + terminal.puts(Capability.save_cursor); + terminal.puts(Capability.cursor_address, display.rows - nbOldLines, 0); + for (int i = 0; i < nbOldLines - nbToDraw; i++) { terminal.puts(Capability.clr_eol); + if (i < nbOldLines - nbToDraw - 1) { + terminal.puts(Capability.cursor_down); + } + oldLines.remove(0); } + terminal.puts(Capability.restore_cursor); } - if (border == 1 && lines.size() > 0) { - terminal.puts(Capability.cursor_address, rows - statusSize, 0); - borderString.columnSubSequence(0, columns).print(terminal); - } - for (int i = 0; i < lines.size(); i++) { - terminal.puts(Capability.cursor_address, rows - lines.size() + i, 0); - if (lines.get(i).length() > columns) { - AttributedStringBuilder asb = new AttributedStringBuilder(); - asb.append(lines.get(i).substring(0, columns - 3)).append("...", new AttributedStyle(AttributedStyle.INVERSE)); - asb.toAttributedString().columnSubSequence(0, columns).print(terminal); - } else { - lines.get(i).columnSubSequence(0, columns).print(terminal); + // update display + display.update(lines, -1, flush); + } + + private AttributedString getBorderString(int columns) { + if (borderString == null || borderString.length() != columns) { + char borderChar = '\u2700'; + AttributedStringBuilder bb = new AttributedStringBuilder(); + for (int i = 0; i < columns; i++) { + bb.append(borderChar); } + borderString = bb.toAttributedString(); } - terminal.puts(Capability.change_scroll_region, 0, rows - 1 - statusSize); - terminal.puts(Capability.restore_cursor); - terminal.flush(); - oldLines = new ArrayList<>(lines); - force = false; + return borderString; } + /** + * The {@code suspend} method is used when a full-screen. + * If the status was not already suspended, the lines + * used by the status are cleared during this call. + */ public void suspend() { - if (suspended) { - return; + if (!suspended) { + suspended = true; } - linesToRestore = new ArrayList<>(oldLines); - int b = border; - update(null); - border = b; - suspended = true; } + /** + * The {@code restore()} call is the opposite of {@code suspend()} and + * will make the status bar be updated again. + * If the status was suspended, the lines + * used by the status will be drawn during this call. + */ public void restore() { - if (!suspended) { - return; + if (suspended) { + suspended = false; + update(this.lines); } - suspended = false; - update(linesToRestore); - linesToRestore = Collections.emptyList(); } public int size() { - return oldLines.size() + border; + return size(this.lines); } + private int size(List lines) { + int l = lines.size(); + return l > 0 ? l + border : 0; + } + + @Override + public String toString() { + return "Status[" + "supported=" + supported + ']'; + } + + static class MovingCursorDisplay extends Display { + protected int firstLine; + + public MovingCursorDisplay(Terminal terminal) { + super(terminal, false); + } + + @Override + public void update(List newLines, int targetCursorPos, boolean flush) { + cursorPos = -1; + firstLine = rows - newLines.size(); + super.update(newLines, targetCursorPos, flush); + if (cursorPos != -1) { + terminal.puts(Capability.restore_cursor); + } + } + + @Override + protected void moveVisualCursorTo(int targetPos, List newLines) { + initCursor(); + super.moveVisualCursorTo(targetPos, newLines); + } + + @Override + protected int moveVisualCursorTo(int i1) { + initCursor(); + return super.moveVisualCursorTo(i1); + } + + void initCursor() { + if (cursorPos == -1) { + terminal.puts(Capability.save_cursor); + terminal.puts(Capability.cursor_address, firstLine, 0); + cursorPos = 0; + } + } + } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/StyleResolver.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/StyleResolver.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/StyleResolver.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/StyleResolver.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -55,12 +55,12 @@ return null; } } else { - // load indexed color - Integer color = color(name); - if (color != null && color != -1) { - color = Colors.DEFAULT_COLORS_256[color]; - } - return color; + // load indexed color + Integer color = color(name); + if (color != null && color != -1) { + color = Colors.DEFAULT_COLORS_256[color]; + } + return color; } } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Timeout.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Timeout.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Timeout.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/Timeout.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2018, the original author or authors. + * Copyright (c) 2002-2018, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -44,5 +44,4 @@ public long timeout() { return timeout > 0 ? Math.max(1, end - cur) : timeout; } - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WCWidth.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WCWidth.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WCWidth.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WCWidth.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2016, the original author or authors. + * Copyright (c) 2002-2016, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -10,8 +10,7 @@ public final class WCWidth { - private WCWidth() { - } + private WCWidth() {} /* The following two functions define the column width of an ISO 10646 * character as follows: @@ -44,88 +43,86 @@ * This implementation assumes that wchar_t characters are encoded * in ISO 10646. */ - public static int wcwidth(int ucs) - { + public static int wcwidth(int ucs) { /* test for 8-bit control characters */ - if (ucs == 0) - return 0; - if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) - return -1; + if (ucs == 0) return 0; + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return -1; /* binary search in table of non-spacing characters */ - if (bisearch(ucs, combining, combining.length - 1)) - return 0; + if (bisearch(ucs, combining, combining.length - 1)) return 0; /* if we arrive here, ucs is not a combining or C0/C1 control character */ - return 1 + - ((ucs >= 0x1100 && - (ucs <= 0x115f || /* Hangul Jamo init. consonants */ - ucs == 0x2329 || ucs == 0x232a || - (ucs >= 0x2e80 && ucs <= 0xa4cf && - ucs != 0x303f) || /* CJK ... Yi */ - (ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */ - (ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */ - (ucs >= 0xfe10 && ucs <= 0xfe19) || /* Vertical forms */ - (ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */ - (ucs >= 0xff00 && ucs <= 0xff60) || /* Fullwidth Forms */ - (ucs >= 0xffe0 && ucs <= 0xffe6) || - (ucs >= 0x1f000 && ucs <= 0x1feee) || - (ucs >= 0x20000 && ucs <= 0x2fffd) || - (ucs >= 0x30000 && ucs <= 0x3fffd))) ? 1 : 0); + return 1 + + ((ucs >= 0x1100 + && (ucs <= 0x115f + || /* Hangul Jamo init. consonants */ ucs == 0x2329 + || ucs == 0x232a + || (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) + || /* CJK ... Yi */ (ucs >= 0xac00 && ucs <= 0xd7a3) + || /* Hangul Syllables */ (ucs >= 0xf900 && ucs <= 0xfaff) + || /* CJK Compatibility Ideographs */ (ucs >= 0xfe10 && ucs <= 0xfe19) + || /* Vertical forms */ (ucs >= 0xfe30 && ucs <= 0xfe6f) + || /* CJK Compatibility Forms */ (ucs >= 0xff00 && ucs <= 0xff60) + || /* Fullwidth Forms */ (ucs >= 0xffe0 && ucs <= 0xffe6) + || (ucs >= 0x1f000 && ucs <= 0x1feee) + || (ucs >= 0x20000 && ucs <= 0x2fffd) + || (ucs >= 0x30000 && ucs <= 0x3fffd))) + ? 1 + : 0); } /* sorted list of non-overlapping intervals of non-spacing characters */ /* generated by "uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B c" */ static Interval[] combining = { - new Interval( 0x0300, 0x036F ), new Interval( 0x0483, 0x0486 ), new Interval( 0x0488, 0x0489 ), - new Interval( 0x0591, 0x05BD ), new Interval( 0x05BF, 0x05BF ), new Interval( 0x05C1, 0x05C2 ), - new Interval( 0x05C4, 0x05C5 ), new Interval( 0x05C7, 0x05C7 ), new Interval( 0x0600, 0x0603 ), - new Interval( 0x0610, 0x0615 ), new Interval( 0x064B, 0x065E ), new Interval( 0x0670, 0x0670 ), - new Interval( 0x06D6, 0x06E4 ), new Interval( 0x06E7, 0x06E8 ), new Interval( 0x06EA, 0x06ED ), - new Interval( 0x070F, 0x070F ), new Interval( 0x0711, 0x0711 ), new Interval( 0x0730, 0x074A ), - new Interval( 0x07A6, 0x07B0 ), new Interval( 0x07EB, 0x07F3 ), new Interval( 0x0901, 0x0902 ), - new Interval( 0x093C, 0x093C ), new Interval( 0x0941, 0x0948 ), new Interval( 0x094D, 0x094D ), - new Interval( 0x0951, 0x0954 ), new Interval( 0x0962, 0x0963 ), new Interval( 0x0981, 0x0981 ), - new Interval( 0x09BC, 0x09BC ), new Interval( 0x09C1, 0x09C4 ), new Interval( 0x09CD, 0x09CD ), - new Interval( 0x09E2, 0x09E3 ), new Interval( 0x0A01, 0x0A02 ), new Interval( 0x0A3C, 0x0A3C ), - new Interval( 0x0A41, 0x0A42 ), new Interval( 0x0A47, 0x0A48 ), new Interval( 0x0A4B, 0x0A4D ), - new Interval( 0x0A70, 0x0A71 ), new Interval( 0x0A81, 0x0A82 ), new Interval( 0x0ABC, 0x0ABC ), - new Interval( 0x0AC1, 0x0AC5 ), new Interval( 0x0AC7, 0x0AC8 ), new Interval( 0x0ACD, 0x0ACD ), - new Interval( 0x0AE2, 0x0AE3 ), new Interval( 0x0B01, 0x0B01 ), new Interval( 0x0B3C, 0x0B3C ), - new Interval( 0x0B3F, 0x0B3F ), new Interval( 0x0B41, 0x0B43 ), new Interval( 0x0B4D, 0x0B4D ), - new Interval( 0x0B56, 0x0B56 ), new Interval( 0x0B82, 0x0B82 ), new Interval( 0x0BC0, 0x0BC0 ), - new Interval( 0x0BCD, 0x0BCD ), new Interval( 0x0C3E, 0x0C40 ), new Interval( 0x0C46, 0x0C48 ), - new Interval( 0x0C4A, 0x0C4D ), new Interval( 0x0C55, 0x0C56 ), new Interval( 0x0CBC, 0x0CBC ), - new Interval( 0x0CBF, 0x0CBF ), new Interval( 0x0CC6, 0x0CC6 ), new Interval( 0x0CCC, 0x0CCD ), - new Interval( 0x0CE2, 0x0CE3 ), new Interval( 0x0D41, 0x0D43 ), new Interval( 0x0D4D, 0x0D4D ), - new Interval( 0x0DCA, 0x0DCA ), new Interval( 0x0DD2, 0x0DD4 ), new Interval( 0x0DD6, 0x0DD6 ), - new Interval( 0x0E31, 0x0E31 ), new Interval( 0x0E34, 0x0E3A ), new Interval( 0x0E47, 0x0E4E ), - new Interval( 0x0EB1, 0x0EB1 ), new Interval( 0x0EB4, 0x0EB9 ), new Interval( 0x0EBB, 0x0EBC ), - new Interval( 0x0EC8, 0x0ECD ), new Interval( 0x0F18, 0x0F19 ), new Interval( 0x0F35, 0x0F35 ), - new Interval( 0x0F37, 0x0F37 ), new Interval( 0x0F39, 0x0F39 ), new Interval( 0x0F71, 0x0F7E ), - new Interval( 0x0F80, 0x0F84 ), new Interval( 0x0F86, 0x0F87 ), new Interval( 0x0F90, 0x0F97 ), - new Interval( 0x0F99, 0x0FBC ), new Interval( 0x0FC6, 0x0FC6 ), new Interval( 0x102D, 0x1030 ), - new Interval( 0x1032, 0x1032 ), new Interval( 0x1036, 0x1037 ), new Interval( 0x1039, 0x1039 ), - new Interval( 0x1058, 0x1059 ), new Interval( 0x1160, 0x11FF ), new Interval( 0x135F, 0x135F ), - new Interval( 0x1712, 0x1714 ), new Interval( 0x1732, 0x1734 ), new Interval( 0x1752, 0x1753 ), - new Interval( 0x1772, 0x1773 ), new Interval( 0x17B4, 0x17B5 ), new Interval( 0x17B7, 0x17BD ), - new Interval( 0x17C6, 0x17C6 ), new Interval( 0x17C9, 0x17D3 ), new Interval( 0x17DD, 0x17DD ), - new Interval( 0x180B, 0x180D ), new Interval( 0x18A9, 0x18A9 ), new Interval( 0x1920, 0x1922 ), - new Interval( 0x1927, 0x1928 ), new Interval( 0x1932, 0x1932 ), new Interval( 0x1939, 0x193B ), - new Interval( 0x1A17, 0x1A18 ), new Interval( 0x1B00, 0x1B03 ), new Interval( 0x1B34, 0x1B34 ), - new Interval( 0x1B36, 0x1B3A ), new Interval( 0x1B3C, 0x1B3C ), new Interval( 0x1B42, 0x1B42 ), - new Interval( 0x1B6B, 0x1B73 ), new Interval( 0x1DC0, 0x1DCA ), new Interval( 0x1DFE, 0x1DFF ), - new Interval( 0x200B, 0x200F ), new Interval( 0x202A, 0x202E ), new Interval( 0x2060, 0x2063 ), - new Interval( 0x206A, 0x206F ), new Interval( 0x20D0, 0x20EF ), new Interval( 0x302A, 0x302F ), - new Interval( 0x3099, 0x309A ), new Interval( 0xA806, 0xA806 ), new Interval( 0xA80B, 0xA80B ), - new Interval( 0xA825, 0xA826 ), new Interval( 0xFB1E, 0xFB1E ), new Interval( 0xFE00, 0xFE0F ), - new Interval( 0xFE20, 0xFE23 ), new Interval( 0xFEFF, 0xFEFF ), new Interval( 0xFFF9, 0xFFFB ), - new Interval( 0x10A01, 0x10A03 ), new Interval( 0x10A05, 0x10A06 ), new Interval( 0x10A0C, 0x10A0F ), - new Interval( 0x10A38, 0x10A3A ), new Interval( 0x10A3F, 0x10A3F ), new Interval( 0x1D167, 0x1D169 ), - new Interval( 0x1D173, 0x1D182 ), new Interval( 0x1D185, 0x1D18B ), new Interval( 0x1D1AA, 0x1D1AD ), - new Interval( 0x1D242, 0x1D244 ), new Interval( 0x1F3FB, 0x1F3FF ), new Interval( 0xE0001, 0xE0001 ), - new Interval( 0xE0020, 0xE007F ), new Interval( 0xE0100, 0xE01EF ) + new Interval(0x0300, 0x036F), new Interval(0x0483, 0x0486), new Interval(0x0488, 0x0489), + new Interval(0x0591, 0x05BD), new Interval(0x05BF, 0x05BF), new Interval(0x05C1, 0x05C2), + new Interval(0x05C4, 0x05C5), new Interval(0x05C7, 0x05C7), new Interval(0x0600, 0x0603), + new Interval(0x0610, 0x0615), new Interval(0x064B, 0x065E), new Interval(0x0670, 0x0670), + new Interval(0x06D6, 0x06E4), new Interval(0x06E7, 0x06E8), new Interval(0x06EA, 0x06ED), + new Interval(0x070F, 0x070F), new Interval(0x0711, 0x0711), new Interval(0x0730, 0x074A), + new Interval(0x07A6, 0x07B0), new Interval(0x07EB, 0x07F3), new Interval(0x0901, 0x0902), + new Interval(0x093C, 0x093C), new Interval(0x0941, 0x0948), new Interval(0x094D, 0x094D), + new Interval(0x0951, 0x0954), new Interval(0x0962, 0x0963), new Interval(0x0981, 0x0981), + new Interval(0x09BC, 0x09BC), new Interval(0x09C1, 0x09C4), new Interval(0x09CD, 0x09CD), + new Interval(0x09E2, 0x09E3), new Interval(0x0A01, 0x0A02), new Interval(0x0A3C, 0x0A3C), + new Interval(0x0A41, 0x0A42), new Interval(0x0A47, 0x0A48), new Interval(0x0A4B, 0x0A4D), + new Interval(0x0A70, 0x0A71), new Interval(0x0A81, 0x0A82), new Interval(0x0ABC, 0x0ABC), + new Interval(0x0AC1, 0x0AC5), new Interval(0x0AC7, 0x0AC8), new Interval(0x0ACD, 0x0ACD), + new Interval(0x0AE2, 0x0AE3), new Interval(0x0B01, 0x0B01), new Interval(0x0B3C, 0x0B3C), + new Interval(0x0B3F, 0x0B3F), new Interval(0x0B41, 0x0B43), new Interval(0x0B4D, 0x0B4D), + new Interval(0x0B56, 0x0B56), new Interval(0x0B82, 0x0B82), new Interval(0x0BC0, 0x0BC0), + new Interval(0x0BCD, 0x0BCD), new Interval(0x0C3E, 0x0C40), new Interval(0x0C46, 0x0C48), + new Interval(0x0C4A, 0x0C4D), new Interval(0x0C55, 0x0C56), new Interval(0x0CBC, 0x0CBC), + new Interval(0x0CBF, 0x0CBF), new Interval(0x0CC6, 0x0CC6), new Interval(0x0CCC, 0x0CCD), + new Interval(0x0CE2, 0x0CE3), new Interval(0x0D41, 0x0D43), new Interval(0x0D4D, 0x0D4D), + new Interval(0x0DCA, 0x0DCA), new Interval(0x0DD2, 0x0DD4), new Interval(0x0DD6, 0x0DD6), + new Interval(0x0E31, 0x0E31), new Interval(0x0E34, 0x0E3A), new Interval(0x0E47, 0x0E4E), + new Interval(0x0EB1, 0x0EB1), new Interval(0x0EB4, 0x0EB9), new Interval(0x0EBB, 0x0EBC), + new Interval(0x0EC8, 0x0ECD), new Interval(0x0F18, 0x0F19), new Interval(0x0F35, 0x0F35), + new Interval(0x0F37, 0x0F37), new Interval(0x0F39, 0x0F39), new Interval(0x0F71, 0x0F7E), + new Interval(0x0F80, 0x0F84), new Interval(0x0F86, 0x0F87), new Interval(0x0F90, 0x0F97), + new Interval(0x0F99, 0x0FBC), new Interval(0x0FC6, 0x0FC6), new Interval(0x102D, 0x1030), + new Interval(0x1032, 0x1032), new Interval(0x1036, 0x1037), new Interval(0x1039, 0x1039), + new Interval(0x1058, 0x1059), new Interval(0x1160, 0x11FF), new Interval(0x135F, 0x135F), + new Interval(0x1712, 0x1714), new Interval(0x1732, 0x1734), new Interval(0x1752, 0x1753), + new Interval(0x1772, 0x1773), new Interval(0x17B4, 0x17B5), new Interval(0x17B7, 0x17BD), + new Interval(0x17C6, 0x17C6), new Interval(0x17C9, 0x17D3), new Interval(0x17DD, 0x17DD), + new Interval(0x180B, 0x180D), new Interval(0x18A9, 0x18A9), new Interval(0x1920, 0x1922), + new Interval(0x1927, 0x1928), new Interval(0x1932, 0x1932), new Interval(0x1939, 0x193B), + new Interval(0x1A17, 0x1A18), new Interval(0x1B00, 0x1B03), new Interval(0x1B34, 0x1B34), + new Interval(0x1B36, 0x1B3A), new Interval(0x1B3C, 0x1B3C), new Interval(0x1B42, 0x1B42), + new Interval(0x1B6B, 0x1B73), new Interval(0x1DC0, 0x1DCA), new Interval(0x1DFE, 0x1DFF), + new Interval(0x200B, 0x200F), new Interval(0x202A, 0x202E), new Interval(0x2060, 0x2063), + new Interval(0x206A, 0x206F), new Interval(0x20D0, 0x20EF), new Interval(0x302A, 0x302F), + new Interval(0x3099, 0x309A), new Interval(0xA806, 0xA806), new Interval(0xA80B, 0xA80B), + new Interval(0xA825, 0xA826), new Interval(0xFB1E, 0xFB1E), new Interval(0xFE00, 0xFE0F), + new Interval(0xFE20, 0xFE23), new Interval(0xFEFF, 0xFEFF), new Interval(0xFFF9, 0xFFFB), + new Interval(0x10A01, 0x10A03), new Interval(0x10A05, 0x10A06), new Interval(0x10A0C, 0x10A0F), + new Interval(0x10A38, 0x10A3A), new Interval(0x10A3F, 0x10A3F), new Interval(0x1D167, 0x1D169), + new Interval(0x1D173, 0x1D182), new Interval(0x1D185, 0x1D18B), new Interval(0x1D1AA, 0x1D1AD), + new Interval(0x1D242, 0x1D244), new Interval(0x1F3FB, 0x1F3FF), new Interval(0xE0001, 0xE0001), + new Interval(0xE0020, 0xE007F), new Interval(0xE0100, 0xE01EF) }; private static class Interval { @@ -143,20 +140,14 @@ int min = 0; int mid; - if (ucs < table[0].first || ucs > table[max].last) - return false; + if (ucs < table[0].first || ucs > table[max].last) return false; while (max >= min) { mid = (min + max) / 2; - if (ucs > table[mid].last) - min = mid + 1; - else if (ucs < table[mid].first) - max = mid - 1; - else - return true; + if (ucs > table[mid].last) min = mid + 1; + else if (ucs < table[mid].first) max = mid - 1; + else return true; } return false; } - - } diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WriterOutputStream.java openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WriterOutputStream.java --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WriterOutputStream.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/WriterOutputStream.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002-2017, the original author or authors. + * Copyright (c) 2002-2017, the original author(s). * * This software is distributable under the BSD license. See the terms of the * BSD license in the documentation provided with this software. @@ -35,9 +35,11 @@ private final CharBuffer decoderOut = CharBuffer.allocate(128); public WriterOutputStream(Writer out, Charset charset) { - this(out, charset.newDecoder() - .onMalformedInput(CodingErrorAction.REPLACE) - .onUnmappableCharacter(CodingErrorAction.REPLACE)); + this( + out, + charset.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE)); } public WriterOutputStream(Writer out, CharsetDecoder decoder) { @@ -47,7 +49,7 @@ @Override public void write(int b) throws IOException { - write(new byte[] { (byte)b }, 0, 1); + write(new byte[] {(byte) b}, 0, 1); } @Override diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/windows-conemu.caps openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/windows-conemu.caps --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/windows-conemu.caps 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/classes/jdk/internal/org/jline/utils/windows-conemu.caps 2025-04-09 19:45:33.000000000 +0000 @@ -5,6 +5,9 @@ cr=^M, cub=\E[%p1%dD, cub1=\E[D, cud=\E[%p1%dB, cud1=\E[B, cuf=\E[%p1%dC, cuf1=\E[C, cup=\E[%i%p1%d;%p2%dH, cuu=\E[%p1%dA, cuu1=\E[A, + civis=\E[?25l, cvvis=\E[?25h, + smcup=\E[?1049h, rmcup=\E[?1049l, + rc=\E8, sc=\E7, il=\E[%p1%dL, il1=\E[L, dl=\E[%p1%dM, dl1=\E[M, ech=\E[%p1%dX, diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/share/legal/jline.md openjdk-17-17.0.15+6/src/jdk.internal.le/share/legal/jline.md --- openjdk-17-17.0.14+7/src/jdk.internal.le/share/legal/jline.md 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/src/jdk.internal.le/share/legal/jline.md 2025-04-09 19:45:33.000000000 +0000 @@ -1,9 +1,9 @@ -## JLine v3.22.0 +## JLine v3.26.1 ### JLine License
 
-Copyright (c) 2002-2018, the original author or authors.
+Copyright (c) 2002-2023, the original author or authors.
 All rights reserved.
 
 https://opensource.org/licenses/BSD-3-Clause
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/JnaTerminalProvider.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/JnaTerminalProvider.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/JnaTerminalProvider.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/JnaTerminalProvider.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2020, the original author or authors.
+ * Copyright (c) 2002-2020, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -8,99 +8,146 @@
  */
 package jdk.internal.org.jline.terminal.impl.jna;
 
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+import java.util.function.Function;
+
 import jdk.internal.org.jline.terminal.Attributes;
 import jdk.internal.org.jline.terminal.Size;
 import jdk.internal.org.jline.terminal.Terminal;
-import jdk.internal.org.jline.terminal.impl.PosixPtyTerminal;
-import jdk.internal.org.jline.terminal.impl.PosixSysTerminal;
+import jdk.internal.org.jline.terminal.TerminalBuilder;
+//import jdk.internal.org.jline.terminal.impl.PosixPtyTerminal;
+//import jdk.internal.org.jline.terminal.impl.PosixSysTerminal;
 import jdk.internal.org.jline.terminal.impl.jna.win.JnaWinSysTerminal;
-import jdk.internal.org.jline.terminal.spi.TerminalProvider;
 import jdk.internal.org.jline.terminal.spi.Pty;
+import jdk.internal.org.jline.terminal.spi.SystemStream;
+import jdk.internal.org.jline.terminal.spi.TerminalProvider;
 import jdk.internal.org.jline.utils.OSUtils;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.charset.Charset;
-import java.util.function.Function;
+public class JnaTerminalProvider implements TerminalProvider {
+
+    public JnaTerminalProvider() {
+        checkSystemStream(SystemStream.Output);
+    }
 
-public class JnaTerminalProvider implements TerminalProvider
-{
     @Override
     public String name() {
-        return "jna";
+        return TerminalBuilder.PROP_PROVIDER_JNA;
     }
 
-//    public Pty current(TerminalProvider.Stream console) throws IOException {
-//        return JnaNativePty.current(console);
+//    public Pty current(SystemStream systemStream) throws IOException {
+//        return JnaNativePty.current(this, systemStream);
 //    }
 //
 //    public Pty open(Attributes attributes, Size size) throws IOException {
-//        return JnaNativePty.open(attributes, size);
+//        return JnaNativePty.open(this, attributes, size);
 //    }
 
     @Override
-    public Terminal sysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding,
-                                boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused,
-                                Stream consoleStream, Function inputStreamWrapper) throws IOException {
+    public Terminal sysTerminal(
+            String name,
+            String type,
+            boolean ansiPassThrough,
+            Charset encoding,
+            boolean nativeSignals,
+            Terminal.SignalHandler signalHandler,
+            boolean paused,
+            SystemStream systemStream,
+            Function inputStreamWrapper)
+            throws IOException {
         if (OSUtils.IS_WINDOWS) {
-            return winSysTerminal(name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, consoleStream, inputStreamWrapper );
+            return winSysTerminal(name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, systemStream, inputStreamWrapper );
         } else {
             return null;
         }
     }
 
-    public Terminal winSysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding,
-                                   boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused,
-                                   Stream console, Function inputStreamWrapper) throws IOException {
-        return JnaWinSysTerminal.createTerminal(name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, console, inputStreamWrapper);
-    }
-
-//    public Terminal posixSysTerminal(String name, String type, boolean ansiPassThrough, Charset encoding,
-//                                     boolean nativeSignals, Terminal.SignalHandler signalHandler, boolean paused,
-//                                     Stream consoleStream) throws IOException {
-//        Pty pty = current(consoleStream);
+    public Terminal winSysTerminal(
+            String name,
+            String type,
+            boolean ansiPassThrough,
+            Charset encoding,
+            boolean nativeSignals,
+            Terminal.SignalHandler signalHandler,
+            boolean paused,
+            SystemStream systemStream,
+            Function inputStreamWrapper)
+            throws IOException {
+        return JnaWinSysTerminal.createTerminal(
+                this, systemStream, name, type, ansiPassThrough, encoding, nativeSignals, signalHandler, paused, inputStreamWrapper);
+    }
+
+//    public Terminal posixSysTerminal(
+//            String name,
+//            String type,
+//            boolean ansiPassThrough,
+//            Charset encoding,
+//            boolean nativeSignals,
+//            Terminal.SignalHandler signalHandler,
+//            boolean paused,
+//            SystemStream systemStream)
+//            throws IOException {
+//        Pty pty = current(systemStream);
 //        return new PosixSysTerminal(name, type, pty, encoding, nativeSignals, signalHandler);
 //    }
 
     @Override
-    public Terminal newTerminal(String name, String type, InputStream in, OutputStream out,
-                                Charset encoding, Terminal.SignalHandler signalHandler, boolean paused,
-                                Attributes attributes, Size size) throws IOException
-    {
+    public Terminal newTerminal(
+            String name,
+            String type,
+            InputStream in,
+            OutputStream out,
+            Charset encoding,
+            Terminal.SignalHandler signalHandler,
+            boolean paused,
+            Attributes attributes,
+            Size size)
+            throws IOException {
 //        Pty pty = open(attributes, size);
 //        return new PosixPtyTerminal(name, type, pty, in, out, encoding, signalHandler, paused);
         return null;
     }
 
     @Override
-    public boolean isSystemStream(Stream stream) {
+    public boolean isSystemStream(SystemStream stream) {
         try {
-            if (OSUtils.IS_WINDOWS) {
-                return isWindowsSystemStream(stream);
-            } else {
-//                return isPosixSystemStream(stream);
-                return false;
-            }
+            return checkSystemStream(stream);
         } catch (Throwable t) {
             return false;
         }
     }
 
-    public boolean isWindowsSystemStream(Stream stream) {
-        return JnaWinSysTerminal.isWindowsSystemStream(stream);
+    private boolean checkSystemStream(SystemStream stream) {
+        if (OSUtils.IS_WINDOWS) {
+            return JnaWinSysTerminal.isWindowsSystemStream(stream);
+        } else {
+//            return JnaNativePty.isPosixSystemStream(stream);
+            return false;
+        }
     }
 
-//    public boolean isPosixSystemStream(Stream stream) {
-//        return JnaNativePty.isPosixSystemStream(stream);
-//    }
-
     @Override
-    public String systemStreamName(Stream stream) {
+    public String systemStreamName(SystemStream stream) {
 //        if (OSUtils.IS_WINDOWS) {
             return null;
 //        } else {
 //            return JnaNativePty.posixSystemStreamName(stream);
 //        }
     }
+
+//    @Override
+//    public int systemStreamWidth(SystemStream stream) {
+//        try (Pty pty = current(stream)) {
+//            return pty.getSize().getColumns();
+//        } catch (Throwable t) {
+//            return -1;
+//        }
+//    }
+
+    @Override
+    public String toString() {
+        return "TerminalProvider[" + name() + "]";
+    }
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinConsoleWriter.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinConsoleWriter.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinConsoleWriter.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinConsoleWriter.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2017, the original author or authors.
+ * Copyright (c) 2002-2017, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -8,12 +8,13 @@
  */
 package jdk.internal.org.jline.terminal.impl.jna.win;
 
+import java.io.IOException;
+
+import jdk.internal.org.jline.terminal.impl.AbstractWindowsConsoleWriter;
+
 //import com.sun.jna.LastErrorException;
 //import com.sun.jna.Pointer;
 //import com.sun.jna.ptr.IntByReference;
-import jdk.internal.org.jline.terminal.impl.AbstractWindowsConsoleWriter;
-
-import java.io.IOException;
 
 class JnaWinConsoleWriter extends AbstractWindowsConsoleWriter {
 
@@ -32,5 +33,4 @@
             throw new IOException("Failed to write to console", e);
         }
     }
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinSysTerminal.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinSysTerminal.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinSysTerminal.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/JnaWinSysTerminal.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2020, the original author or authors.
+ * Copyright (c) 2002-2020, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -16,25 +16,43 @@
 import java.util.function.Function;
 import java.util.function.IntConsumer;
 
-//import com.sun.jna.LastErrorException;
-//import com.sun.jna.Pointer;
-//import com.sun.jna.ptr.IntByReference;
 import jdk.internal.org.jline.terminal.Cursor;
 import jdk.internal.org.jline.terminal.Size;
 import jdk.internal.org.jline.terminal.impl.AbstractWindowsTerminal;
+import jdk.internal.org.jline.terminal.spi.SystemStream;
 import jdk.internal.org.jline.terminal.spi.TerminalProvider;
+import jdk.internal.org.jline.utils.InfoCmp.Capability;
 import jdk.internal.org.jline.utils.InfoCmp;
 import jdk.internal.org.jline.utils.OSUtils;
 
-public class JnaWinSysTerminal extends AbstractWindowsTerminal {
+//import com.sun.jna.LastErrorException;
+//import com.sun.jna.Pointer;
+//import com.sun.jna.ptr.IntByReference;
+
+public class JnaWinSysTerminal extends AbstractWindowsTerminal {
 
     private static final Pointer consoleIn = Kernel32.INSTANCE.GetStdHandle(Kernel32.STD_INPUT_HANDLE);
     private static final Pointer consoleOut = Kernel32.INSTANCE.GetStdHandle(Kernel32.STD_OUTPUT_HANDLE);
     private static final Pointer consoleErr = Kernel32.INSTANCE.GetStdHandle(Kernel32.STD_ERROR_HANDLE);
 
-    public static JnaWinSysTerminal createTerminal(String name, String type, boolean ansiPassThrough, Charset encoding, boolean nativeSignals, SignalHandler signalHandler, boolean paused, TerminalProvider.Stream consoleStream, Function inputStreamWrapper) throws IOException {
+    public static JnaWinSysTerminal createTerminal(
+            TerminalProvider provider,
+            SystemStream systemStream,
+            String name,
+            String type,
+            boolean ansiPassThrough,
+            Charset encoding,
+            boolean nativeSignals,
+            SignalHandler signalHandler,
+            boolean paused,
+            Function inputStreamWrapper)
+            throws IOException {
+        // Get input console mode
+        IntByReference inMode = new IntByReference();
+        Kernel32.INSTANCE.GetConsoleMode(JnaWinSysTerminal.consoleIn, inMode);
+        // Get output console and mode
         Pointer console;
-        switch (consoleStream) {
+        switch (systemStream) {
             case Output:
                 console = JnaWinSysTerminal.consoleOut;
                 break;
@@ -42,38 +60,42 @@
                 console = JnaWinSysTerminal.consoleErr;
                 break;
             default:
-                throw new IllegalArgumentException("Unsupport stream for console: " + consoleStream);
+                throw new IllegalArgumentException("Unsupported stream for console: " + systemStream);
         }
+        IntByReference outMode = new IntByReference();
+        Kernel32.INSTANCE.GetConsoleMode(console, outMode);
+        // Create writer
         Writer writer;
         if (ansiPassThrough) {
-            if (type == null) {
-                type = OSUtils.IS_CONEMU ? TYPE_WINDOWS_CONEMU : TYPE_WINDOWS;
-            }
+            type = type != null ? type : OSUtils.IS_CONEMU ? TYPE_WINDOWS_CONEMU : TYPE_WINDOWS;
             writer = new JnaWinConsoleWriter(console);
         } else {
-            IntByReference mode = new IntByReference();
-            Kernel32.INSTANCE.GetConsoleMode(console, mode);
-            try {
-                Kernel32.INSTANCE.SetConsoleMode(console, mode.getValue() | AbstractWindowsTerminal.ENABLE_VIRTUAL_TERMINAL_PROCESSING);
-                if (type == null) {
-                    type = TYPE_WINDOWS_VTP;
-                }
+            if (enableVtp(console, outMode.getValue())) {
+                type = type != null ? type : TYPE_WINDOWS_VTP;
                 writer = new JnaWinConsoleWriter(console);
-            } catch (LastErrorException e) {
-                if (OSUtils.IS_CONEMU) {
-                    if (type == null) {
-                        type = TYPE_WINDOWS_CONEMU;
-                    }
-                    writer = new JnaWinConsoleWriter(console);
-                } else {
-                    if (type == null) {
-                        type = TYPE_WINDOWS;
-                    }
-                    writer = new WindowsAnsiWriter(new BufferedWriter(new JnaWinConsoleWriter(console)), console);
-                }
+            } else if (OSUtils.IS_CONEMU) {
+                type = type != null ? type : TYPE_WINDOWS_CONEMU;
+                writer = new JnaWinConsoleWriter(console);
+            } else {
+                type = type != null ? type : TYPE_WINDOWS;
+                writer = new WindowsAnsiWriter(new BufferedWriter(new JnaWinConsoleWriter(console)), console);
             }
         }
-        JnaWinSysTerminal terminal = new JnaWinSysTerminal(writer, name, type, encoding, nativeSignals, signalHandler, inputStreamWrapper);
+        // Create terminal
+        JnaWinSysTerminal terminal = new JnaWinSysTerminal(
+                provider,
+                systemStream,
+                writer,
+                name,
+                type,
+                encoding,
+                nativeSignals,
+                signalHandler,
+                JnaWinSysTerminal.consoleIn,
+                inMode.getValue(),
+                console,
+                outMode.getValue(),
+                inputStreamWrapper);
         // Start input pump thread
         if (!paused) {
             terminal.resume();
@@ -81,15 +103,32 @@
         return terminal;
     }
 
-    public static boolean isWindowsSystemStream(TerminalProvider.Stream stream) {
+    private static boolean enableVtp(Pointer console, int outMode) {
+        try {
+            Kernel32.INSTANCE.SetConsoleMode(
+                    console, outMode | AbstractWindowsTerminal.ENABLE_VIRTUAL_TERMINAL_PROCESSING);
+            return true;
+        } catch (LastErrorException e) {
+            return false;
+        }
+    }
+
+    public static boolean isWindowsSystemStream(SystemStream stream) {
         try {
             IntByReference mode = new IntByReference();
             Pointer console;
             switch (stream) {
-                case Input: console = consoleIn; break;
-                case Output: console = consoleOut; break;
-                case Error: console = consoleErr; break;
-                default: return false;
+                case Input:
+                    console = consoleIn;
+                    break;
+                case Output:
+                    console = consoleOut;
+                    break;
+                case Error:
+                    console = consoleErr;
+                    break;
+                default:
+                    return false;
             }
             Kernel32.INSTANCE.GetConsoleMode(console, mode);
             return true;
@@ -98,27 +137,53 @@
         }
     }
 
-    JnaWinSysTerminal(Writer writer, String name, String type, Charset encoding, boolean nativeSignals, SignalHandler signalHandler,
-            Function inputStreamWrapper) throws IOException {
-        super(writer, name, type, encoding, nativeSignals, signalHandler, inputStreamWrapper);
-        strings.put(InfoCmp.Capability.key_mouse, "\\E[M");
+    JnaWinSysTerminal(
+            TerminalProvider provider,
+            SystemStream systemStream,
+            Writer writer,
+            String name,
+            String type,
+            Charset encoding,
+            boolean nativeSignals,
+            SignalHandler signalHandler,
+            Pointer inConsole,
+            int inConsoleMode,
+            Pointer outConsole,
+            int outConsoleMode,
+            Function inputStreamWrapper)
+            throws IOException {
+        super(
+                provider,
+                systemStream,
+                writer,
+                name,
+                type,
+                encoding,
+                nativeSignals,
+                signalHandler,
+                inConsole,
+                inConsoleMode,
+                outConsole,
+                outConsoleMode,
+                inputStreamWrapper);
+        this.strings.put(Capability.key_mouse, "\\E[M");
     }
 
     @Override
-    protected int getConsoleMode() {
+    protected int getConsoleMode(Pointer console) {
         IntByReference mode = new IntByReference();
-        Kernel32.INSTANCE.GetConsoleMode(consoleIn, mode);
+        Kernel32.INSTANCE.GetConsoleMode(console, mode);
         return mode.getValue();
     }
 
     @Override
-    protected void setConsoleMode(int mode) {
-        Kernel32.INSTANCE.SetConsoleMode(consoleIn, mode);
+    protected void setConsoleMode(Pointer console, int mode) {
+        Kernel32.INSTANCE.SetConsoleMode(console, mode);
     }
 
     public Size getSize() {
         Kernel32.CONSOLE_SCREEN_BUFFER_INFO info = new Kernel32.CONSOLE_SCREEN_BUFFER_INFO();
-        Kernel32.INSTANCE.GetConsoleScreenBufferInfo(consoleOut, info);
+        Kernel32.INSTANCE.GetConsoleScreenBufferInfo(outConsole, info);
         return new Size(info.windowWidth(), info.windowHeight());
     }
 
@@ -154,10 +219,11 @@
     }
 
     private void processKeyEvent(Kernel32.KEY_EVENT_RECORD keyEvent) throws IOException {
-        processKeyEvent(keyEvent.bKeyDown, keyEvent.wVirtualKeyCode, keyEvent.uChar.UnicodeChar, keyEvent.dwControlKeyState);
+        processKeyEvent(
+                keyEvent.bKeyDown, keyEvent.wVirtualKeyCode, keyEvent.uChar.UnicodeChar, keyEvent.dwControlKeyState);
     }
 
-    private char[] focus = new char[] { '\033', '[', ' ' };
+    private char[] focus = new char[] {'\033', '[', ' '};
 
     private void processFocusEvent(boolean hasFocus) throws IOException {
         if (focusTracking) {
@@ -166,7 +232,7 @@
         }
     }
 
-    private char[] mouse = new char[] { '\033', '[', 'M', ' ', ' ', ' ' };
+    private char[] mouse = new char[] {'\033', '[', 'M', ' ', ' ', ' '};
 
     private void processMouseEvent(Kernel32.MOUSE_EVENT_RECORD mouseEvent) throws IOException {
         int dwEventFlags = mouseEvent.dwEventFlags;
@@ -177,7 +243,7 @@
             return;
         }
         int cb = 0;
-        dwEventFlags &= ~ Kernel32.DOUBLE_CLICK; // Treat double-clicks as normal
+        dwEventFlags &= ~Kernel32.DOUBLE_CLICK; // Treat double-clicks as normal
         if (dwEventFlags == Kernel32.MOUSE_WHEELED) {
             cb |= 64;
             if ((dwButtonState >> 16) < 0) {
@@ -223,5 +289,4 @@
         Kernel32.INSTANCE.GetConsoleScreenBufferInfo(consoleOut, info);
         return new Cursor(info.dwCursorPosition.X, info.dwCursorPosition.Y);
     }
-
 }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2018, the original author or authors.
+ * Copyright (c) 2002-2018, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -30,46 +30,46 @@
 
 //    Pointer INVALID_HANDLE_VALUE = Pointer.createConstant(-1L);
 
-    int STD_INPUT_HANDLE =  -10;
+    int STD_INPUT_HANDLE = -10;
     int STD_OUTPUT_HANDLE = -11;
-    int STD_ERROR_HANDLE =  -12;
+    int STD_ERROR_HANDLE = -12;
 
-    int ENABLE_PROCESSED_INPUT =    0x0001;
-    int ENABLE_LINE_INPUT =         0x0002;
-    int ENABLE_ECHO_INPUT =         0x0004;
-    int ENABLE_WINDOW_INPUT =       0x0008;
-    int ENABLE_MOUSE_INPUT =        0x0010;
-    int ENABLE_INSERT_MODE =        0x0020;
-    int ENABLE_QUICK_EDIT_MODE =    0x0040;
-    int ENABLE_EXTENDED_FLAGS =     0x0080;
-
-    int RIGHT_ALT_PRESSED =     0x0001;
-    int LEFT_ALT_PRESSED =      0x0002;
-    int RIGHT_CTRL_PRESSED =    0x0004;
-    int LEFT_CTRL_PRESSED =     0x0008;
-    int SHIFT_PRESSED =         0x0010;
-
-    int FOREGROUND_BLUE =       0x0001;
-    int FOREGROUND_GREEN =      0x0002;
-    int FOREGROUND_RED =        0x0004;
-    int FOREGROUND_INTENSITY =  0x0008;
-    int BACKGROUND_BLUE =       0x0010;
-    int BACKGROUND_GREEN =      0x0020;
-    int BACKGROUND_RED =        0x0040;
-    int BACKGROUND_INTENSITY =  0x0080;
+    int ENABLE_PROCESSED_INPUT = 0x0001;
+    int ENABLE_LINE_INPUT = 0x0002;
+    int ENABLE_ECHO_INPUT = 0x0004;
+    int ENABLE_WINDOW_INPUT = 0x0008;
+    int ENABLE_MOUSE_INPUT = 0x0010;
+    int ENABLE_INSERT_MODE = 0x0020;
+    int ENABLE_QUICK_EDIT_MODE = 0x0040;
+    int ENABLE_EXTENDED_FLAGS = 0x0080;
+
+    int RIGHT_ALT_PRESSED = 0x0001;
+    int LEFT_ALT_PRESSED = 0x0002;
+    int RIGHT_CTRL_PRESSED = 0x0004;
+    int LEFT_CTRL_PRESSED = 0x0008;
+    int SHIFT_PRESSED = 0x0010;
+
+    int FOREGROUND_BLUE = 0x0001;
+    int FOREGROUND_GREEN = 0x0002;
+    int FOREGROUND_RED = 0x0004;
+    int FOREGROUND_INTENSITY = 0x0008;
+    int BACKGROUND_BLUE = 0x0010;
+    int BACKGROUND_GREEN = 0x0020;
+    int BACKGROUND_RED = 0x0040;
+    int BACKGROUND_INTENSITY = 0x0080;
 
     // Button state
     int FROM_LEFT_1ST_BUTTON_PRESSED = 0x0001;
-    int RIGHTMOST_BUTTON_PRESSED     = 0x0002;
+    int RIGHTMOST_BUTTON_PRESSED = 0x0002;
     int FROM_LEFT_2ND_BUTTON_PRESSED = 0x0004;
     int FROM_LEFT_3RD_BUTTON_PRESSED = 0x0008;
     int FROM_LEFT_4TH_BUTTON_PRESSED = 0x0010;
 
     // Event flags
-    int MOUSE_MOVED                  = 0x0001;
-    int DOUBLE_CLICK                 = 0x0002;
-    int MOUSE_WHEELED                = 0x0004;
-    int MOUSE_HWHEELED               = 0x0008;
+    int MOUSE_MOVED = 0x0001;
+    int DOUBLE_CLICK = 0x0002;
+    int MOUSE_WHEELED = 0x0004;
+    int MOUSE_HWHEELED = 0x0008;
 
     // DWORD WINAPI WaitForSingleObject(
     //  _In_ HANDLE hHandle,
@@ -94,18 +94,18 @@
 //    // UINT WINAPI GetConsoleCP(void)
 //    int GetConsoleCP();
 //
-    // UINT WINAPI GetConsoleOutputCP(void)
-    int GetConsoleOutputCP();
-
     // BOOL WINAPI FillConsoleOutputCharacter(
     // _In_ HANDLE hConsoleOutput,
     // _In_ TCHAR cCharacter,
     // _In_ DWORD nLength,
     // _In_ COORD dwWriteCoord,
     // _Out_ LPDWORD lpNumberOfCharsWritten);
-    void FillConsoleOutputCharacter(Pointer in_hConsoleOutput,
-                                    char in_cCharacter, int in_nLength, COORD in_dwWriteCoord,
-                                    IntByReference out_lpNumberOfCharsWritten)
+    void FillConsoleOutputCharacter(
+            Pointer in_hConsoleOutput,
+            char in_cCharacter,
+            int in_nLength,
+            COORD in_dwWriteCoord,
+            IntByReference out_lpNumberOfCharsWritten)
             throws LastErrorException;
 
     // BOOL WINAPI FillConsoleOutputAttribute(
@@ -114,56 +114,53 @@
     // _In_ DWORD nLength,
     // _In_ COORD dwWriteCoord,
     // _Out_ LPDWORD lpNumberOfAttrsWritten);
-    void FillConsoleOutputAttribute(Pointer in_hConsoleOutput,
-                                    short in_wAttribute, int in_nLength, COORD in_dwWriteCoord,
-                                    IntByReference out_lpNumberOfAttrsWritten)
+    void FillConsoleOutputAttribute(
+            Pointer in_hConsoleOutput,
+            short in_wAttribute,
+            int in_nLength,
+            COORD in_dwWriteCoord,
+            IntByReference out_lpNumberOfAttrsWritten)
             throws LastErrorException;
-//
-////    // BOOL WINAPI GetConsoleCursorInfo(
-////    // _In_ HANDLE hConsoleOutput,
-////    // _Out_ PCONSOLE_CURSOR_INFO lpConsoleCursorInfo);
-////    void GetConsoleCursorInfo(Pointer in_hConsoleOutput,
-////                              CONSOLE_CURSOR_INFO.ByReference out_lpConsoleCursorInfo)
-////            throws LastErrorException;
-//
+
+//    // BOOL WINAPI GetConsoleCursorInfo(
+//    // _In_ HANDLE hConsoleOutput,
+//    // _Out_ PCONSOLE_CURSOR_INFO lpConsoleCursorInfo);
+//    void GetConsoleCursorInfo(Pointer in_hConsoleOutput, CONSOLE_CURSOR_INFO.ByReference out_lpConsoleCursorInfo)
+//            throws LastErrorException;
+
     // BOOL WINAPI GetConsoleMode(
     //   _In_   HANDLE hConsoleHandle,
     //   _Out_  LPDWORD lpMode);
-    void GetConsoleMode(
-            Pointer in_hConsoleOutput,
-            IntByReference out_lpMode)
-            throws LastErrorException;
+    void GetConsoleMode(Pointer in_hConsoleOutput, IntByReference out_lpMode) throws LastErrorException;
 
     // BOOL WINAPI GetConsoleScreenBufferInfo(
     // _In_   HANDLE hConsoleOutput,
     // _Out_  PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo);
-    void GetConsoleScreenBufferInfo(
-            Pointer in_hConsoleOutput,
-            CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo)
+    void GetConsoleScreenBufferInfo(Pointer in_hConsoleOutput, CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo)
             throws LastErrorException;
 //
 //    // BOOL WINAPI GetNumberOfConsoleInputEvents(
 //    // _In_ HANDLE hConsoleInput,
 //    // _Out_ LPDWORD lpcNumberOfEvents);
-//    void GetNumberOfConsoleInputEvents(Pointer in_hConsoleOutput,
-//                                       IntByReference out_lpcNumberOfEvents) throws LastErrorException;
+//    void GetNumberOfConsoleInputEvents(Pointer in_hConsoleOutput, IntByReference out_lpcNumberOfEvents)
+//            throws LastErrorException;
 //
     // BOOL WINAPI ReadConsoleInput(
     // _In_ HANDLE hConsoleInput,
     // _Out_ PINPUT_RECORD lpBuffer,
     // _In_ DWORD nLength,
     // _Out_ LPDWORD lpNumberOfEventsRead);
-    void ReadConsoleInput(Pointer in_hConsoleOutput,
-                          INPUT_RECORD[] out_lpBuffer, int in_nLength,
-                          IntByReference out_lpNumberOfEventsRead) throws LastErrorException;
+    void ReadConsoleInput(
+            Pointer in_hConsoleOutput,
+            INPUT_RECORD[] out_lpBuffer,
+            int in_nLength,
+            IntByReference out_lpNumberOfEventsRead)
+            throws LastErrorException;
 
 //    // BOOL WINAPI SetConsoleCtrlHandler(
 //    // _In_opt_  PHANDLER_ROUTINE HandlerRoutine,
 //    // _In_      BOOL Add);
-//    void SetConsoleCtrlHandler(
-//            Pointer in_opt_HandlerRoutine,
-//            boolean in_Add)
-//            throws LastErrorException;
+//    void SetConsoleCtrlHandler(Pointer in_opt_HandlerRoutine, boolean in_Add) throws LastErrorException;
 //
 //    // BOOL WINAPI ReadConsoleOutput(
 //    // _In_     HANDLE hConsoleOutput,
@@ -171,12 +168,21 @@
 //    // _In_     COORD dwBufferSize,
 //    // _In_     COORD dwBufferCoord,
 //    // _Inout_  PSMALL_RECT lpReadRegion);
-////    void ReadConsoleOutput(Pointer in_hConsoleOutput, CHAR_INFO[] out_lpBuffer,
-////                           COORD in_dwBufferSize, COORD in_dwBufferCoord,
-////                           SMALL_RECT inout_lpReadRegion) throws LastErrorException;
-////    void ReadConsoleOutputA(Pointer in_hConsoleOutput, CHAR_INFO[] out_lpBuffer,
-////                            COORD in_dwBufferSize, COORD in_dwBufferCoord,
-////                            SMALL_RECT inout_lpReadRegion) throws LastErrorException;
+//    void ReadConsoleOutput(
+//            Pointer in_hConsoleOutput,
+//            CHAR_INFO[] out_lpBuffer,
+//            COORD in_dwBufferSize,
+//            COORD in_dwBufferCoord,
+//            SMALL_RECT inout_lpReadRegion)
+//            throws LastErrorException;
+//
+//    void ReadConsoleOutputA(
+//            Pointer in_hConsoleOutput,
+//            CHAR_INFO[] out_lpBuffer,
+//            COORD in_dwBufferSize,
+//            COORD in_dwBufferCoord,
+//            SMALL_RECT inout_lpReadRegion)
+//            throws LastErrorException;
 //
 //    // BOOL WINAPI ReadConsoleOutputCharacter(
 //    // _In_   HANDLE hConsoleOutput,
@@ -184,20 +190,26 @@
 //    // _In_   DWORD nLength,
 //    // _In_   COORD dwReadCoord,
 //    // _Out_  LPDWORD lpNumberOfCharsRead);
-//    void ReadConsoleOutputCharacter(Pointer in_hConsoleOutput,
-//                                    char[] ouy_lpCharacter, int in_nLength, COORD in_dwReadCoord,
-//                                    IntByReference out_lpNumberOfCharsRead)
-//            throws LastErrorException;
-//    void ReadConsoleOutputCharacterA(Pointer in_hConsoleOutput,
-//                                     byte[] ouy_lpCharacter, int in_nLength, COORD in_dwReadCoord,
-//                                     IntByReference out_lpNumberOfCharsRead)
+//    void ReadConsoleOutputCharacter(
+//            Pointer in_hConsoleOutput,
+//            char[] ouy_lpCharacter,
+//            int in_nLength,
+//            COORD in_dwReadCoord,
+//            IntByReference out_lpNumberOfCharsRead)
+//            throws LastErrorException;
+//
+//    void ReadConsoleOutputCharacterA(
+//            Pointer in_hConsoleOutput,
+//            byte[] ouy_lpCharacter,
+//            int in_nLength,
+//            COORD in_dwReadCoord,
+//            IntByReference out_lpNumberOfCharsRead)
 //            throws LastErrorException;
 //
 //    // BOOL WINAPI SetConsoleCursorInfo(
 //    // _In_ HANDLE hConsoleOutput,
 //    // _In_ const CONSOLE_CURSOR_INFO *lpConsoleCursorInfo);
-//    void SetConsoleCursorInfo(Pointer in_hConsoleOutput,
-//                              CONSOLE_CURSOR_INFO in_lpConsoleCursorInfo)
+//    void SetConsoleCursorInfo(Pointer in_hConsoleOutput, CONSOLE_CURSOR_INFO in_lpConsoleCursorInfo)
 //            throws LastErrorException;
 //
 //    // BOOL WINAPI SetConsoleCP(
@@ -207,47 +219,39 @@
 //    // BOOL WINAPI SetConsoleOutputCP(
 //    // _In_ UINT wCodePageID);
 //    void SetConsoleOutputCP(int in_wCodePageID) throws LastErrorException;
-//
+
     // BOOL WINAPI SetConsoleCursorPosition(
     // _In_ HANDLE hConsoleOutput,
     // _In_ COORD dwCursorPosition);
-    void SetConsoleCursorPosition(Pointer in_hConsoleOutput,
-                                  COORD in_dwCursorPosition) throws LastErrorException;
+    void SetConsoleCursorPosition(Pointer in_hConsoleOutput, COORD in_dwCursorPosition) throws LastErrorException;
 
     // BOOL WINAPI SetConsoleMode(
     //   _In_  HANDLE hConsoleHandle,
     //   _In_  DWORD dwMode);
-    void SetConsoleMode(
-            Pointer in_hConsoleOutput,
-            int in_dwMode) throws LastErrorException;
+    void SetConsoleMode(Pointer in_hConsoleOutput, int in_dwMode) throws LastErrorException;
 
 //    // BOOL WINAPI SetConsoleScreenBufferSize(
 //    // __in HANDLE hConsoleOutput,
 //    // __in COORD dwSize
 //    // );
-//    void SetConsoleScreenBufferSize(Pointer in_hConsoleOutput,
-//                                    COORD in_dwSize) throws LastErrorException;
-//
+//    void SetConsoleScreenBufferSize(Pointer in_hConsoleOutput, COORD in_dwSize) throws LastErrorException;
+
     // BOOL WINAPI SetConsoleTextAttribute(
     // _In_ HANDLE hConsoleOutput,
     // _In_ WORD   wAttributes
     // );
-    void SetConsoleTextAttribute(Pointer in_hConsoleOutput,
-                                 short in_wAttributes)
-            throws LastErrorException;
+    void SetConsoleTextAttribute(Pointer in_hConsoleOutput, short in_wAttributes) throws LastErrorException;
 
     // BOOL WINAPI SetConsoleTitle(
     // _In_ LPCTSTR lpConsoleTitle
     // );
-    void SetConsoleTitle(String in_lpConsoleTitle)
-            throws LastErrorException;
+    void SetConsoleTitle(String in_lpConsoleTitle) throws LastErrorException;
 
 //    // BOOL WINAPI SetConsoleWindowInfo(
 //    // _In_ HANDLE hConsoleOutput,
 //    // _In_ BOOL bAbsolute,
 //    // _In_ const SMALL_RECT *lpConsoleWindow);
-//    void SetConsoleWindowInfo(Pointer in_hConsoleOutput,
-//                              boolean in_bAbsolute, SMALL_RECT in_lpConsoleWindow)
+//    void SetConsoleWindowInfo(Pointer in_hConsoleOutput, boolean in_bAbsolute, SMALL_RECT in_lpConsoleWindow)
 //            throws LastErrorException;
 
     // BOOL WINAPI WriteConsole(
@@ -257,8 +261,13 @@
     //  _Out_            LPDWORD lpNumberOfCharsWritten,
     //  _Reserved_       LPVOID  lpReserved
     // );
-    void WriteConsoleW(Pointer in_hConsoleOutput, char[] in_lpBuffer, int in_nNumberOfCharsToWrite,
-                          IntByReference out_lpNumberOfCharsWritten, Pointer reserved_lpReserved) throws LastErrorException;
+    void WriteConsoleW(
+            Pointer in_hConsoleOutput,
+            char[] in_lpBuffer,
+            int in_nNumberOfCharsToWrite,
+            IntByReference out_lpNumberOfCharsWritten,
+            Pointer reserved_lpReserved)
+            throws LastErrorException;
 
 //    // BOOL WINAPI WriteConsoleOutput(
 //    // _In_ HANDLE hConsoleOutput,
@@ -266,12 +275,21 @@
 //    // _In_ COORD dwBufferSize,
 //    // _In_ COORD dwBufferCoord,
 //    // _Inout_ PSMALL_RECT lpWriteRegion);
-////    void WriteConsoleOutput(Pointer in_hConsoleOutput, CHAR_INFO[] in_lpBuffer,
-////                            COORD in_dwBufferSize, COORD in_dwBufferCoord,
-////                            SMALL_RECT inout_lpWriteRegion) throws LastErrorException;
-////    void WriteConsoleOutputA(Pointer in_hConsoleOutput, CHAR_INFO[] in_lpBuffer,
-////                             COORD in_dwBufferSize, COORD in_dwBufferCoord,
-////                             SMALL_RECT inout_lpWriteRegion) throws LastErrorException;
+//    void WriteConsoleOutput(
+//            Pointer in_hConsoleOutput,
+//            CHAR_INFO[] in_lpBuffer,
+//            COORD in_dwBufferSize,
+//            COORD in_dwBufferCoord,
+//            SMALL_RECT inout_lpWriteRegion)
+//            throws LastErrorException;
+//
+//    void WriteConsoleOutputA(
+//            Pointer in_hConsoleOutput,
+//            CHAR_INFO[] in_lpBuffer,
+//            COORD in_dwBufferSize,
+//            COORD in_dwBufferCoord,
+//            SMALL_RECT inout_lpWriteRegion)
+//            throws LastErrorException;
 //
 //    // BOOL WINAPI WriteConsoleOutputCharacter(
 //    // _In_ HANDLE hConsoleOutput,
@@ -279,26 +297,34 @@
 //    // _In_ DWORD nLength,
 //    // _In_ COORD dwWriteCoord,
 //    // _Out_ LPDWORD lpNumberOfCharsWritten);
-//    void WriteConsoleOutputCharacter(Pointer in_hConsoleOutput,
-//                                     char[] in_lpCharacter, int in_nLength, COORD in_dwWriteCoord,
-//                                     IntByReference out_lpNumberOfCharsWritten)
-//            throws LastErrorException;
-//    void WriteConsoleOutputCharacterA(Pointer in_hConsoleOutput,
-//                                      byte[] in_lpCharacter, int in_nLength, COORD in_dwWriteCoord,
-//                                      IntByReference out_lpNumberOfCharsWritten)
+//    void WriteConsoleOutputCharacter(
+//            Pointer in_hConsoleOutput,
+//            char[] in_lpCharacter,
+//            int in_nLength,
+//            COORD in_dwWriteCoord,
+//            IntByReference out_lpNumberOfCharsWritten)
 //            throws LastErrorException;
 //
+//    void WriteConsoleOutputCharacterA(
+//            Pointer in_hConsoleOutput,
+//            byte[] in_lpCharacter,
+//            int in_nLength,
+//            COORD in_dwWriteCoord,
+//            IntByReference out_lpNumberOfCharsWritten)
+//            throws LastErrorException;
+
     // BOOL WINAPI ScrollConsoleScreenBuffer(
     //     _In_           HANDLE     hConsoleOutput,
     //     _In_     const SMALL_RECT *lpScrollRectangle,
     //     _In_opt_ const SMALL_RECT *lpClipRectangle,
     //     _In_           COORD      dwDestinationOrigin,
     //     _In_     const CHAR_INFO  *lpFill);
-    void ScrollConsoleScreenBuffer(Pointer in_hConsoleOutput,
-                                   SMALL_RECT in_lpScrollRectangle,
-                                   SMALL_RECT in_lpClipRectangle,
-                                   COORD in_dwDestinationOrigin,
-                                   CHAR_INFO in_lpFill)
+    void ScrollConsoleScreenBuffer(
+            Pointer in_hConsoleOutput,
+            SMALL_RECT in_lpScrollRectangle,
+            SMALL_RECT in_lpClipRectangle,
+            COORD in_dwDestinationOrigin,
+            CHAR_INFO in_lpFill)
             throws LastErrorException;
 
     // typedef struct _CHAR_INFO {
@@ -309,8 +335,7 @@
     //   WORD  Attributes;
     // } CHAR_INFO, *PCHAR_INFO;
     class CHAR_INFO {//extends Structure {
-        public CHAR_INFO() {
-        }
+        public CHAR_INFO() {}
 
         public CHAR_INFO(char c, short attr) {
             uChar = new UnionChar(c);
@@ -329,7 +354,7 @@
 //            return (CHAR_INFO[]) new CHAR_INFO().toArray(size);
 //        }
 //
-//        private static String[] fieldOrder = { "uChar", "Attributes" };
+//        private static String[] fieldOrder = {"uChar", "Attributes"};
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -345,11 +370,9 @@
         public int dwSize;
         public boolean bVisible;
 
-//        public static class ByReference extends CONSOLE_CURSOR_INFO implements
-//                Structure.ByReference {
-//        }
+//        public static class ByReference extends CONSOLE_CURSOR_INFO implements Structure.ByReference {}
 //
-//        private static String[] fieldOrder = { "dwSize", "bVisible" };
+//        private static String[] fieldOrder = {"dwSize", "bVisible"};
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -365,13 +388,15 @@
     //   COORD      dwMaximumWindowSize;
     // } CONSOLE_SCREEN_BUFFER_INFO;
     class CONSOLE_SCREEN_BUFFER_INFO {//extends Structure {
-        public COORD      dwSize;
-        public COORD      dwCursorPosition;
-        public short      wAttributes;
+        public COORD dwSize;
+        public COORD dwCursorPosition;
+        public short wAttributes;
         public SMALL_RECT srWindow;
-        public COORD      dwMaximumWindowSize;
+        public COORD dwMaximumWindowSize;
 
-//        private static String[] fieldOrder = { "dwSize", "dwCursorPosition", "wAttributes", "srWindow", "dwMaximumWindowSize" };
+//        private static String[] fieldOrder = {
+//            "dwSize", "dwCursorPosition", "wAttributes", "srWindow", "dwMaximumWindowSize"
+//        };
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -392,8 +417,7 @@
     //    SHORT Y;
     //  } COORD, *PCOORD;
     class COORD {//extends Structure implements Structure.ByValue {
-        public COORD() {
-        }
+        public COORD() {}
 
         public COORD(short X, short Y) {
             this.X = X;
@@ -403,7 +427,7 @@
         public short X;
         public short Y;
 
-//        private static String[] fieldOrder = { "X", "Y" };
+//        private static String[] fieldOrder = {"X", "Y"};
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -489,7 +513,9 @@
         public UnionChar uChar;
         public int dwControlKeyState;
 
-//        private static String[] fieldOrder = {"bKeyDown", "wRepeatCount", "wVirtualKeyCode", "wVirtualScanCode", "uChar", "dwControlKeyState"};
+//        private static String[] fieldOrder = {
+//            "bKeyDown", "wRepeatCount", "wVirtualKeyCode", "wVirtualScanCode", "uChar", "dwControlKeyState"
+//        };
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -509,7 +535,7 @@
         public int dwControlKeyState;
         public int dwEventFlags;
 
-//        private static String[] fieldOrder = { "dwMousePosition", "dwButtonState", "dwControlKeyState", "dwEventFlags"};
+//        private static String[] fieldOrder = {"dwMousePosition", "dwButtonState", "dwControlKeyState", "dwEventFlags"};
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -548,7 +574,7 @@
 
     // typedef struct _FOCUS_EVENT_RECORD {
     //  BOOL bSetFocus;
-    //} FOCUS_EVENT_RECORD;
+    // } FOCUS_EVENT_RECORD;
     class FOCUS_EVENT_RECORD {//extends Structure {
         public boolean bSetFocus;
 
@@ -567,8 +593,7 @@
     //    SHORT Bottom;
     //  } SMALL_RECT;
     class SMALL_RECT {//extends Structure {
-        public SMALL_RECT() {
-        }
+        public SMALL_RECT() {}
 
         public SMALL_RECT(SMALL_RECT org) {
             this(org.Top, org.Left, org.Bottom, org.Right);
@@ -586,7 +611,7 @@
         public short Right;
         public short Bottom;
 
-//        private static String[] fieldOrder = { "Left", "Top", "Right", "Bottom" };
+//        private static String[] fieldOrder = {"Left", "Top", "Right", "Bottom"};
 //
 //        @Override
 //        protected java.util.List getFieldOrder() {
@@ -594,18 +619,16 @@
 //        }
 
         public short width() {
-            return (short)(this.Right - this.Left);
+            return (short) (this.Right - this.Left);
         }
 
         public short height() {
-            return (short)(this.Bottom - this.Top);
+            return (short) (this.Bottom - this.Top);
         }
-
     }
 
     class UnionChar {//extends Union {
-        public UnionChar() {
-        }
+        public UnionChar() {}
 
         public UnionChar(char c) {
 //            setType(char.class);
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32Impl.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32Impl.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32Impl.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/Kernel32Impl.java	2025-04-09 19:45:33.000000000 +0000
@@ -46,9 +46,6 @@
     public native Pointer GetStdHandle(int nStdHandle);
 
     @Override
-    public native int GetConsoleOutputCP();
-
-    @Override
     public native void FillConsoleOutputCharacter(Pointer in_hConsoleOutput, char in_cCharacter, int in_nLength, COORD in_dwWriteCoord, IntByReference out_lpNumberOfCharsWritten) throws LastErrorException;
 
     @Override
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/WindowsAnsiWriter.java openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/WindowsAnsiWriter.java
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/WindowsAnsiWriter.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/classes/jdk/internal/org/jline/terminal/impl/jna/win/WindowsAnsiWriter.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002-2016, the original author or authors.
+ * Copyright (c) 2002-2016, the original author(s).
  *
  * This software is distributable under the BSD license. See the terms of the
  * BSD license in the documentation provided with this software.
@@ -11,11 +11,12 @@
 import java.io.IOException;
 import java.io.Writer;
 
-//import com.sun.jna.Pointer;
-//import com.sun.jna.ptr.IntByReference;
 import jdk.internal.org.jline.utils.AnsiWriter;
 import jdk.internal.org.jline.utils.Colors;
 
+//import com.sun.jna.Pointer;
+//import com.sun.jna.ptr.IntByReference;
+
 import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_BLUE;
 import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_GREEN;
 import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.BACKGROUND_INTENSITY;
@@ -25,7 +26,6 @@
 import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_INTENSITY;
 import static jdk.internal.org.jline.terminal.impl.jna.win.Kernel32.FOREGROUND_RED;
 
-
 /**
  * A Windows ANSI escape processor, uses JNA to access native platform
  * API's to change the console attributes.
@@ -36,41 +36,41 @@
  */
 public final class WindowsAnsiWriter extends AnsiWriter {
 
-    private static final short FOREGROUND_BLACK   = 0;
-    private static final short FOREGROUND_YELLOW  = (short) (FOREGROUND_RED|FOREGROUND_GREEN);
-    private static final short FOREGROUND_MAGENTA = (short) (FOREGROUND_BLUE|FOREGROUND_RED);
-    private static final short FOREGROUND_CYAN    = (short) (FOREGROUND_BLUE|FOREGROUND_GREEN);
-    private static final short FOREGROUND_WHITE   = (short) (FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
-
-    private static final short BACKGROUND_BLACK   = 0;
-    private static final short BACKGROUND_YELLOW  = (short) (BACKGROUND_RED|BACKGROUND_GREEN);
-    private static final short BACKGROUND_MAGENTA = (short) (BACKGROUND_BLUE|BACKGROUND_RED);
-    private static final short BACKGROUND_CYAN    = (short) (BACKGROUND_BLUE|BACKGROUND_GREEN);
-    private static final short BACKGROUND_WHITE   = (short) (BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE);
+    private static final short FOREGROUND_BLACK = 0;
+    private static final short FOREGROUND_YELLOW = (short) (FOREGROUND_RED | FOREGROUND_GREEN);
+    private static final short FOREGROUND_MAGENTA = (short) (FOREGROUND_BLUE | FOREGROUND_RED);
+    private static final short FOREGROUND_CYAN = (short) (FOREGROUND_BLUE | FOREGROUND_GREEN);
+    private static final short FOREGROUND_WHITE = (short) (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
+
+    private static final short BACKGROUND_BLACK = 0;
+    private static final short BACKGROUND_YELLOW = (short) (BACKGROUND_RED | BACKGROUND_GREEN);
+    private static final short BACKGROUND_MAGENTA = (short) (BACKGROUND_BLUE | BACKGROUND_RED);
+    private static final short BACKGROUND_CYAN = (short) (BACKGROUND_BLUE | BACKGROUND_GREEN);
+    private static final short BACKGROUND_WHITE = (short) (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
 
     private static final short ANSI_FOREGROUND_COLOR_MAP[] = {
-            FOREGROUND_BLACK,
-            FOREGROUND_RED,
-            FOREGROUND_GREEN,
-            FOREGROUND_YELLOW,
-            FOREGROUND_BLUE,
-            FOREGROUND_MAGENTA,
-            FOREGROUND_CYAN,
-            FOREGROUND_WHITE,
+        FOREGROUND_BLACK,
+        FOREGROUND_RED,
+        FOREGROUND_GREEN,
+        FOREGROUND_YELLOW,
+        FOREGROUND_BLUE,
+        FOREGROUND_MAGENTA,
+        FOREGROUND_CYAN,
+        FOREGROUND_WHITE,
     };
 
     private static final short ANSI_BACKGROUND_COLOR_MAP[] = {
-            BACKGROUND_BLACK,
-            BACKGROUND_RED,
-            BACKGROUND_GREEN,
-            BACKGROUND_YELLOW,
-            BACKGROUND_BLUE,
-            BACKGROUND_MAGENTA,
-            BACKGROUND_CYAN,
-            BACKGROUND_WHITE,
+        BACKGROUND_BLACK,
+        BACKGROUND_RED,
+        BACKGROUND_GREEN,
+        BACKGROUND_YELLOW,
+        BACKGROUND_BLUE,
+        BACKGROUND_MAGENTA,
+        BACKGROUND_CYAN,
+        BACKGROUND_WHITE,
     };
 
-    private final static int MAX_ESCAPE_SEQUENCE_LENGTH = 100;
+    private static final int MAX_ESCAPE_SEQUENCE_LENGTH = 100;
 
     private final Pointer console;
 
@@ -134,7 +134,7 @@
     protected void processEraseScreen(int eraseOption) throws IOException {
         getConsoleInfo();
         IntByReference written = new IntByReference();
-        switch(eraseOption) {
+        switch (eraseOption) {
             case ERASE_SCREEN:
                 Kernel32.COORD topLeft = new Kernel32.COORD();
                 topLeft.X = 0;
@@ -147,36 +147,44 @@
                 Kernel32.COORD topLeft2 = new Kernel32.COORD();
                 topLeft2.X = 0;
                 topLeft2.Y = info.srWindow.Top;
-                int lengthToCursor = (info.dwCursorPosition.Y - info.srWindow.Top) * info.dwSize.X + info.dwCursorPosition.X;
+                int lengthToCursor =
+                        (info.dwCursorPosition.Y - info.srWindow.Top) * info.dwSize.X + info.dwCursorPosition.X;
                 Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToCursor, topLeft2, written);
-                Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToCursor, topLeft2, written);
+                Kernel32.INSTANCE.FillConsoleOutputAttribute(
+                        console, info.wAttributes, lengthToCursor, topLeft2, written);
                 break;
             case ERASE_SCREEN_TO_END:
-                int lengthToEnd = (info.srWindow.Bottom - info.dwCursorPosition.Y) * info.dwSize.X +
-                        (info.dwSize.X - info.dwCursorPosition.X);
+                int lengthToEnd = (info.srWindow.Bottom - info.dwCursorPosition.Y) * info.dwSize.X
+                        + (info.dwSize.X - info.dwCursorPosition.X);
                 Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToEnd, info.dwCursorPosition, written);
-                Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToEnd, info.dwCursorPosition, written);
+                Kernel32.INSTANCE.FillConsoleOutputAttribute(
+                        console, info.wAttributes, lengthToEnd, info.dwCursorPosition, written);
         }
     }
 
     protected void processEraseLine(int eraseOption) throws IOException {
         getConsoleInfo();
         IntByReference written = new IntByReference();
-        switch(eraseOption) {
+        switch (eraseOption) {
             case ERASE_LINE:
                 Kernel32.COORD leftColCurrRow = new Kernel32.COORD((short) 0, info.dwCursorPosition.Y);
                 Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', info.dwSize.X, leftColCurrRow, written);
-                Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, info.dwSize.X, leftColCurrRow, written);
+                Kernel32.INSTANCE.FillConsoleOutputAttribute(
+                        console, info.wAttributes, info.dwSize.X, leftColCurrRow, written);
                 break;
             case ERASE_LINE_TO_BEGINING:
                 Kernel32.COORD leftColCurrRow2 = new Kernel32.COORD((short) 0, info.dwCursorPosition.Y);
-                Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', info.dwCursorPosition.X, leftColCurrRow2, written);
-                Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, info.dwCursorPosition.X, leftColCurrRow2, written);
+                Kernel32.INSTANCE.FillConsoleOutputCharacter(
+                        console, ' ', info.dwCursorPosition.X, leftColCurrRow2, written);
+                Kernel32.INSTANCE.FillConsoleOutputAttribute(
+                        console, info.wAttributes, info.dwCursorPosition.X, leftColCurrRow2, written);
                 break;
             case ERASE_LINE_TO_END:
                 int lengthToLastCol = info.dwSize.X - info.dwCursorPosition.X;
-                Kernel32.INSTANCE.FillConsoleOutputCharacter(console, ' ', lengthToLastCol, info.dwCursorPosition, written);
-                Kernel32.INSTANCE.FillConsoleOutputAttribute(console, info.wAttributes, lengthToLastCol, info.dwCursorPosition, written);
+                Kernel32.INSTANCE.FillConsoleOutputCharacter(
+                        console, ' ', lengthToLastCol, info.dwCursorPosition, written);
+                Kernel32.INSTANCE.FillConsoleOutputAttribute(
+                        console, info.wAttributes, lengthToLastCol, info.dwCursorPosition, written);
         }
     }
 
@@ -218,7 +226,7 @@
             scroll.Top = 0;
             Kernel32.COORD org = new Kernel32.COORD();
             org.X = 0;
-            org.Y = (short)(- nb);
+            org.Y = (short) (-nb);
             Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
             Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
         }
@@ -247,29 +255,31 @@
     protected void processSetForegroundColorExt(int paletteIndex) throws IOException {
         int color = Colors.roundColor(paletteIndex, 16);
         info.wAttributes = (short) ((info.wAttributes & ~0x0007) | ANSI_FOREGROUND_COLOR_MAP[color & 0x07]);
-        info.wAttributes = (short) ((info.wAttributes & ~FOREGROUND_INTENSITY) | (color >= 8 ? FOREGROUND_INTENSITY : 0));
+        info.wAttributes =
+                (short) ((info.wAttributes & ~FOREGROUND_INTENSITY) | (color >= 8 ? FOREGROUND_INTENSITY : 0));
         applyAttribute();
     }
 
     protected void processSetBackgroundColorExt(int paletteIndex) throws IOException {
         int color = Colors.roundColor(paletteIndex, 16);
-        info.wAttributes = (short)((info.wAttributes & ~0x0070 ) | ANSI_BACKGROUND_COLOR_MAP[color & 0x07]);
-        info.wAttributes = (short) ((info.wAttributes & ~BACKGROUND_INTENSITY) | (color >= 8 ? BACKGROUND_INTENSITY : 0));
+        info.wAttributes = (short) ((info.wAttributes & ~0x0070) | ANSI_BACKGROUND_COLOR_MAP[color & 0x07]);
+        info.wAttributes =
+                (short) ((info.wAttributes & ~BACKGROUND_INTENSITY) | (color >= 8 ? BACKGROUND_INTENSITY : 0));
         applyAttribute();
     }
 
     protected void processDefaultTextColor() throws IOException {
-        info.wAttributes = (short)((info.wAttributes & ~0x000F ) | (originalColors & 0x000F));
+        info.wAttributes = (short) ((info.wAttributes & ~0x000F) | (originalColors & 0x000F));
         applyAttribute();
     }
 
     protected void processDefaultBackgroundColor() throws IOException {
-        info.wAttributes = (short)((info.wAttributes & ~0x00F0 ) | (originalColors & 0x00F0));
+        info.wAttributes = (short) ((info.wAttributes & ~0x00F0) | (originalColors & 0x00F0));
         applyAttribute();
     }
 
     protected void processAttributeRest() throws IOException {
-        info.wAttributes = (short)((info.wAttributes & ~0x00FF ) | originalColors);
+        info.wAttributes = (short) ((info.wAttributes & ~0x00FF) | originalColors);
         this.negative = false;
         this.bold = false;
         this.underline = false;
@@ -277,7 +287,7 @@
     }
 
     protected void processSetAttribute(int attribute) throws IOException {
-        switch(attribute) {
+        switch (attribute) {
             case ATTRIBUTE_INTENSITY_BOLD:
                 bold = true;
                 applyAttribute();
@@ -330,7 +340,7 @@
         scroll.Top = info.dwCursorPosition.Y;
         Kernel32.COORD org = new Kernel32.COORD();
         org.X = 0;
-        org.Y = (short)(info.dwCursorPosition.Y + optionInt);
+        org.Y = (short) (info.dwCursorPosition.Y + optionInt);
         Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
         Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
     }
@@ -342,7 +352,7 @@
         scroll.Top = info.dwCursorPosition.Y;
         Kernel32.COORD org = new Kernel32.COORD();
         org.X = 0;
-        org.Y = (short)(info.dwCursorPosition.Y - optionInt);
+        org.Y = (short) (info.dwCursorPosition.Y - optionInt);
         Kernel32.CHAR_INFO info = new Kernel32.CHAR_INFO(' ', originalColors);
         Kernel32.INSTANCE.ScrollConsoleScreenBuffer(console, scroll, scroll, org, info);
     }
diff -Nru openjdk-17-17.0.14+7/src/jdk.internal.le/windows/native/lible/Kernel32.cpp openjdk-17-17.0.15+6/src/jdk.internal.le/windows/native/lible/Kernel32.cpp
--- openjdk-17-17.0.14+7/src/jdk.internal.le/windows/native/lible/Kernel32.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.internal.le/windows/native/lible/Kernel32.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -329,16 +329,6 @@
 
 /*
  * Class:     jdk_internal_org_jline_terminal_impl_jna_win_Kernel32Impl
- * Method:    GetConsoleOutputCP
- * Signature: ()I
- */
-JNIEXPORT jint JNICALL Java_jdk_internal_org_jline_terminal_impl_jna_win_Kernel32Impl_GetConsoleOutputCP
-  (JNIEnv *, jobject) {
-    return GetConsoleOutputCP();
-}
-
-/*
- * Class:     jdk_internal_org_jline_terminal_impl_jna_win_Kernel32Impl
  * Method:    FillConsoleOutputCharacter
  * Signature: (Ljdk/internal/org/jline/terminal/impl/jna/win/Pointer;CILjdk/internal/org/jline/terminal/impl/jna/win/Kernel32/COORD;Ljdk/internal/org/jline/terminal/impl/jna/win/IntByReference;)V
  */
diff -Nru openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java
--- openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java	2025-04-09 19:45:33.000000000 +0000
@@ -180,6 +180,7 @@
     private boolean hasExpiringCert = false;
     private boolean hasExpiringTsaCert = false;
     private boolean noTimestamp = true;
+    private boolean hasNonexistentEntries = false;
 
     // Expiration date. The value could be null if signed by a trusted cert.
     private Date expireDate = null;
@@ -706,6 +707,7 @@
         Map sigMap = new HashMap<>();
         Map sigNameMap = new HashMap<>();
         Map unparsableSignatures = new HashMap<>();
+        Map> entriesInSF = new HashMap<>();
 
         try {
             jf = new JarFile(jarName, true);
@@ -753,6 +755,7 @@
                                         break;
                                     }
                                 }
+                                entriesInSF.put(alias, sf.getEntries().keySet());
                                 if (!found) {
                                     unparsableSignatures.putIfAbsent(alias,
                                         String.format(
@@ -851,6 +854,9 @@
                                 sb.append('\n');
                             }
                         }
+                        for (var signed : entriesInSF.values()) {
+                            signed.remove(name);
+                        }
                     } else if (showcerts && !verbose.equals("all")) {
                         // Print no info for unsigned entries when -verbose:all,
                         // to be consistent with old behavior.
@@ -1044,6 +1050,13 @@
                         if (verbose != null) {
                             System.out.println(history);
                         }
+                        var signed = entriesInSF.get(s);
+                        if (!signed.isEmpty()) {
+                            if (verbose != null) {
+                                System.out.println(rb.getString("history.nonexistent.entries") + signed);
+                            }
+                            hasNonexistentEntries = true;
+                        }
                     } else {
                         unparsableSignatures.putIfAbsent(s, String.format(
                                 rb.getString("history.nobk"), s));
@@ -1287,6 +1300,9 @@
             }
         }
 
+        if (hasNonexistentEntries) {
+            warnings.add(rb.getString("nonexistent.entries.found"));
+        }
         if (extraAttrsDetected) {
             warnings.add(rb.getString("extra.attributes.detected"));
         }
@@ -2151,7 +2167,7 @@
                     && !KeyStoreUtil.isWindowsKeyStore(storetype)) {
                 storepass = getPass
                         (rb.getString("Enter.Passphrase.for.keystore."));
-            } else if (!token && storepass == null && prompt) {
+            } else if (!token && storepass == null && prompt && !protectedPath) {
                 storepass = getPass
                         (rb.getString("Enter.Passphrase.for.keystore."));
             }
diff -Nru openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Resources.java openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Resources.java
--- openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Resources.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Resources.java	2025-04-09 19:45:33.000000000 +0000
@@ -165,6 +165,7 @@
 
         {"history.with.ts", "- Signed by \"%1$s\"\n    Digest algorithm: %2$s\n    Signature algorithm: %3$s, %4$s\n  Timestamped by \"%6$s\" on %5$tc\n    Timestamp digest algorithm: %7$s\n    Timestamp signature algorithm: %8$s, %9$s"},
         {"history.without.ts", "- Signed by \"%1$s\"\n    Digest algorithm: %2$s\n    Signature algorithm: %3$s, %4$s"},
+        {"history.nonexistent.entries", "    Warning: nonexistent signed entries: "},
         {"history.unparsable", "- Unparsable signature-related file %s"},
         {"history.nosf", "- Missing signature-related file META-INF/%s.SF"},
         {"history.nobk", "- Missing block file for signature-related file META-INF/%s.SF"},
@@ -175,6 +176,7 @@
         {"key.bit.weak", "%d-bit key (weak)"},
         {"key.bit.disabled", "%d-bit key (disabled)"},
         {"unknown.size", "unknown size"},
+        {"nonexistent.entries.found", "This jar contains signed entries for files that do not exist. See the -verbose output for more details."},
         {"extra.attributes.detected", "POSIX file permission and/or symlink attributes detected. These attributes are ignored when signing and are not protected by the signature."},
 
         {"jarsigner.", "jarsigner: "},
diff -Nru openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/tools/jar/Main.java openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/tools/jar/Main.java
--- openjdk-17-17.0.14+7/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -252,7 +252,7 @@
      * Starts main program with the specified arguments.
      */
     @SuppressWarnings({"removal"})
-    public synchronized boolean run(String args[]) {
+    public synchronized boolean run(String[] args) {
         ok = true;
         if (!parseArgs(args)) {
             return false;
@@ -367,11 +367,9 @@
                 if (fname != null) {
                     list(fname, files);
                 } else {
-                    InputStream in = new FileInputStream(FileDescriptor.in);
-                    try {
-                        list(new BufferedInputStream(in), files);
-                    } finally {
-                        in.close();
+                    try (InputStream in = new FileInputStream(FileDescriptor.in);
+                         BufferedInputStream bis = new BufferedInputStream(in)) {
+                        list(bis, files);
                     }
                 }
             } else if (xflag) {
@@ -387,18 +385,12 @@
                 // latter can handle it.
 
                 String[] files = filesMapToFiles(filesMap);
-                if (fname != null && files != null) {
+                if (fname != null) {
                     extract(fname, files);
                 } else {
-                    InputStream in = (fname == null)
-                        ? new FileInputStream(FileDescriptor.in)
-                        : new FileInputStream(fname);
-                    try {
-                        if (!extract(new BufferedInputStream(in), files) && fname != null) {
-                            extract(fname, files);
-                        }
-                    } finally {
-                        in.close();
+                    try (InputStream in = new FileInputStream(FileDescriptor.in);
+                         BufferedInputStream bis = new BufferedInputStream(in)) {
+                        extract(bis, files);
                     }
                 }
             } else if (iflag) {
@@ -495,7 +487,7 @@
     /**
      * Parses command line arguments.
      */
-    boolean parseArgs(String args[]) {
+    boolean parseArgs(String[] args) {
         /* Preprocess and expand @file arguments */
         try {
             args = CommandLine.parse(args);
@@ -929,118 +921,116 @@
                    Map moduleInfos,
                    JarIndex jarIndex) throws IOException
     {
-        ZipInputStream zis = new ZipInputStream(in);
-        ZipOutputStream zos = new JarOutputStream(out);
-        ZipEntry e = null;
-        boolean foundManifest = false;
         boolean updateOk = true;
+        try (ZipInputStream zis = new ZipInputStream(in);
+            ZipOutputStream zos = new JarOutputStream(out)) {
 
-        // All actual entries added/updated/existing, in the jar file (excl manifest
-        // and module-info.class ).
-        Set jentries = new HashSet<>();
-
-        if (jarIndex != null) {
-            addIndex(jarIndex, zos);
-        }
+            if (jarIndex != null) {
+                addIndex(jarIndex, zos);
+            }
+            ZipEntry e = null;
+            boolean foundManifest = false;
+            // All actual entries added/updated/existing, in the jar file (excl manifest
+            // and module-info.class ).
+            Set jentries = new HashSet<>();
 
-        // put the old entries first, replace if necessary
-        while ((e = zis.getNextEntry()) != null) {
-            String name = e.getName();
+            // put the old entries first, replace if necessary
+            while ((e = zis.getNextEntry()) != null) {
+                String name = e.getName();
 
-            boolean isManifestEntry = equalsIgnoreCase(name, MANIFEST_NAME);
-            boolean isModuleInfoEntry = isModuleInfoEntry(name);
+                boolean isManifestEntry = equalsIgnoreCase(name, MANIFEST_NAME);
+                boolean isModuleInfoEntry = isModuleInfoEntry(name);
 
-            if ((jarIndex != null && equalsIgnoreCase(name, INDEX_NAME))
-                || (Mflag && isManifestEntry)) {
-                continue;
-            } else if (isManifestEntry && ((newManifest != null) ||
+                if ((jarIndex != null && equalsIgnoreCase(name, INDEX_NAME))
+                        || (Mflag && isManifestEntry)) {
+                    continue;
+                } else if (isManifestEntry && ((newManifest != null) ||
                         (ename != null) || isMultiRelease)) {
-                foundManifest = true;
-                if (newManifest != null) {
-                    // Don't read from the newManifest InputStream, as we
-                    // might need it below, and we can't re-read the same data
-                    // twice.
-                    try (FileInputStream fis = new FileInputStream(mname)) {
-                        if (isAmbiguousMainClass(new Manifest(fis))) {
-                            return false;
+                    foundManifest = true;
+                    if (newManifest != null) {
+                        // Don't read from the newManifest InputStream, as we
+                        // might need it below, and we can't re-read the same data
+                        // twice.
+                        try (FileInputStream fis = new FileInputStream(mname)) {
+                            if (isAmbiguousMainClass(new Manifest(fis))) {
+                                return false;
+                            }
                         }
                     }
-                }
-                // Update the manifest.
-                Manifest old = new Manifest(zis);
-                if (newManifest != null) {
-                    old.read(newManifest);
-                }
-                if (!updateManifest(old, zos)) {
-                    return false;
-                }
-            } else if (moduleInfos != null && isModuleInfoEntry) {
-                moduleInfos.putIfAbsent(name, zis.readAllBytes());
-            } else {
-                boolean isDir = e.isDirectory();
-                if (!entryMap.containsKey(name)) { // copy the old stuff
-                    // do our own compression
-                    ZipEntry e2 = new ZipEntry(name);
-                    e2.setMethod(e.getMethod());
-                    setZipEntryTime(e2, e.getTime());
-                    e2.setComment(e.getComment());
-                    e2.setExtra(e.getExtra());
-                    if (e.getMethod() == ZipEntry.STORED) {
-                        e2.setSize(e.getSize());
-                        e2.setCrc(e.getCrc());
-                    }
-                    zos.putNextEntry(e2);
-                    copy(zis, zos);
-                } else { // replace with the new files
-                    Entry ent = entryMap.get(name);
-                    addFile(zos, ent);
-                    entryMap.remove(name);
-                    entries.remove(ent);
-                    isDir = ent.isDir;
-                }
-                if (!isDir) {
-                    jentries.add(name);
+                    // Update the manifest.
+                    Manifest old = new Manifest(zis);
+                    if (newManifest != null) {
+                        old.read(newManifest);
+                    }
+                    if (!updateManifest(old, zos)) {
+                        return false;
+                    }
+                } else if (moduleInfos != null && isModuleInfoEntry) {
+                    moduleInfos.putIfAbsent(name, zis.readAllBytes());
+                } else {
+                    boolean isDir = e.isDirectory();
+                    if (!entryMap.containsKey(name)) { // copy the old stuff
+                        // do our own compression
+                        ZipEntry e2 = new ZipEntry(name);
+                        e2.setMethod(e.getMethod());
+                        setZipEntryTime(e2, e.getTime());
+                        e2.setComment(e.getComment());
+                        e2.setExtra(e.getExtra());
+                        if (e.getMethod() == ZipEntry.STORED) {
+                            e2.setSize(e.getSize());
+                            e2.setCrc(e.getCrc());
+                        }
+                        zos.putNextEntry(e2);
+                        copy(zis, zos);
+                    } else { // replace with the new files
+                        Entry ent = entryMap.get(name);
+                        addFile(zos, ent);
+                        entryMap.remove(name);
+                        entries.remove(ent);
+                        isDir = ent.isDir;
+                    }
+                    if (!isDir) {
+                        jentries.add(name);
+                    }
                 }
             }
-        }
 
-        // add the remaining new files
-        for (Entry entry : entries) {
-            addFile(zos, entry);
-            if (!entry.isDir) {
-                jentries.add(entry.name);
-            }
-        }
-        if (!foundManifest) {
-            if (newManifest != null) {
-                Manifest m = new Manifest(newManifest);
-                updateOk = !isAmbiguousMainClass(m);
-                if (updateOk) {
-                    if (!updateManifest(m, zos)) {
+            // add the remaining new files
+            for (Entry entry : entries) {
+                addFile(zos, entry);
+                if (!entry.isDir) {
+                    jentries.add(entry.name);
+                }
+            }
+            if (!foundManifest) {
+                if (newManifest != null) {
+                    Manifest m = new Manifest(newManifest);
+                    updateOk = !isAmbiguousMainClass(m);
+                    if (updateOk) {
+                        if (!updateManifest(m, zos)) {
+                            updateOk = false;
+                        }
+                    }
+                } else if (ename != null) {
+                    if (!updateManifest(new Manifest(), zos)) {
                         updateOk = false;
                     }
                 }
-            } else if (ename != null) {
-                if (!updateManifest(new Manifest(), zos)) {
+            }
+            if (updateOk) {
+                if (moduleInfos != null && !moduleInfos.isEmpty()) {
+                    Set pkgs = new HashSet<>();
+                    jentries.forEach(je -> addPackageIfNamed(pkgs, je));
+                    addExtendedModuleAttributes(moduleInfos, pkgs);
+                    updateOk = checkModuleInfo(moduleInfos.get(MODULE_INFO), jentries);
+                    updateModuleInfo(moduleInfos, zos);
+                    // TODO: check manifest main classes, etc
+                } else if (moduleVersion != null || modulesToHash != null) {
+                    error(getMsg("error.module.options.without.info"));
                     updateOk = false;
                 }
             }
         }
-        if (updateOk) {
-            if (moduleInfos != null && !moduleInfos.isEmpty()) {
-                Set pkgs = new HashSet<>();
-                jentries.forEach( je -> addPackageIfNamed(pkgs, je));
-                addExtendedModuleAttributes(moduleInfos, pkgs);
-                updateOk = checkModuleInfo(moduleInfos.get(MODULE_INFO), jentries);
-                updateModuleInfo(moduleInfos, zos);
-                // TODO: check manifest main classes, etc
-            } else if (moduleVersion != null || modulesToHash != null) {
-                error(getMsg("error.module.options.without.info"));
-                updateOk = false;
-            }
-        }
-        zis.close();
-        zos.close();
         return updateOk;
     }
 
@@ -1362,19 +1352,12 @@
 
     /**
      * Extracts specified entries from JAR file.
-     *
-     * @return whether entries were found and successfully extracted
-     * (indicating this was a zip file without "leading garbage")
      */
-    boolean extract(InputStream in, String files[]) throws IOException {
+    void extract(InputStream in, String[] files) throws IOException {
         ZipInputStream zis = new ZipInputStream(in);
         ZipEntry e;
-        // Set of all directory entries specified in archive.  Disallows
-        // null entries.  Disallows all entries if using pre-6.0 behavior.
-        boolean entriesFound = false;
         Set dirs = newDirSet();
         while ((e = zis.getNextEntry()) != null) {
-            entriesFound = true;
             if (files == null) {
                 dirs.add(extractFile(zis, e));
             } else {
@@ -1393,32 +1376,31 @@
         // instead of during, because creating a file in a directory changes
         // that directory's timestamp.
         updateLastModifiedTime(dirs);
-
-        return entriesFound;
     }
 
     /**
      * Extracts specified entries from JAR file, via ZipFile.
      */
-    void extract(String fname, String files[]) throws IOException {
-        ZipFile zf = new ZipFile(fname);
-        Set dirs = newDirSet();
-        Enumeration zes = zf.entries();
-        while (zes.hasMoreElements()) {
-            ZipEntry e = zes.nextElement();
-            if (files == null) {
-                dirs.add(extractFile(zf.getInputStream(e), e));
-            } else {
-                String name = e.getName();
-                for (String file : files) {
-                    if (name.startsWith(file)) {
-                        dirs.add(extractFile(zf.getInputStream(e), e));
-                        break;
+    void extract(String fname, String[] files) throws IOException {
+        final Set dirs;
+        try (ZipFile zf = new ZipFile(fname)) {
+            dirs = newDirSet();
+            Enumeration zes = zf.entries();
+            while (zes.hasMoreElements()) {
+                ZipEntry e = zes.nextElement();
+                if (files == null) {
+                    dirs.add(extractFile(zf.getInputStream(e), e));
+                } else {
+                    String name = e.getName();
+                    for (String file : files) {
+                        if (name.startsWith(file)) {
+                            dirs.add(extractFile(zf.getInputStream(e), e));
+                            break;
+                        }
                     }
                 }
             }
         }
-        zf.close();
         updateLastModifiedTime(dirs);
     }
 
@@ -1499,7 +1481,7 @@
     /**
      * Lists contents of JAR file.
      */
-    void list(InputStream in, String files[]) throws IOException {
+    void list(InputStream in, String[] files) throws IOException {
         ZipInputStream zis = new ZipInputStream(in);
         ZipEntry e;
         while ((e = zis.getNextEntry()) != null) {
@@ -1517,13 +1499,13 @@
     /**
      * Lists contents of JAR file, via ZipFile.
      */
-    void list(String fname, String files[]) throws IOException {
-        ZipFile zf = new ZipFile(fname);
-        Enumeration zes = zf.entries();
-        while (zes.hasMoreElements()) {
-            printEntry(zes.nextElement(), files);
+    void list(String fname, String[] files) throws IOException {
+        try (ZipFile zf = new ZipFile(fname)) {
+            Enumeration zes = zf.entries();
+            while (zes.hasMoreElements()) {
+                printEntry(zes.nextElement(), files);
+            }
         }
-        zf.close();
     }
 
     /**
@@ -1566,10 +1548,8 @@
         // class path attribute will give us jar file name with
         // '/' as separators, so we need to change them to the
         // appropriate one before we open the jar file.
-        JarFile rf = new JarFile(jar.replace('/', File.separatorChar));
-
-        if (rf != null) {
-            Manifest man = rf.getManifest();
+        try (JarFile jarFile = new JarFile(jar.replace('/', File.separatorChar))) {
+            Manifest man = jarFile.getManifest();
             if (man != null) {
                 Attributes attr = man.getMainAttributes();
                 if (attr != null) {
@@ -1590,7 +1570,6 @@
                 }
             }
         }
-        rf.close();
         return files;
     }
 
@@ -1697,7 +1676,7 @@
     /**
      * Main routine to start program.
      */
-    public static void main(String args[]) {
+    public static void main(String[] args) {
         Main jartool = new Main(System.out, System.err, "jar");
         System.exit(jartool.run(args) ? 0 : 1);
     }
diff -Nru openjdk-17-17.0.14+7/src/jdk.javadoc/share/man/javadoc.1 openjdk-17-17.0.15+6/src/jdk.javadoc/share/man/javadoc.1
--- openjdk-17-17.0.14+7/src/jdk.javadoc/share/man/javadoc.1	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.javadoc/share/man/javadoc.1	2025-04-09 19:45:33.000000000 +0000
@@ -584,6 +584,12 @@
 .TP
 .B \f[CB]\-docfilessubdirs\f[R]
 Recursively copies doc\-file subdirectories.
+Enables deep copying of doc\-files directories.
+Subdirectories and all contents are recursively copied to the
+destination.
+For example, the directory \f[CB]doc\-files/example/images\f[R] and all of
+its contents are copied.
+There is also an option to exclude subdirectories.
 .RS
 .RE
 .TP
@@ -602,12 +608,7 @@
 .TP
 .B \f[CB]\-excludedocfilessubdir\f[R] \f[I]name\f[R]
 Excludes any doc files sub directories with the given name.
-Enables deep copying of doc\-files directories.
-Subdirectories and all contents are recursively copied to the
-destination.
-For example, the directory \f[CB]doc\-files/example/images\f[R] and all of
-its contents are copied.
-There is also an option to exclude subdirectories.
+See \f[B]\f[VB]-docfilessubdirs\f[B]\f[R].
 .RS
 .RE
 .TP
diff -Nru openjdk-17-17.0.14+7/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java
--- openjdk-17-17.0.14+7/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java	2025-04-09 19:45:33.000000000 +0000
@@ -201,55 +201,55 @@
 
                Options:
 
-                 begin           (Optional) Specify the time from which recording data will be included
-                                 in the dump file. The format is specified as local time.
-                                 (STRING, no default value)
-
-                 end             (Optional) Specify the time to which recording data will be included
-                                 in the dump file. The format is specified as local time.
-                                 (STRING, no default value)
-
-                                 Note: For both begin and end, the time must be in a format that can
-                                 be read by any of these methods:
-
-                                  java.time.LocalTime::parse(String),
-                                  java.time.LocalDateTime::parse(String)
-                                  java.time.Instant::parse(String)
-
-                                 For example, "13:20:15", "2020-03-17T09:00:00" or
-                                 "2020-03-17T09:00:00Z".
-
-                                 Note: begin and end times correspond to the timestamps found within
-                                 the recorded information in the flight recording data.
-
-                                 Another option is to use a time relative to the current time that is
-                                 specified by a negative integer followed by "s", "m" or "h".
-                                 For example, "-12h", "-15m" or "-30s"
-
-                 filename        (Optional) Name of the file to which the flight recording data is
-                                 dumped. If no filename is given, a filename is generated from the PID
-                                 and the current date. The filename may also be a directory in which
-                                 case, the filename is generated from the PID and the current date in
-                                 the specified directory. (STRING, no default value)
-
-                 maxage          (Optional) Length of time for dumping the flight recording data to a
-                                 file. (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
-                                 hours, no default value)
-
-                 maxsize         (Optional) Maximum size for the amount of data to dump from a flight
-                                 recording in bytes if one of the following suffixes is not used:
-                                 'm' or 'M' for megabytes OR 'g' or 'G' for gigabytes.
-                                 (STRING, no default value)
-
-                 name            (Optional) Name of the recording. If no name is given, data from all
-                                 recordings is dumped. (STRING, no default value)
-
-                 path-to-gc-root (Optional) Flag for saving the path to garbage collection (GC) roots
-                                 at the time the recording data is dumped. The path information is
-                                 useful for finding memory leaks but collecting it can cause the
-                                 application to pause for a short period of time. Turn on this flag
-                                 only when you have an application that you suspect has a memory
-                                 leak. (BOOLEAN, false)
+                 begin            (Optional) Specify the time from which recording data will be
+                                  included in the dump file. The format is specified as local time.
+                                  (STRING, no default value)
+
+                 end              (Optional) Specify the time to which recording data will be included
+                                  in the dump file. The format is specified as local time.
+                                  (STRING, no default value)
+
+                                  Note: For both begin and end, the time must be in a format that can
+                                  be read by any of these methods:
+
+                                   java.time.LocalTime::parse(String),
+                                   java.time.LocalDateTime::parse(String)
+                                   java.time.Instant::parse(String)
+
+                                  For example, "13:20:15", "2020-03-17T09:00:00" or
+                                  "2020-03-17T09:00:00Z".
+
+                                  Note: begin and end times correspond to the timestamps found within
+                                  the recorded information in the flight recording data.
+
+                                  Another option is to use a time relative to the current time that is
+                                  specified by a negative integer followed by "s", "m" or "h".
+                                  For example, "-12h", "-15m" or "-30s"
+
+                 filename         (Optional) Name of the file to which the flight recording data is
+                                  dumped. If no filename is given, a filename is generated from the PID
+                                  and the current date. The filename may also be a directory in which
+                                  case, the filename is generated from the PID and the current date in
+                                  the specified directory. (STRING, no default value)
+
+                 maxage           (Optional) Length of time for dumping the flight recording data to a
+                                  file. (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
+                                  hours, no default value)
+
+                 maxsize          (Optional) Maximum size for the amount of data to dump from a flight
+                                  recording in bytes if one of the following suffixes is not used:
+                                  'm' or 'M' for megabytes OR 'g' or 'G' for gigabytes.
+                                  (STRING, no default value)
+
+                 name             (Optional) Name of the recording. If no name is given, data from all
+                                  recordings is dumped. (STRING, no default value)
+
+                 path-to-gc-roots (Optional) Flag for saving the path to garbage collection (GC) roots
+                                  at the time the recording data is dumped. The path information is
+                                  useful for finding memory leaks but collecting it can cause the
+                                  application to pause for a short period of time. Turn on this flag
+                                  only when you have an application that you suspect has a memory
+                                  leak. (BOOLEAN, false)
 
                Options must be specified using the  or = syntax.
 
@@ -261,7 +261,7 @@
                 $ jcmd  JFR.dump name=1 filename=%s
                 $ jcmd  JFR.dump maxage=1h
                 $ jcmd  JFR.dump maxage=1h maxsize=50M
-                $ jcmd  JFR.dump fillename=leaks.jfr path-to-gc-root=true
+                $ jcmd  JFR.dump filename=leaks.jfr path-to-gc-roots=true
                 $ jcmd  JFR.dump begin=13:15
                 $ jcmd  JFR.dump begin=13:15 end=21:30:00
                 $ jcmd  JFR.dump end=18:00 maxage=10m
diff -Nru openjdk-17-17.0.14+7/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java
--- openjdk-17-17.0.14+7/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java	2025-04-09 19:45:33.000000000 +0000
@@ -306,78 +306,78 @@
 
     @Override
     public String[] printHelp() {
-        // 0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890
+            // 0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890
         return """
                Syntax : JFR.start [options]
 
                Options:
 
-                 delay           (Optional) Length of time to wait before starting to record
-                                 (INTEGER followed by 's' for seconds 'm' for minutes or h' for
-                                 hours, 0s)
-
-                 disk            (Optional) Flag for also writing the data to disk while recording
-                                 (BOOLEAN, true)
-
-                 dumponexit      (Optional) Flag for writing the recording to disk when the Java
-                                 Virtual Machine (JVM) shuts down. If set to 'true' and no value
-                                 is given for filename, the recording is written to a file in the
-                                 directory where the process was started. The file name is a
-                                 system-generated name that contains the process ID, the recording
-                                 ID and the current time stamp. (For example:
-                                 id-1-2021_09_14_09_00.jfr) (BOOLEAN, false)
-
-                 duration        (Optional) Length of time to record. Note that 0s means forever
-                                 (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
-                                 hours, 0s)
-
-                 filename        (Optional) Name of the file to which the flight recording data is
-                                 written when the recording is stopped. If no filename is given, a
-                                 filename is generated from the PID and the current date and is
-                                 placed in the directory where the process was started. The
-                                 filename may also be a directory in which case, the filename is
-                                 generated from the PID and the current date in the specified
-                                 directory. (STRING, no default value)
-
-                 maxage          (Optional) Maximum time to keep the recorded data on disk. This
-                                 parameter is valid only when the disk parameter is set to true.
-                                 Note 0s means forever. (INTEGER followed by 's' for seconds 'm'
-                                 for minutes or 'h' for hours, 0s)
-
-                 maxsize         (Optional) Maximum size of the data to keep on disk in bytes if
-                                 one of the following suffixes is not used: 'm' or 'M' for
-                                 megabytes OR 'g' or 'G' for gigabytes. This parameter is valid
-                                 only when the disk parameter is set to 'true'. The value must not
-                                 be less than the value for the maxchunksize parameter set with
-                                 the JFR.configure command. (STRING, 0 (no max size))
-
-                 name            (Optional) Name of the recording. If no name is provided, a name
-                                 is generated. Make note of the generated name that is shown in
-                                 the response to the command so that you can use it with other
-                                 commands. (STRING, system-generated default name)
-
-                 path-to-gc-root (Optional) Flag for saving the path to garbage collection (GC)
-                                 roots at the end of a recording. The path information is useful
-                                 for finding memory leaks but collecting it is time consuming.
-                                 Turn on this flag only when you have an application that you
-                                 suspect has a memory leak. If the settings parameter is set to
-                                 'profile', then the information collected includes the stack
-                                 trace from where the potential leaking object wasallocated.
-                                 (BOOLEAN, false)
-
-                 settings        (Optional) Name of the settings file that identifies which events
-                                 to record. To specify more than one file, use the settings
-                                 parameter repeatedly. Include the path if the file is not in
-                                 JAVA-HOME/lib/jfr. The following profiles are included with the
-                                 JDK in the JAVA-HOME/lib/jfr directory: 'default.jfc': collects a
-                                 predefined set of information with low overhead, so it has minimal
-                                 impact on performance and can be used with recordings that run
-                                 continuously; 'profile.jfc': Provides more data than the
-                                 'default.jfc' profile, but with more overhead and impact on
-                                 performance. Use this configuration for short periods of time
-                                 when more information is needed. Use none to start a recording
-                                 without a predefined configuration file. (STRING,
-                                 JAVA-HOME/lib/jfr/default.jfc)
+                 delay            (Optional) Length of time to wait before starting to record
+                                  (INTEGER followed by 's' for seconds 'm' for minutes or h' for
+                                  hours, 0s)
+
+                 disk             (Optional) Flag for also writing the data to disk while recording
+                                  (BOOLEAN, true)
+
+                 dumponexit       (Optional) Flag for writing the recording to disk when the Java
+                                  Virtual Machine (JVM) shuts down. If set to 'true' and no value
+                                  is given for filename, the recording is written to a file in the
+                                  directory where the process was started. The file name is a
+                                  system-generated name that contains the process ID, the recording
+                                  ID and the current time stamp. (For example:
+                                  id-1-2021_09_14_09_00.jfr) (BOOLEAN, false)
+
+                 duration         (Optional) Length of time to record. Note that 0s means forever
+                                  (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
+                                  hours, 0s)
+
+                 filename         (Optional) Name of the file to which the flight recording data is
+                                  written when the recording is stopped. If no filename is given, a
+                                  filename is generated from the PID and the current date and is
+                                  placed in the directory where the process was started. The
+                                  filename may also be a directory in which case, the filename is
+                                  generated from the PID and the current date in the specified
+                                  directory. (STRING, no default value)
+
+                 maxage           (Optional) Maximum time to keep the recorded data on disk. This
+                                  parameter is valid only when the disk parameter is set to true.
+                                  Note 0s means forever. (INTEGER followed by 's' for seconds 'm'
+                                  for minutes or 'h' for hours, 0s)
+
+                 maxsize          (Optional) Maximum size of the data to keep on disk in bytes if
+                                  one of the following suffixes is not used: 'm' or 'M' for
+                                  megabytes OR 'g' or 'G' for gigabytes. This parameter is valid
+                                  only when the disk parameter is set to 'true'. The value must not
+                                  be less than the value for the maxchunksize parameter set with
+                                  the JFR.configure command. (STRING, 0 (no max size))
+
+                 name             (Optional) Name of the recording. If no name is provided, a name
+                                  is generated. Make note of the generated name that is shown in
+                                  the response to the command so that you can use it with other
+                                  commands. (STRING, system-generated default name)
+
+                 path-to-gc-roots (Optional) Flag for saving the path to garbage collection (GC)
+                                  roots at the end of a recording. The path information is useful
+                                  for finding memory leaks but collecting it is time consuming.
+                                  Turn on this flag only when you have an application that you
+                                  suspect has a memory leak. If the settings parameter is set to
+                                  'profile', then the information collected includes the stack
+                                  trace from where the potential leaking object was allocated.
+                                  (BOOLEAN, false)
+
+                 settings         (Optional) Name of the settings file that identifies which events
+                                  to record. To specify more than one file, use the settings
+                                  parameter repeatedly. Include the path if the file is not in
+                                  JAVA-HOME/lib/jfr. The following profiles are included with the
+                                  JDK in the JAVA-HOME/lib/jfr directory: 'default.jfc': collects a
+                                  predefined set of information with low overhead, so it has minimal
+                                  impact on performance and can be used with recordings that run
+                                  continuously; 'profile.jfc': Provides more data than the
+                                  'default.jfc' profile, but with more overhead and impact on
+                                  performance. Use this configuration for short periods of time
+                                  when more information is needed. Use none to start a recording
+                                  without a predefined configuration file. (STRING,
+                                  JAVA-HOME/lib/jfr/default.jfc)
 
                Event settings and .jfc options can also be specified using the following syntax:
 
diff -Nru openjdk-17-17.0.14+7/src/jdk.jpackage/share/native/common/Log.cpp openjdk-17-17.0.15+6/src/jdk.jpackage/share/native/common/Log.cpp
--- openjdk-17-17.0.14+7/src/jdk.jpackage/share/native/common/Log.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/src/jdk.jpackage/share/native/common/Log.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -40,10 +40,6 @@
     // variables are initialized if any. This will result in AV. To avoid such
     // use cases keep logging module free from static variables that require
     // initialization with functions called by CRT.
-    //
-
-    // by default log everything
-    const Logger::LogLevel defaultLogLevel = Logger::LOG_TRACE;
 
     char defaultLogAppenderMemory[sizeof(StreamLogAppender)] = {};
 
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/Makefile openjdk-17-17.0.15+6/test/failure_handler/Makefile
--- openjdk-17-17.0.14+7/test/failure_handler/Makefile	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/Makefile	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,7 @@
 
 CONF_DIR = src/share/conf
 
-JAVA_RELEASE = 7
+JAVA_RELEASE = 15
 
 TARGET_JAR = ${IMAGE_DIR}/lib/jtregFailureHandler.jar
 
@@ -107,4 +107,3 @@
 
 .PHONY: all build classes test require_env clean
 .DEFAULT: all
-
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/README openjdk-17-17.0.15+6/test/failure_handler/README
--- openjdk-17-17.0.14+7/test/failure_handler/README	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/README	2025-04-09 19:45:33.000000000 +0000
@@ -1,4 +1,4 @@
-Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
 This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@
 
 DEPENDENCES
 
-The library requires jtreg 4b13+ and JDK 7+.
+The library requires jtreg 4b13+ and JDK 15+.
 
 BUILDING
 
@@ -102,4 +102,3 @@
  -timeoutHandler:jdk.test.failurehandler.jtreg.GatherProcessInfoTimeoutHandler\
  -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver         \
  ${WS}/hotspot/test/
-
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.test.failurehandler;
+
+import java.nio.file.Path;
+
+public interface CoreInfoGatherer {
+    void gatherCoreInfo(HtmlSection section, Path core);
+}
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,6 +51,10 @@
         return create();
     }
 
+    public CoreInfoGatherer getCoreInfoGatherer() {
+        return create();
+    }
+
     private ToolKit create() {
         Properties osProperty = Utils.getProperties(osName);
         try {
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,19 +26,25 @@
 import jdk.test.failurehandler.action.ActionSet;
 import jdk.test.failurehandler.action.ActionHelper;
 
+import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Queue;
 import java.util.Deque;
+import java.util.zip.GZIPInputStream;
 
-public class ToolKit implements EnvironmentInfoGatherer, ProcessInfoGatherer {
+public class ToolKit implements EnvironmentInfoGatherer, ProcessInfoGatherer, CoreInfoGatherer {
     private final List actions = new ArrayList<>();
     private final ActionHelper helper;
+    private final PrintWriter log;
 
     public ToolKit(ActionHelper helper, PrintWriter log, String... names) {
         this.helper = helper;
+        this.log = log;
         for (String name : names) {
             actions.add(new ActionSet(helper, log, name));
         }
@@ -51,6 +57,27 @@
         }
     }
 
+    @Override
+    public void gatherCoreInfo(HtmlSection section, Path core) {
+        if (core.getFileName().toString().endsWith(".gz")) {
+            Path unpackedCore = Path.of(core.toString().replace(".gz", ""));
+            try (GZIPInputStream gzis = new GZIPInputStream(Files.newInputStream(core))) {
+                Files.copy(gzis, unpackedCore);
+                for (ActionSet set : actions) {
+                    set.gatherCoreInfo(section, unpackedCore);
+                }
+                Files.delete(unpackedCore);
+            } catch (IOException ioe) {
+                log.printf("Unexpected exception whilc opening %s", core.getFileName().toString());
+                ioe.printStackTrace(log);
+            }
+        } else {
+            for (ActionSet set : actions) {
+                set.gatherCoreInfo(section, core);
+            }
+        }
+    }
+
     @Override
     public void gatherProcessInfo(HtmlSection section, long pid) {
         // as some of actions can kill a process, we need to get children of all
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,6 @@
 
 package jdk.test.failurehandler.action;
 
-import com.sun.tools.attach.VirtualMachine;
-import com.sun.tools.attach.VirtualMachineDescriptor;
 import jdk.test.failurehandler.value.InvalidValueException;
 import jdk.test.failurehandler.value.Value;
 import jdk.test.failurehandler.value.ValueHandler;
@@ -134,7 +132,7 @@
                 .directory(workDir.toFile());
     }
 
-    private File findApp(String app) {
+    public File findApp(String app) {
         String name = app + executableSuffix;
         for (Path pathElem : paths) {
             File result = pathElem.resolve(name).toFile();
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,19 +23,26 @@
 
 package jdk.test.failurehandler.action;
 
+import jdk.test.failurehandler.CoreInfoGatherer;
 import jdk.test.failurehandler.ProcessInfoGatherer;
 import jdk.test.failurehandler.EnvironmentInfoGatherer;
 import jdk.test.failurehandler.HtmlSection;
 import jdk.test.failurehandler.Utils;
 
+import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+import java.util.zip.GZIPInputStream;
 
-public class ActionSet implements ProcessInfoGatherer, EnvironmentInfoGatherer {
+public class ActionSet implements ProcessInfoGatherer, EnvironmentInfoGatherer, CoreInfoGatherer {
     private static final String ENVIRONMENT_PROPERTY = "environment";
     private static final String ON_PID_PROPERTY = "onTimeout";
+    private static final String CORES_PROPERTY = "cores";
+
 
     private final ActionHelper helper;
 
@@ -46,6 +53,7 @@
     private final String name;
     private final List environmentActions;
     private final List processActions;
+    private final List coreActions;
 
 
     public ActionSet(ActionHelper helper, PrintWriter log, String name) {
@@ -55,6 +63,7 @@
         Properties p = Utils.getProperties(name);
         environmentActions = getSimpleActions(log, p, ENVIRONMENT_PROPERTY);
         processActions = getPatternActions(log, p, ON_PID_PROPERTY);
+        coreActions = getPatternActions(log, p, CORES_PROPERTY);
     }
 
     private List getSimpleActions(PrintWriter log, Properties p,
@@ -95,8 +104,11 @@
 
     private String[] getTools(PrintWriter writer, Properties p, String key) {
         String value = p.getProperty(key);
-        if (value == null || value.isEmpty()) {
-            writer.printf("ERROR: '%s' property is empty%n", key);
+        if (value == null) {
+            writer.printf("ERROR: '%s' property is not set%n", key);
+            return new String[]{};
+        }
+        if (value.isEmpty()) {
             return new String[]{};
         }
         return value.split(" ");
@@ -123,4 +135,11 @@
             helper.runPatternAction(action, section);
         }
     }
+
+    @Override
+    public void gatherCoreInfo(HtmlSection section, Path core) {
+        for (PatternAction action : coreActions) {
+            helper.runPatternAction(action, section, core.toString());
+        }
+    }
 }
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,9 @@
         for (int i = 0, n = args.length; i < n; ++i) {
             args[i] = args[i].replace(pattern, value) ;
         }
+        for (int i = 0, n = args.length; i < n; ++i) {
+            args[i] = args[i].replace("%java", helper.findApp("java").getAbsolutePath());
+        }
         return action.prepareProcess(section.getWriter(), helper);
     }
 
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,10 +33,9 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.Map;
 
 /**
  * The jtreg test execution observer, which gathers info about
@@ -45,6 +44,8 @@
 public class GatherDiagnosticInfoObserver implements Harness.Observer {
     public static final String LOG_FILENAME = "environment.log";
     public static final String ENVIRONMENT_OUTPUT = "environment.html";
+    public static final String CORES_OUTPUT = "cores.html";
+
 
     private Path compileJdk;
     private Path testJdk;
@@ -64,18 +65,19 @@
         workDir.toFile().mkdir();
 
         String name = getClass().getName();
-        PrintWriter log;
+        PrintWriter log1;
         boolean needClose = false;
         try {
-            log = new PrintWriter(new FileWriter(
+            log1 = new PrintWriter(new FileWriter(
                     workDir.resolve(LOG_FILENAME).toFile(), true), true);
             needClose = true;
         } catch (IOException e) {
-            log = new PrintWriter(System.out);
-            log.printf("ERROR: %s cannot open log file %s", name,
+            log1 = new PrintWriter(System.out);
+            log1.printf("ERROR: %s cannot open log file %s", name,
                     LOG_FILENAME);
-            e.printStackTrace(log);
+            e.printStackTrace(log1);
         }
+        final PrintWriter log = log1;
         try {
             log.printf("%s ---%n", name);
             GathererFactory gathererFactory = new GathererFactory(
@@ -83,6 +85,11 @@
                     testJdk, compileJdk);
             gatherEnvInfo(workDir, name, log,
                     gathererFactory.getEnvironmentInfoGatherer());
+            Files.walk(workDir)
+                    .filter(Files::isRegularFile)
+                    .filter(f -> (f.getFileName().toString().contains("core") || f.getFileName().toString().contains("mdmp")))
+                    .forEach(core -> gatherCoreInfo(workDir, name,
+                            core, log, gathererFactory.getCoreInfoGatherer()));
         } catch (Throwable e) {
             log.printf("ERROR: exception in observer %s:", name);
             e.printStackTrace(log);
@@ -96,6 +103,22 @@
         }
     }
 
+    private void gatherCoreInfo(Path workDir, String name, Path core, PrintWriter log,
+                               CoreInfoGatherer gatherer) {
+        File output = workDir.resolve(CORES_OUTPUT).toFile();
+        try (HtmlPage html = new HtmlPage(new PrintWriter(
+                new FileWriter(output, true), true))) {
+            try (ElapsedTimePrinter timePrinter
+                         = new ElapsedTimePrinter(new Stopwatch(), name, log)) {
+                gatherer.gatherCoreInfo(html.getRootSection(), core);
+            }
+        } catch (Throwable e) {
+            log.printf("ERROR: exception in observer on getting environment "
+                    + "information %s:", name);
+            e.printStackTrace(log);
+        }
+    }
+
     private void gatherEnvInfo(Path workDir, String name, PrintWriter log,
                                EnvironmentInfoGatherer gatherer) {
         File output = workDir.resolve(ENVIRONMENT_OUTPUT).toFile();
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/common.properties openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/common.properties
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/common.properties	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/common.properties	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@
         jcmd.vm.symboltable jcmd.vm.uptime jcmd.vm.dynlibs \
         jcmd.vm.system_properties jcmd.vm.info \
   jcmd.gc.heap_info jcmd.gc.class_histogram jcmd.gc.finalizer_info \
-  jstack
+  jstack jhsdb.jstack
 
 jinfo.app=jinfo
 
@@ -51,6 +51,7 @@
 jcmd.vm.uptime.args=%p VM.uptime
 jcmd.vm.dynlibs.args=%p VM.dynlibs
 jcmd.vm.system_properties.args=%p VM.system_properties
+jcmd.vm.info.args=%p VM.info
 
 jcmd.gc.class_histogram.args=%p GC.class_histogram
 jcmd.gc.finalizer_info.args=%p GC.finalizer_info
@@ -60,6 +61,15 @@
 jstack.args=-e -l %p
 jstack.params.repeat=6
 
+jhsdb.app=jhsdb
+jhsdb.jstack.args=jstack --mixed --pid %p
+jhsdb.jstack.params.repeat=6
+
+cores=jhsdb.jstack
+jhsdb.jstack.app=jhsdb
+# Assume that java standard laucher has been used
+jhsdb.jstack.args=jstack --mixed --core %p --exe %java
+
 ################################################################################
 # environment info to gather
 ################################################################################
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/linux.properties openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/linux.properties
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/linux.properties	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/linux.properties	2025-04-09 19:45:33.000000000 +0000
@@ -32,6 +32,7 @@
   native.pmap.normal native.pmap.everything \
   native.files native.locks \
   native.stack native.core
+
 ################################################################################
 native.pattern=%p
 native.javaOnly=false
@@ -48,13 +49,20 @@
 native.locks.args=-u --pid %p
 
 native.stack.app=gdb
-native.stack.args=--pid=%p\0-batch\0-ex\0thread apply all backtrace
+native.stack.args=--pid=%p\0-batch\0-ex\0info threads\0-ex\0thread apply all backtrace
 native.stack.args.delimiter=\0
 native.stack.params.repeat=6
 
 # has to be the last command
 native.core.app=kill
 native.core.args=-ABRT %p
+
+cores=native.gdb
+native.gdb.app=gdb
+# Assume that java standard laucher has been used
+native.gdb.args=%java\0-c\0%p\0-batch\0-ex\0info threads\0-ex\0thread apply all backtrace
+native.gdb.args.delimiter=\0
+
 ################################################################################
 # environment info to gather
 ################################################################################
@@ -128,4 +136,3 @@
     ' | jshell -
 screenshot.args.delimiter=\0
 ################################################################################
-
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/mac.properties openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/mac.properties
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/mac.properties	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/mac.properties	2025-04-09 19:45:33.000000000 +0000
@@ -64,6 +64,13 @@
 # has to be the last command
 native.core.app=kill
 native.core.args=-ABRT %p
+
+cores=native.lldb
+native.lldb.app=lldb
+native.lldb.delimiter=\0
+# Assume that java standard laucher has been used
+native.lldb.args=--core\0%p\0%java\0-o\0thread backtrace all\0-o\0quit
+
 ################################################################################
 # environment info to gather
 ################################################################################
diff -Nru openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/windows.properties openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/windows.properties
--- openjdk-17-17.0.14+7/test/failure_handler/src/share/conf/windows.properties	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/failure_handler/src/share/conf/windows.properties	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -57,8 +57,10 @@
 native.stack.params.repeat=6
 
 native.core.app=cdb
-native.core.args=-c ".dump /f core.%p;qd" -p %p
-native.core.params.timeout=3600000
+native.core.args=-c ".dump /mA core.%p;qd" -p %p
+native.core.params.timeout=600000
+
+cores=
 ################################################################################
 # environment info to gather
 ################################################################################
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/compiler/test_directivesParser.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/compiler/test_directivesParser.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/compiler/test_directivesParser.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/compiler/test_directivesParser.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -32,15 +32,16 @@
 
 class DirectivesParserTest : public ::testing::Test{
  protected:
-  const char* const _locale;
+  char* const _locale;
   ResourceMark rm;
   stringStream stream;
   // These tests require the "C" locale to correctly parse decimal values
-  DirectivesParserTest() : _locale(setlocale(LC_NUMERIC, NULL)) {
+  DirectivesParserTest() : _locale(os::strdup(setlocale(LC_NUMERIC, nullptr), mtTest)) {
     setlocale(LC_NUMERIC, "C");
   }
   ~DirectivesParserTest() {
     setlocale(LC_NUMERIC, _locale);
+    os::free(_locale);
   }
 
   void test_negative(const char* text) {
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 #include "utilities/globalDefinitions.hpp"
 
 #include "utilities/vmassert_uninstall.hpp"
+#include 
 #include 
 #include 
 #include "utilities/vmassert_reinstall.hpp"
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/logging/logTestFixture.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestFixture.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/logging/logTestFixture.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestFixture.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -112,7 +112,7 @@
   if (_configuration_snapshot == NULL) {
     return;
   }
-  assert(_n_snapshots > 0, "non-null array should have at least 1 element");
+  ASSERT_GT(_n_snapshots, size_t(0)) << "non-null array should have at least 1 element";
   for (size_t i = 0; i < _n_snapshots; i++) {
     os::free(_configuration_snapshot[i]);
   }
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/logging/logTestUtils.inline.hpp openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestUtils.inline.hpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/logging/logTestUtils.inline.hpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/logging/logTestUtils.inline.hpp	2025-04-09 19:45:33.000000000 +0000
@@ -57,14 +57,14 @@
 }
 
 static inline void create_directory(const char* name) {
-  assert(!file_exists(name), "can't create directory: %s already exists", name);
+  ASSERT_FALSE(file_exists(name)) << "can't create directory: " << name << " already exists";
   bool failed;
 #ifdef _WINDOWS
   failed = !CreateDirectory(name, NULL);
 #else
   failed = mkdir(name, 0777);
 #endif
-  assert(!failed, "failed to create directory %s", name);
+  ASSERT_FALSE(failed) << "failed to create directory " << name;
 }
 
 static inline void delete_empty_directory(const char* name) {
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logConfiguration.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logConfiguration.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logConfiguration.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logConfiguration.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -36,6 +36,8 @@
 #include "unittest.hpp"
 #include "utilities/ostream.hpp"
 
+using testing::HasSubstr;
+
 class LogConfigurationTest : public LogTestFixture {
  protected:
   static char _all_decorators[256];
@@ -71,26 +73,26 @@
   const char* description = ss.as_string();
 
   // Verify that stdout and stderr are listed by default
-  EXPECT_PRED2(string_contains_substring, description, StdoutLog.name());
-  EXPECT_PRED2(string_contains_substring, description, StderrLog.name());
+  EXPECT_THAT(description, HasSubstr(StdoutLog.name()));
+  EXPECT_THAT(description, HasSubstr(StderrLog.name()));
 
   // Verify that each tag, level and decorator is listed
   for (size_t i = 0; i < LogTag::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogTag::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogTag::name(static_cast(i))));
   }
   for (size_t i = 0; i < LogLevel::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogLevel::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogLevel::name(static_cast(i))));
   }
   for (size_t i = 0; i < LogDecorators::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogDecorators::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogDecorators::name(static_cast(i))));
   }
 
   // Verify that the default configuration is printed
   char expected_buf[256];
   int ret = jio_snprintf(expected_buf, sizeof(expected_buf), "=%s", LogLevel::name(LogLevel::Default));
   ASSERT_NE(-1, ret);
-  EXPECT_PRED2(string_contains_substring, description, expected_buf);
-  EXPECT_PRED2(string_contains_substring, description, "#1: stderr all=off");
+  EXPECT_THAT(description, HasSubstr(expected_buf));
+  EXPECT_THAT(description, HasSubstr("#1: stderr all=off"));
 
   // Verify default decorators are listed
   LogDecorators default_decorators;
@@ -107,7 +109,7 @@
       ASSERT_NE(-1, ret);
     }
   }
-  EXPECT_PRED2(string_contains_substring, description, expected_buf);
+  EXPECT_THAT(description, HasSubstr(expected_buf));
 
   // Add a new output and verify that it gets described after it has been added
   const char* what = "all=trace";
@@ -493,8 +495,8 @@
   bool success = LogConfiguration::parse_log_arguments("stdout", invalid_tagset, NULL, NULL, &ss);
   const char* msg = ss.as_string();
   EXPECT_TRUE(success) << "Should only cause a warning, not an error";
-  EXPECT_TRUE(string_contains_substring(msg, "No tag set matches selection:"));
-  EXPECT_TRUE(string_contains_substring(msg, invalid_tagset));
+  EXPECT_THAT(msg, HasSubstr("No tag set matches selection:"));
+  EXPECT_THAT(msg, HasSubstr(invalid_tagset));
 }
 
 TEST_VM_F(LogConfigurationTest, output_name_normalization) {
@@ -559,7 +561,7 @@
 
   const char* suggestion = ss.as_string();
   SCOPED_TRACE(suggestion);
-  EXPECT_TRUE(string_contains_substring(ss.as_string(), "Did you mean any of the following?"));
+  EXPECT_THAT(suggestion, HasSubstr("Did you mean any of the following?"));
   EXPECT_TRUE(string_contains_substring(suggestion, "logging") ||
               string_contains_substring(suggestion, "start") ||
               string_contains_substring(suggestion, "exit") ||
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logFileOutput.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logFileOutput.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logFileOutput.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logFileOutput.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -169,12 +169,26 @@
   ResourceMark rm;
   stringStream ss;
 
+  // Generate sufficiently unique directory path and log spec for that path
+  ss.print("%s%s%s%d", os::get_temp_directory(), os::file_separator(), "tmplogdir", os::current_process_id());
+  char* path = ss.as_string();
+  ss.reset();
+
+  ss.print("%s%s", "file=", path);
+  char* log_spec = ss.as_string();
+  ss.reset();
+
+  ss.print("%s is not a regular file", path);
+  char* expected_output_substring = ss.as_string();
+  ss.reset();
+
   // Attempt to log to a directory (existing log not a regular file)
-  create_directory("tmplogdir");
-  LogFileOutput bad_file("file=tmplogdir");
+  create_directory(path);
+  LogFileOutput bad_file(log_spec);
   EXPECT_FALSE(bad_file.initialize("", &ss))
     << "file was initialized when there was an existing directory with the same name";
-  EXPECT_TRUE(string_contains_substring(ss.as_string(), "tmplogdir is not a regular file"))
-    << "missing expected error message, received msg: %s" << ss.as_string();
-  delete_empty_directory("tmplogdir");
+  char* logger_output = ss.as_string();
+  EXPECT_THAT(logger_output, testing::HasSubstr(expected_output_substring))
+    << "missing expected error message, received msg: %s" << logger_output;
+  delete_empty_directory(path);
 }
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -42,7 +42,7 @@
     ResourceMark rm;
     stringStream stream;
     LogConfiguration::describe(&stream);
-    EXPECT_PRED2(string_contains_substring, stream.as_string(), expected)
+    EXPECT_THAT(stream.base(), testing::HasSubstr(expected))
       << "missing log tag set descriptions in LogConfiguration::describe";
   }
 }
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/memory/test_guardedMemory.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/memory/test_guardedMemory.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/memory/test_guardedMemory.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/memory/test_guardedMemory.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -140,7 +140,7 @@
   if (HasFatalFailure()) {
     return;
   }
-  EXPECT_EQ(0, strcmp(str, str_copy)) << "Not identical copy";
+  EXPECT_STREQ(str, str_copy) << "Not identical copy";
   EXPECT_TRUE(GuardedMemory::free_copy(str_copy)) << "Free copy failed to verify";
 
   void* no_data = NULL;
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/oops/test_instanceKlass.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_instanceKlass.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/oops/test_instanceKlass.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_instanceKlass.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -27,6 +27,8 @@
 #include "oops/instanceKlass.hpp"
 #include "unittest.hpp"
 
+using testing::HasSubstr;
+
 // Tests for InstanceKlass::is_class_loader_instance_klass() function
 TEST_VM(InstanceKlass, class_loader_class) {
   InstanceKlass* klass = vmClasses::ClassLoader_klass();
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/oops/test_markWord.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_markWord.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/oops/test_markWord.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/oops/test_markWord.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -41,20 +41,17 @@
 
 // The test doesn't work for PRODUCT because it needs WizardMode
 #ifndef PRODUCT
-static bool test_pattern(stringStream* st, const char* pattern) {
-  return (strstr(st->as_string(), pattern) != NULL);
-}
 
 static void assert_test_pattern(Handle object, const char* pattern) {
   stringStream st;
   object->print_on(&st);
-  ASSERT_TRUE(test_pattern(&st, pattern)) << pattern << " not in " << st.as_string();
+  ASSERT_THAT(st.base(), testing::HasSubstr(pattern));
 }
 
 static void assert_not_test_pattern(Handle object, const char* pattern) {
   stringStream st;
   object->print_on(&st);
-  ASSERT_FALSE(test_pattern(&st, pattern)) << pattern << " found in " << st.as_string();
+  ASSERT_THAT(st.base(), testing::Not(testing::HasSubstr(pattern)));
 }
 
 class LockerThread : public JavaTestThread {
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -171,8 +171,10 @@
       // Verify the current thread refers to tlh2:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list())
           << "thr->_threads_hazard_ptr must match tlh2.list()";
-      EXPECT_EQ(tlh1.list(), tlh2.list())
-          << "tlh1.list() must match tlh2.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2.list())
+    //       << "tlh1.list() must match tlh2.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2)
           << "thr->_threads_list_ptr must match list_ptr2";
       EXPECT_NE(list_ptr1, list_ptr2)
@@ -291,8 +293,10 @@
       // Verify the current thread refers to tlh2:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list())
           << "thr->_threads_hazard_ptr must match tlh2.list()";
-      EXPECT_EQ(tlh1.list(), tlh2.list())
-          << "tlh1.list() must match tlh2.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2.list())
+    //       << "tlh1.list() must match tlh2.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2)
           << "thr->_threads_list_ptr must match list_ptr2";
       EXPECT_NE(list_ptr1, list_ptr2)
@@ -339,8 +343,10 @@
         // Verify the current thread refers to tlh3:
         EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh3.list())
             << "thr->_threads_hazard_ptr must match tlh3.list()";
-        EXPECT_EQ(tlh1.list(), tlh3.list())
-            << "tlh1.list() must match tlh3.list()";
+        // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+        // until the root cause of test failure(JDK-8315141) has been fixed
+        // EXPECT_EQ(tlh1.list(), tlh3.list())
+        //     << "tlh1.list() must match tlh3.list()";
         EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr3)
             << "thr->_threads_list_ptr must match list_ptr3";
         EXPECT_NE(list_ptr1, list_ptr3)
@@ -523,8 +529,10 @@
       // Verify the current thread refers to tlh2a:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2a.list())
           << "thr->_threads_hazard_ptr must match tlh2a.list()";
-      EXPECT_EQ(tlh1.list(), tlh2a.list())
-          << "tlh1.list() must match tlh2a.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2a.list())
+    //       << "tlh1.list() must match tlh2a.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2a)
           << "thr->_threads_list_ptr must match list_ptr2a";
       EXPECT_NE(list_ptr1, list_ptr2a)
@@ -601,8 +609,10 @@
       // Verify the current thread refers to tlh2b:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2b.list())
           << "thr->_threads_hazard_ptr must match tlh2b.list()";
-      EXPECT_EQ(tlh1.list(), tlh2b.list())
-          << "tlh1.list() must match tlh2b.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2b.list())
+    //       << "tlh1.list() must match tlh2b.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2b)
           << "thr->_threads_list_ptr must match list_ptr2b";
       EXPECT_NE(list_ptr1, list_ptr2b)
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_globals.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_globals.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_globals.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_globals.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -81,11 +81,11 @@
 TEST_VM(FlagAccess, ccstr_flag) {
   FLAG_SET_CMDLINE(SharedArchiveConfigFile, "");
   ASSERT_EQ(FLAG_IS_CMDLINE(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, ""), 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "");
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, "foobar");
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, "foobar") , 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "foobar");
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, nullptr);
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
@@ -93,7 +93,7 @@
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, "xyz");
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, "xyz"), 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "xyz");
 }
 
 template 
diff -Nru openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_os.cpp openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_os.cpp
--- openjdk-17-17.0.14+7/test/hotspot/gtest/runtime/test_os.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/gtest/runtime/test_os.cpp	2025-04-09 19:45:33.000000000 +0000
@@ -34,6 +34,8 @@
 #include "unittest.hpp"
 #include "runtime/frame.inline.hpp"
 
+using testing::HasSubstr;
+
 static size_t small_page_size() {
   return os::vm_page_size();
 }
@@ -167,7 +169,7 @@
   os::print_hex_dump(&ss, addr, addr + len, unitsize);
 //  tty->print_cr("expected: %s", expected);
 //  tty->print_cr("result: %s", buf);
-  ASSERT_NE(strstr(buf, expected), (char*)NULL);
+  EXPECT_THAT(buf, HasSubstr(expected));
 }
 
 TEST_VM(os, test_print_hex_dump) {
@@ -769,7 +771,7 @@
   char buffer[256];
   stringStream ss(buffer, sizeof(buffer));
   pss.print_on(&ss);
-  ASSERT_EQ(strcmp(expected, buffer), 0);
+  EXPECT_STREQ(expected, buffer);
 }
 
 TEST_VM(os, dll_address_to_function_and_library_name) {
@@ -778,9 +780,9 @@
   stringStream st(output, sizeof(output));
 
 #define EXPECT_CONTAINS(haystack, needle) \
-  EXPECT_NE(::strstr(haystack, needle), (char*)NULL)
+  EXPECT_THAT(haystack, HasSubstr(needle));
 #define EXPECT_DOES_NOT_CONTAIN(haystack, needle) \
-  EXPECT_EQ(::strstr(haystack, needle), (char*)NULL)
+  EXPECT_THAT(haystack, Not(HasSubstr(needle)));
 // #define LOG(...) tty->print_cr(__VA_ARGS__); // enable if needed
 #define LOG(...)
 
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/ProblemList.txt openjdk-17-17.0.15+6/test/hotspot/jtreg/ProblemList.txt
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/ProblemList.txt	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/ProblemList.txt	2025-04-09 19:45:33.000000000 +0000
@@ -115,13 +115,13 @@
 serviceability/jvmti/ModuleAwareAgents/ThreadStart/MAAThreadStart.java 8225354 windows-all
 serviceability/dcmd/gc/RunFinalizationTest.java 8227120 generic-all
 
-serviceability/sa/ClhsdbCDSCore.java  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbFindPC.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbFindPC.java#id3  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbPmap.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbPstack.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/TestJmapCore.java  8294316,8267433 macosx-x64
-serviceability/sa/TestJmapCoreMetaspace.java  8294316,8267433 macosx-x64
+serviceability/sa/ClhsdbCDSCore.java  8267433 macosx-x64
+serviceability/sa/ClhsdbFindPC.java#id1  8267433 macosx-x64
+serviceability/sa/ClhsdbFindPC.java#id3  8267433 macosx-x64
+serviceability/sa/ClhsdbPmap.java#id1  8267433 macosx-x64
+serviceability/sa/ClhsdbPstack.java#id1  8267433 macosx-x64
+serviceability/sa/TestJmapCore.java  8267433 macosx-x64
+serviceability/sa/TestJmapCoreMetaspace.java  8267433 macosx-x64
 
 #############################################################################
 
@@ -161,6 +161,7 @@
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2none_a/TestDescription.java 8013267 generic-all
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manyDiff_b/TestDescription.java 8013267 generic-all
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manySame_b/TestDescription.java 8013267 generic-all
+vmTestbase/vm/mlvm/meth/stress/compiler/deoptimize/Test.java#id1 8325905 generic-all
 
 vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn001/forceEarlyReturn001.java 7199837 generic-all
 
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package compiler.arraycopy;
+import java.util.Random;
+
+/**
+ * @test
+ * @bug 8310159
+ * @summary Test large arrayCopy.
+ *
+ * @run main/timeout=600 compiler.arraycopy.TestArrayCopyDisjointLarge
+ *
+ */
+
+public class TestArrayCopyDisjointLarge {
+
+    public static final int ARRLEN = 4194304;
+    public static int fromPos, toPos;
+    public static byte[] fromByteArr, toByteArr;
+
+    public static void setup() {
+        fromPos = 0;
+        toPos = 0;
+
+        fromByteArr = new byte[ARRLEN];
+        toByteArr = new byte[ARRLEN];
+        for (int i = 0 ; i < ARRLEN ; i++) {
+            fromByteArr[i] = (byte)i;
+        }
+    }
+
+    public static void validate(String msg, byte[] toByteArr, int length, int fromPos, int toPos) {
+        for(int i = 0 ; i < length; i++) {
+            if (fromByteArr[i + fromPos] != toByteArr[i + toPos]) {
+                System.out.println(msg + "[" + toByteArr.getClass() + "] Result mismtach at i = " + i
+                                + " expected = " + fromByteArr[i + fromPos]
+                                + " actual   = " + toByteArr[i + toPos]
+                                + " fromPos = " + fromPos
+                                + " toPos = " + toPos);
+                throw new Error("Fail");
+            }
+        }
+    }
+
+    public static void testByte(int length, int fromPos, int toPos) {
+        System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
+        validate(" Test ByteArr ", toByteArr, length, fromPos, toPos);
+    }
+
+    public static void main(String [] args) {
+        int base_size = 2621440;
+        Random r = new Random(1024);
+        int [] lengths = {base_size - 1, base_size, base_size + 1, base_size + 63, base_size + 64,
+                                base_size + 65, base_size + 255, base_size + 256, base_size + 257,
+                                base_size + r.nextInt(2048)};
+        setup();
+
+        for (int i = 0 ; i < 20 ; i++ ) {
+            testByte(lengths[i % lengths.length], 0, 0);
+            testByte(lengths[i % lengths.length], 0, 9);
+            testByte(lengths[i % lengths.length], 9, 0);
+            testByte(lengths[i % lengths.length], 9, 9);
+            testByte(lengths[i % lengths.length], r.nextInt(2048) , r.nextInt(2048));
+        }
+    }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+super public class LongCountedLoopInInfiniteLoop
+{
+  public Method "":"()V"
+    stack 1 locals 1
+  {
+        aload_0;
+        invokespecial    Method java/lang/Object."":"()V";
+        return;
+  }
+  Method test:"()V"
+    stack 3 locals 3
+  {
+        // #1 = 0;
+        iconst_0;
+        istore_1;
+
+    LOOPa:
+        // if #1 >= 10: goto END
+        iload_1;
+        bipush    10;
+        if_icmpge    END;
+
+        // if #1 > 1: goto LOOPc
+        iload_1;
+        iconst_1;
+        if_icmpgt    LOOPc;
+
+        // #2 = 0;
+        iconst_0;
+        istore_2;
+
+    LOOPb:
+        // if #2 > 2: goto LOOPa
+        iload_2;
+        iconst_2;
+        if_icmpgt    LOOPa;
+
+        // #2 ++
+        iinc    2, 1;
+
+        goto    LOOPb;
+
+    LOOPc:
+        // #1 ++
+        iinc    1, 1;
+
+        goto    LOOPa;
+
+    END:
+        return;
+    
+  }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+super public class MoveStoreAfterInfiniteLoop
+{
+  static Field a:I;
+  static Field b:I;
+  static Field c:S;
+
+  public Method "":"()V"
+	stack 1 locals 1
+  {
+		aload_0;
+		invokespecial	Method java/lang/Object."":"()V";
+		return;
+  }
+
+public static Method test:"()V"
+    stack 3 locals 3
+  {
+    LTOP:
+        iconst_0;
+        istore_1;
+
+    LOUTER:
+        iload_1;
+        bipush    10;
+        if_icmpge    LTOP;
+
+        getstatic    Field c:"S";
+        putstatic    Field a:"I";
+
+        iconst_0;
+        istore_2;
+
+    LINNER:
+        iload_2;
+        iconst_2;
+        if_icmpge    LBOTTOM;
+
+        getstatic    Field b:"I";
+        i2s;
+        putstatic    Field c:"S";
+
+        iinc    2, 1;
+
+        goto    LINNER;
+
+    LBOTTOM:
+        iinc    1, 1;
+
+        goto    LOUTER;
+  }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2024, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8336478
+ * @summary C2: assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0) failed: should have been turned into a counted loop
+ * @compile LongCountedLoopInInfiniteLoop.jasm
+ * @run main/othervm -XX:+UnlockExperimentalVMOptions -Xcomp -XX:PerMethodTrapLimit=0 -XX:PerMethodSpecTrapLimit=0
+ *                   -XX:+IgnoreUnrecognizedVMOptions -XX:StressLongCountedLoop=2000000
+ *                   -XX:CompileCommand=compileonly,TestLongCountedLoopInInfiniteLoop::test TestLongCountedLoopInInfiniteLoop
+ */
+
+public class TestLongCountedLoopInInfiniteLoop {
+    public static void main(String[] args) {
+        LongCountedLoopInInfiniteLoop obj = new LongCountedLoopInInfiniteLoop();
+        test(false, obj);
+    }
+
+    private static void test(boolean flag, LongCountedLoopInInfiniteLoop obj) {
+        if (flag) {
+            obj.test();
+        }
+    }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2024, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8338100
+ * @summary C2: assert(!n_loop->is_member(get_loop(lca))) failed: control must not be back in the loop
+ * @compile MoveStoreAfterInfiniteLoop.jasm
+ * @run main/othervm -Xcomp -XX:-TieredCompilation -XX:CompileOnly=TestMoveStoreAfterInfiniteLoop::test
+ *                   -XX:CompileCommand=inline,MoveStoreAfterInfiniteLoop::test TestMoveStoreAfterInfiniteLoop
+ */
+
+public class TestMoveStoreAfterInfiniteLoop {
+    public static void main(String[] args) {
+        new MoveStoreAfterInfiniteLoop();
+        test(false);
+    }
+
+    private static void test(boolean flag) {
+        if (flag) {
+            MoveStoreAfterInfiniteLoop.test();
+        }
+    }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package compiler.loopopts.superword;
+
+/*
+ * @test
+ * @bug 8342498
+ * @summary Test SuperWord, when it aligns to field-store, and the corresponding allocation is eliminated.
+ * @run driver compiler.loopopts.superword.TestEliminateAllocationWithCastP2XUse
+ * @run main/othervm -Xbatch
+ *                   -XX:-SplitIfBlocks -XX:LoopMaxUnroll=8
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:DominatorSearchLimit=45
+ *                   compiler.loopopts.superword.TestEliminateAllocationWithCastP2XUse
+ */
+
+public class TestEliminateAllocationWithCastP2XUse {
+    public static void main(String args[]) {
+        byte[] a = new byte[10_000];
+        for (int i = 0; i < 10000; i++) {
+            test(a);
+        }
+    }
+
+    // Summary:
+    //  - Some B allocations are detected as NoEscape, but cannot be removed because of a field load.
+    //  - The field loads cannot be LoadNode::split_through_phi because DominatorSearchLimit is too low
+    //    for the dominates query to look through some IfNode / IfProj path.
+    //  - We go into loop-opts.
+    //  - In theory, the Stores of B::offset would be moved out of the loop. But we disable
+    //    PhaseIdealLoop::try_move_store_after_loop by setting -XX:-SplitIfBlocks.
+    //  - The field loads are folded away because of some MaxUnroll trick, where the val constant folds to 1.
+    //  - SuperWord eventually kicks in, and vectorizes the array stores.
+    //  - Since some vectorization has happened, SuperWord wants to align the main loop with a memory reference
+    //    in the loop. The code here is not very smart, and just picks the memory reference that occurs the
+    //    most often. But the B::offset stores occur more often than the array stores, and so we align to
+    //    one of the B::offset stores. This inserts a CastP2X under the CheckCastPP of the B allocation.
+    //  - Once loop opts is over, we eventually go into macro expansion.
+    //  - During macro expansion, we now discover that the Allocations were marked NoEscape, and that by now
+    //    there are no field loads any more: yay, we can remove the allocation!
+    //  - ... except that there is the CastP2X from SuperWord alignment ...
+    //  - The Allocation removal code wants to pattern match the CastP2X as part of a GC barrier, but then
+    //    the pattern does not conform to the expecatation - it is after all from SuperWord. This leads to
+    //    an assert, and SIGSEGV in product, at least with G1GC.
+    public static long test(byte[] a) {
+        // Delay val == 1 until loop-opts, with MaxUnroll trick.
+        int val = 0;
+        for (int i = 0; i < 4; i++) {
+            if ((i % 2) == 0) {
+                val = 1;
+            }
+        }
+        // during loop opts, we learn val == 1
+        // But we don't know that during EscapeAnalysis (EA) yet.
+
+        // 9 Allocations, discovered as NoEscape during EA.
+        B b1 = new B();
+        B b2 = new B();
+        B b3 = new B();
+        B b4 = new B();
+        B b5 = new B();
+        B b6 = new B();
+        B b7 = new B();
+        B b8 = new B();
+        B b9 = new B();
+
+        // Some path of IfNode / IfProj.
+        // Only folds away once we know val == 1
+        // This delays the LoadNode::split_through_phi, because it needs a dominates call
+        // to succeed, but it cannot look through this path because we set -XX:DominatorSearchLimit=45
+        // i.e. just a little too low to be able to look through.
+        // Without the LoadNode::split_through_phi before the end of EA, the Allocation cannot yet be
+        // removed, due to a "Field load", i.e. that Load for B::offset.
+        // But later, this path can actually fold away, when we know that val == 1. At that point,
+        // also the Load from B::offset folds away because LoadNode::split_through_phi succeeds
+        // At that point the B allocations have no Loads any more, and can be removed... but this only
+        // happens at macro expansion, after all loop opts.
+        if (val == 1010) { throw new RuntimeException("never"); }
+        if (val == 1020) { throw new RuntimeException("never"); }
+        if (val == 1030) { throw new RuntimeException("never"); }
+        if (val == 1040) { throw new RuntimeException("never"); }
+        if (val == 1060) { throw new RuntimeException("never"); }
+        if (val == 1070) { throw new RuntimeException("never"); }
+        if (val == 1080) { throw new RuntimeException("never"); }
+        if (val == 1090) { throw new RuntimeException("never"); }
+
+        if (val == 2010) { throw new RuntimeException("never"); }
+        if (val == 2020) { throw new RuntimeException("never"); }
+        if (val == 2030) { throw new RuntimeException("never"); }
+        if (val == 2040) { throw new RuntimeException("never"); }
+        if (val == 2060) { throw new RuntimeException("never"); }
+        if (val == 2070) { throw new RuntimeException("never"); }
+        if (val == 2080) { throw new RuntimeException("never"); }
+        if (val == 2090) { throw new RuntimeException("never"); }
+
+        if (val == 3010) { throw new RuntimeException("never"); }
+        if (val == 3020) { throw new RuntimeException("never"); }
+        if (val == 3030) { throw new RuntimeException("never"); }
+        if (val == 3040) { throw new RuntimeException("never"); }
+        if (val == 3060) { throw new RuntimeException("never"); }
+        if (val == 3070) { throw new RuntimeException("never"); }
+        if (val == 3080) { throw new RuntimeException("never"); }
+        if (val == 3090) { throw new RuntimeException("never"); }
+
+        if (val == 4010) { throw new RuntimeException("never"); }
+        if (val == 4020) { throw new RuntimeException("never"); }
+        if (val == 4030) { throw new RuntimeException("never"); }
+        if (val == 4040) { throw new RuntimeException("never"); }
+        if (val == 4060) { throw new RuntimeException("never"); }
+        if (val == 4070) { throw new RuntimeException("never"); }
+        if (val == 4080) { throw new RuntimeException("never"); }
+        if (val == 4090) { throw new RuntimeException("never"); }
+
+        long mulVal = 1;
+        for (int i = 0; i < a.length; i++) {
+            mulVal *= 3;
+            // We do some vector store, so that SuperWord succeeds, and creates the
+            // alignment code, which emits the CastP2X.
+            a[i]++;
+            // But we also have 9 Stores for the B::offset.
+            // SuperWord now sees more of these stores than of the array stores, and picks
+            // one of the B::offset stores as the alignment reference... creating a CastP2X
+            // for the CheckCastPP of the B allocation.
+            b1.offset = mulVal;
+            b2.offset = mulVal;
+            b3.offset = mulVal;
+            b4.offset = mulVal;
+            b5.offset = mulVal;
+            b6.offset = mulVal;
+            b7.offset = mulVal;
+            b8.offset = mulVal;
+            b9.offset = mulVal;
+        }
+
+        // This folds the loads away, once we know val == 1
+        // That happens during loop-opts, so after EA, but before macro expansion.
+        long ret = 0;
+        if (val == 42) {
+            ret = b1.offset +
+                  b2.offset +
+                  b3.offset +
+                  b4.offset +
+                  b5.offset +
+                  b6.offset +
+                  b7.offset +
+                  b8.offset +
+                  b9.offset;
+        }
+
+        return ret;
+    }
+
+    static class B {
+        // Add padding so that the old SuperWord::can_create_pairs accepts the field store to B.offset
+        long pad1 = 0;   // at 16
+        long pad2 = 0;   // at 24
+        long pad3 = 0;   // at 32
+        long pad4 = 0;   // at 40
+        long pad5 = 0;   // at 48
+        long pad6 = 0;   // at 56
+        long offset = 0; // offset at 64 bytes
+    }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/gc/TestDisableExplicitGC.java openjdk-17-17.0.15+6/test/hotspot/jtreg/gc/TestDisableExplicitGC.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/gc/TestDisableExplicitGC.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/gc/TestDisableExplicitGC.java	2025-04-09 19:45:33.000000000 +0000
@@ -26,6 +26,7 @@
 /*
  * @test TestDisableExplicitGC
  * @requires vm.opt.DisableExplicitGC == null
+ * @requires vm.compMode != "Xcomp"
  * @summary Verify GC behavior with DisableExplicitGC flag.
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @library /test/lib
+ * @requires os.family != "Windows"
+ * @run driver TestGetCreatedJavaVMs
+ */
+import jdk.test.lib.Utils;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+
+public class TestGetCreatedJavaVMs {
+    public static void main(String args[]) throws Exception {
+        ProcessBuilder pb = ProcessTools.createNativeTestProcessBuilder("GetCreatedJavaVMs");
+        OutputAnalyzer output = ProcessTools.executeProcess(pb);
+        output.shouldHaveExitValue(0);
+        output.reportDiagnosticSummary();
+    }
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* This code tests concurrent creation of and then attach to a JVM.
+ * Two threads race to create the JVM, the loser then checks GetCreatedJavaVMs
+ * and attaches to the returned JVM. Prior to the fix this could crash as the
+ * JVM is not fully initialized.
+ */
+#include "jni.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define NUM_THREADS 2
+
+void *thread_runner(void *threadid) {
+  int tid;
+  tid = (int)(intptr_t)threadid;
+
+  JavaVM *vm;
+  JNIEnv *env = 0;
+
+  JavaVMInitArgs vm_args;
+  JavaVMOption options[0];
+  vm_args.version = JNI_VERSION_1_2;
+  vm_args.nOptions = 0;
+  vm_args.options = options;
+  vm_args.ignoreUnrecognized = JNI_FALSE;
+
+  printf("[%d] BEGIN JNI_CreateJavaVM\n", tid);
+  jint create_res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
+  printf("[%d] END JNI_CreateJavaVM\n", tid);
+
+  if (create_res != JNI_OK) {
+    printf("[%d] Error creating JVM: %d\n", tid, create_res);
+    if (create_res == JNI_EEXIST) {
+      jsize count;
+      printf("[%d] BEGIN JNI_GetCreatedJavaVMs\n", tid);
+      jint get_res = JNI_GetCreatedJavaVMs(&vm, 1, &count);
+      printf("[%d] END JNI_GetCreatedJavaVMs\n", tid);
+
+      if (get_res != JNI_OK) {
+        printf("[%d] Error obtaining created VMs: %d\n", tid, get_res);
+        pthread_exit(NULL);
+      } else {
+        printf("[%d] Obtained %d created VMs\n", tid, count);
+      }
+      if (count > 0) {
+        printf("[%d] BEGIN AttachCurrentThread\n", tid);
+        get_res = (*vm)->AttachCurrentThread(vm, (void **)&env, NULL);
+        printf("[%d] END AttachCurrentThread - %s\n", tid,
+               (get_res == JNI_OK ? "succeeded" : "failed"));
+        if (get_res == JNI_OK) {
+          (*vm)->DetachCurrentThread(vm);
+        }
+      }
+      pthread_exit(NULL);
+    } else {
+      pthread_exit(NULL);
+    }
+  } else {
+    printf("[%d] Created a JVM\n", tid);
+  }
+
+  pthread_exit(NULL);
+}
+
+int main (int argc, char* argv[]) {
+  pthread_t threads[NUM_THREADS];
+  for (int i = 0; i < NUM_THREADS; i++ ) {
+    printf("[*] Creating thread %d\n", i);
+    int status = pthread_create(&threads[i], NULL, thread_runner, (void *)(intptr_t)i);
+    if (status != 0) {
+      printf("[*] Error creating thread %d - %d\n", i, status);
+      exit(-1);
+    }
+  }
+  for (int i = 0; i < NUM_THREADS; i++ ) {
+    pthread_join(threads[i], NULL);
+  }
+  return 0;
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java openjdk-17-17.0.15+6/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java	1970-01-01 00:00:00.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java	2025-04-09 19:45:33.000000000 +0000
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8317636
+ * @summary The test verifies heap walking API (FollowReferences) reports
+ *     field indeces in correct order (as described by jvmtiHeapReferenceInfoField spec).
+ *     For simplification only primitive field callback is tested
+ *     and all fields in the test classes are 'int'.
+ *     Field IDs are not reported to the callback, so the test uses field values
+ *     to distinguish between fields, so all field values in the test classes should be unique.
+ * @run main/othervm/native -agentlib:FieldIndicesTest FieldIndicesTest
+ */
+
+import java.lang.ref.Reference;
+
+// Test class hierarchy is based on the example described in the spec.
+// Extra fields added to improve coverage.
+interface I0 {
+    int p = 10;
+    // extra fields
+    public int p5 = 11;
+    int p6 = 12;
+    public int p1 = 13;
+}
+
+interface I1 extends I0 {
+    int x = 20;
+    // extra fields
+    int x1 = 21;
+    public int x2 = 22;
+}
+
+interface I2 extends I0 {
+    int y = 30;
+    // extra fields
+    int y9 = 31;
+    public int y4 = 32;
+    public int y3 = 33;
+}
+
+class C1 implements I1 {
+    public static int a = 40;
+    private int b = 41;
+    // extra fields
+    private int a1 = 42;
+    protected static int b7 = 43;
+    static int b2 = 44;
+    final protected int a3 = 45;
+    static int a2 = 46;
+    public int b1 = 47;
+}
+
+class C2 extends C1 implements I2 {
+    static int q = 60;
+    final int r = 61;
+    // extra fields
+    private int q11 = 61;
+    final static int q9 = 62;
+    static int q2 = 63;
+    final protected int r3 = 64;
+    public int r7 = 65;
+}
+
+public class FieldIndicesTest {
+    static {
+        System.loadLibrary("FieldIndicesTest");
+    }
+
+    private static native void prepare(Object testObject);
+
+    private static native void test(Object rootObject);
+
+    private static native boolean testFailed();
+
+    private static void prepare(String name, Object testObject) {
+        System.out.println(">>prepare(" + name + ")");
+        prepare(testObject);
+        System.out.println("<>test(" + name + ")");
+        test(rootObject);
+        System.out.println("<
+#include 
+#include "jvmti.h"
+#include "jvmti_common.h"
+
+extern "C" {
+
+static jvmtiEnv* jvmti = nullptr;
+static bool test_failed = false;
+
+static void* allocate(JNIEnv* env, jlong size) {
+  unsigned char* result = nullptr;
+  check_jvmti_status(env,
+    jvmti->Allocate(size, &result),
+    "Allocate failed");
+  return result;
+}
+
+static void deallocate(JNIEnv* env, void* mem) {
+  check_jvmti_status(env,
+    jvmti->Deallocate((unsigned char*)mem),
+    "Deallocate failed");
+}
+
+// Converts JNI class name signature to simple name (in place).
+static void sig2name(char* str) {
+  size_t len = strlen(str);
+  if (len >=2 && str[0] == 'L' && str[len-1] == ';') {
+    len -=2;
+    memmove(str, str+1, len);
+    str[len] = '\0';
+  }
+  // Replace '/' with '.'.
+  for (char* pos = str; (pos = strchr(pos, '/')) != nullptr; ) {
+    *pos = '.';
+  }
+}
+
+static bool is_static_field(JNIEnv* env, jclass klass, jfieldID fid) {
+  enum {
+    ACC_STATIC        = 0x0008
+  };
+
+  jint access_flags = 0;
+  check_jvmti_status(env,
+    jvmti->GetFieldModifiers(klass, fid, &access_flags),
+    "GetFieldModifiers failed");
+  return (access_flags & ACC_STATIC) != 0;
+}
+
+static void verify_int_field(JNIEnv* env, jclass klass, jfieldID fid) {
+  char* name = nullptr;
+  char* sig = nullptr;
+  check_jvmti_status(env,
+    jvmti->GetFieldName(klass, fid, &name, &sig, nullptr),
+    "GetFieldName failed");
+
+  if (strcmp(sig, "I") != 0) {
+    printf("ERROR: field '%s' is not int ('%s')\n", name, sig);
+    fflush(nullptr);
+    fatal(env, "unexpected field type");
+  }
+
+  deallocate(env, name);
+  deallocate(env, sig);
+}
+
+
+/*
+Per jvmtiHeapReferenceInfoField spec (reference information for
+JVMTI_HEAP_REFERENCE_FIELD and JVMTI_HEAP_REFERENCE_STATIC_FIELD references.):
+If the referrer object is not an interface, then the field indices are determined as follows:
+- make a list of all the fields in C and its superclasses,
+  starting with all the fields in java.lang.Object and ending with all the fields in C.
+- Within this list, put the fields for a given class in the order returned by GetClassFields.
+- Assign the fields in this list indices n, n+1, ..., in order,
+  where n is the count of the fields in all the interfaces implemented by C.
+  Note that C implements all interfaces directly implemented by its superclasses;
+  as well as all superinterfaces of these interfaces.
+If the referrer object is an interface, then the field indices are determined as follows:
+- make a list of the fields directly declared in I.
+- Within this list, put the fields in the order returned by GetClassFields.
+- Assign the fields in this list indices n, n+1, ..., in order,
+  where n is the count of the fields in all the superinterfaces of I.
+
+'Klass' struct contains all required data to calculate field indices.
+Also contains static field values.
+For each test class, the 'Klass' struct is created and a pointer to it is set as the jclass's tag.
+*/
+
+struct Klass {
+  jclass klass;
+  char* name;
+  Klass* super_klass;
+
+  struct Field {
+    jfieldID id;
+    char* name;
+
+    // Field value for static fields (0 for instance fields).
+    // All fields in the test classes are 'int'.
+    jint value;
+
+    void init(JNIEnv* env, jclass klass, jfieldID fid);
+  };
+
+  // Fields of the class and its superclasses
+  // as described in jvmtiHeapReferenceInfoField spec.
+  Field* fields;
+  jint field_count;
+
+  // Interfaces implemented by this klass, superclasses and superinterfaces.
+  Klass** interfaces;
+  jint interface_count;
+
+  // Number of fields in all implemented interfaces.
+  jint interface_field_count;
+
+  static Klass* explore(JNIEnv* env, jclass klass);
+
+private:
+  // Initializes fields, field_count.
+  void explore_fields(JNIEnv* env);
+  // Initializes interfaces, interface_count.
+  void explore_interfaces(JNIEnv* env);
+
+  void print() const;
+};
+
+/*
+For each test object, the 'Object' struct is created and a pointer to it is set as the jobject's tag.
+*/
+struct Object {
+  Klass* klass;
+  // Values of instance fields (0 for static fields).
+  // Size of the array == klass->field_count.
+  jint* field_values;
+
+  static Object* explore(JNIEnv* env, jobject obj);
+};
+
+
+void Klass::Field::init(JNIEnv* env, jclass klass, jfieldID fid) {
+  id = fid;
+  check_jvmti_status(env,
+    jvmti->GetFieldName(klass, fid, &name, nullptr, nullptr),
+    "GetFieldName failed");
+  if (is_static_field(env, klass, fid)) {
+    verify_int_field(env, klass, fid);
+    value = env->GetStaticIntField(klass, fid);
+  } else {
+    value = 0;
+  }
+}
+
+void Klass::explore_fields(JNIEnv* env) {
+  jint this_count;
+  jfieldID* this_fields;
+  check_jvmti_status(env,
+    jvmti->GetClassFields(klass, &this_count, &this_fields),
+    "GetClassFields failed");
+
+  jint super_count = super_klass != nullptr ? super_klass->field_count : 0;
+
+  fields = (Field*)allocate(env, sizeof(Field) * (super_count + this_count));
+  field_count = 0;
+
+  if (super_klass != 0) {
+    // super_klass->fields already contains fields from all superclasses in the required order.
+    for (int i = 0; i < super_count; i++) {
+      fields[field_count++].init(env, super_klass->klass, super_klass->fields[i].id);
+    }
+  }
+
+  // Add field of this class to the end of the list.
+  for (int i = 0; i < this_count; i++) {
+    fields[field_count++].init(env, klass, this_fields[i]);
+  }
+  deallocate(env, this_fields);
+}
+
+
+// Calculates maximum number of implemented interfaces of the klass and its superinterfaces.
+static jint get_max_interface_count(JNIEnv* env, jclass klass) {
+  jint interface_count;
+  jclass* interfaces;
+  check_jvmti_status(env,
+    jvmti->GetImplementedInterfaces(klass, &interface_count, &interfaces),
+    "GetImplementedInterfaces failed");
+
+  jint result = interface_count;
+  // interfaces implemented by superinterfaces
+  for (jint i = 0; i < interface_count; i++) {
+    result += get_max_interface_count(env, interfaces[i]);
+  }
+
+  deallocate(env, interfaces);
+
+  return result;
+}
+
+// Explores all interfaces implemented by 'klass', sorts out duplicates,
+// and stores the interfaces in the 'arr' starting from 'index'.
+// Returns number of the interfaces added.
+static jint fill_interfaces(Klass** arr, jint index, JNIEnv* env, jclass klass) {
+  jint interface_count;
+  jclass* interfaces;
+  check_jvmti_status(env,
+    jvmti->GetImplementedInterfaces(klass, &interface_count, &interfaces),
+    "GetImplementedInterfaces failed");
+
+  jint count = 0;
+  for (jint i = 0; i < interface_count; i++) {
+    // Skip interface if it's already in the array
+    // (i.e. implemented by another superclass/superinterface).
+    bool dup = false;
+    for (jint j = 0; j < index; j++) {
+      if (env->IsSameObject(arr[j]->klass, interfaces[i]) == JNI_TRUE) {
+        dup = true;
+        break;
+      }
+    }
+    if (dup) {
+      continue;
+    }
+
+    // Add the interface.
+    arr[index + count] = Klass::explore(env, interfaces[i]);
+    count++;
+
+    // And explore its superinterfaces.
+    count += fill_interfaces(arr, index + count, env, interfaces[i]);
+  }
+
+  deallocate(env, interfaces);
+
+  return count;
+}
+
+void Klass::explore_interfaces(JNIEnv* env) {
+  jint max_count = get_max_interface_count(env, klass);
+  if (super_klass != nullptr) {
+    max_count += super_klass->interface_count;
+  }
+
+  // Allocate array for maximum possible count.
+  interfaces = (Klass**)allocate(env, sizeof(Klass*) * max_count);
+
+  interface_count = 0;
+  if (super_klass != nullptr) {
+    // Add all interfaces implemented by super_klass first.
+    interface_count = super_klass->interface_count;
+    memcpy(interfaces, super_klass->interfaces, sizeof(Klass*) * super_klass->interface_count);
+  }
+
+  // Interfaces implemented by the klass.
+  interface_count += fill_interfaces(interfaces, interface_count, env, klass);
+}
+
+void Klass::print() const {
+  printf("Explored klass: %s, super: %s\n",
+         name, super_klass == nullptr ? nullptr : super_klass->name);
+  printf("  interfaces (%d):\n", (int)interface_count);
+  for (jint i = 0; i < interface_count; i++) {
+    printf("    %d: %s\n", (int)i, interfaces[i]->name);
+  }
+  printf("  fields (%d):\n", (int)field_count);
+  for (jint i = 0; i < field_count; i++) {
+    printf("    %d: %s (value = %d)\n",
+           (int)i, fields[i].name, (int)fields[i].value);
+  }
+  printf("  interface_field_count: %d\n", (int)interface_field_count);
+}
+
+Klass* Klass::explore(JNIEnv* env, jclass klass) {
+  jlong tag = 0;
+  check_jvmti_status(env,
+    jvmti->GetTag(klass, &tag),
+    "GetTag failed");
+  if (tag != 0) { // already explored
+    return (Klass*)tag;
+  }
+
+  Klass* result = (Klass*)allocate(env, sizeof(Klass));
+
+  result->klass = (jclass)env->NewGlobalRef(klass);
+
+  check_jvmti_status(env,
+    jvmti->GetClassSignature(klass, &result->name, nullptr),
+    "GetClassSignature failed");
+  sig2name(result->name);
+
+  // Explore superclass first.
+  jclass super_klass = env->GetSuperclass(klass);
+  result->super_klass = super_klass == nullptr ? nullptr : Klass::explore(env, super_klass);
+
+  result->explore_fields(env);
+
+  result->explore_interfaces(env);
+
+  // Calculate interface_field_count.
+  result->interface_field_count = 0;
+  for (jint i = 0; i < result->interface_count; i++) {
+    result->interface_field_count += result->interfaces[i]->field_count;
+  }
+
+  check_jvmti_status(env,
+    jvmti->SetTag(klass, (jlong)result),
+    "SetTag failed");
+
+  result->print();
+
+  return result;
+}
+
+Object* Object::explore(JNIEnv* env, jobject obj) {
+  jlong tag = 0;
+  check_jvmti_status(env,
+    jvmti->GetTag(obj, &tag),
+    "GetTag failed");
+  if (tag != 0) { // already explored
+    return (Object*)tag;
+  }
+
+  jclass obj_klass = env->GetObjectClass(obj);
+  Klass* klass = Klass::explore(env, obj_klass);
+  jint* values = (jint*)allocate(env, sizeof(jint) * klass->field_count);
+
+  for (jint i = 0; i < klass->field_count; i++) {
+    jfieldID fid = klass->fields[i].id;
+    if (is_static_field(env, obj_klass, fid)) {
+      values[i] = 0;
+    } else {
+      verify_int_field(env, obj_klass, fid);
+      values[i] = env->GetIntField(obj, fid);
+    }
+  }
+
+  Object* result = (Object*)allocate(env, sizeof(Object));
+  result->klass = klass;
+  result->field_values = values;
+
+  check_jvmti_status(env,
+    jvmti->SetTag(obj, (jlong)result),
+    "SetTag failed");
+
+  return result;
+}
+
+
+JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
+  jint res = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_1);
+  if (res != JNI_OK || jvmti == nullptr) {
+    printf("jvm->GetEnv failed\n");
+    fflush(nullptr);
+    return JNI_ERR;
+  }
+
+  jvmtiCapabilities caps;
+  memset(&caps, 0, sizeof(caps));
+  caps.can_tag_objects = 1;
+  jvmtiError err = jvmti->AddCapabilities(&caps);
+  if (err != JVMTI_ERROR_NONE) {
+    printf("AddCapabilities failed: %s (%d)\n", TranslateError(err), err);
+    fflush(nullptr);
+    return JNI_ERR;
+  }
+
+  return JNI_OK;
+}
+
+
+static bool check_index_bounds(jint index, Klass* klass) {
+  if (index < klass->interface_field_count) {
+    printf("ERROR: field_index is too small (%d < %d)\n",
+           (int)index, (int)klass->interface_field_count);
+    test_failed = true;
+    return false;
+  }
+  if (index >= klass->interface_field_count + klass->field_count) {
+    printf("ERROR: field_index is too big (%d >= %d)\n",
+           (int)index, (int)(klass->interface_field_count + klass->field_count));
+    test_failed = true;
+    return false;
+  }
+  return true;
+}
+
+static char* get_field_name(Klass* klass, jint index) {
+  index -= klass->interface_field_count;
+  if (index < 0 || index >= klass->field_count) {
+    return nullptr;
+  }
+  return klass->fields[index].name;
+}
+
+
+jint JNICALL primitiveFieldCallback(
+   jvmtiHeapReferenceKind        reference_kind,
+   const jvmtiHeapReferenceInfo* reference_info,
+   jlong                         class_tag,
+   jlong*                        tag_ptr,
+   jvalue                        value,
+   jvmtiPrimitiveType            value_type,
+   void*                         user_data)
+{
+  if (*tag_ptr == 0) {
+    return 0;
+  }
+
+  jint index = reference_info->field.index;
+  jint int_value = value.i;
+  if (value_type != JVMTI_PRIMITIVE_TYPE_INT) {
+    printf("ERROR: unexpected value type in primitiveFieldCallback: '%c'\n", (char)value_type);
+    test_failed = true;
+    int_value = -1;
+  }
+
+  if (reference_kind == JVMTI_HEAP_REFERENCE_FIELD) {
+    Object* obj = (Object*)(*tag_ptr);
+    Klass* klass = obj->klass;
+    printf("primitiveFieldCallback(JVMTI_HEAP_REFERENCE_FIELD): "
+           "klass=%s, index=%d, type=%c, value=%d\n",
+           klass->name, index,
+           (int)value_type, (int)value.i);
+    if (check_index_bounds(index, klass)) {
+      jint expected_value = obj->field_values[index - klass->interface_field_count];
+      if (int_value != expected_value) {
+        printf("  ERROR: wrong instance value: (%d, expected %d)\n",
+               (int)int_value, (int)expected_value);
+        test_failed = true;
+      } else {
+        printf("  OK: field %s.%s, value %d\n",
+               klass->name, get_field_name(klass, index), (int)int_value);
+      }
+    }
+  } else if (reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) {
+    Klass* klass = (Klass*)(*tag_ptr);
+    printf("primitiveFieldCallback(JVMTI_HEAP_REFERENCE_STATIC_FIELD): "
+           "klass=%s, index=%d, type=%c, value=%d\n",
+           klass->name, index,
+           (int)value_type, (int)value.i);
+    if (check_index_bounds(index, klass)) {
+      jint expected_value = klass->fields[index - klass->interface_field_count].value;
+      if (int_value != expected_value) {
+        printf("  ERROR: wrong static value: (%d, expected %d)\n\n\n",
+               (int)int_value, (int)expected_value);
+        test_failed = true;
+      } else {
+        printf("  OK: field %s.%s, value %d\n",
+               klass->name, get_field_name(klass, index), (int)int_value);
+      }
+    }
+  } else {
+    printf("ERROR: unexpected reference_kind in primitiveFieldCallback: %d\n", (int)reference_kind);
+    test_failed = true;
+  }
+
+  fflush(nullptr);
+  return 0;
+}
+
+
+JNIEXPORT void JNICALL
+Java_FieldIndicesTest_prepare(JNIEnv *env, jclass cls, jobject testObj) {
+  Object::explore(env, testObj);
+  fflush(nullptr);
+}
+
+JNIEXPORT void JNICALL
+Java_FieldIndicesTest_test(JNIEnv *env, jclass cls, jobject rootObject) {
+  jvmtiHeapCallbacks heapCallbacks;
+  memset(&heapCallbacks, 0, sizeof(heapCallbacks));
+
+  heapCallbacks.primitive_field_callback = primitiveFieldCallback;
+
+  check_jvmti_status(env,
+    jvmti->FollowReferences(JVMTI_HEAP_FILTER_UNTAGGED, // heap_filter
+                            nullptr,                    // class
+                            rootObject,                 // initial_object
+                            &heapCallbacks,
+                            nullptr),
+    "FollowReferences failed");
+  fflush(nullptr);
+}
+
+JNIEXPORT jboolean JNICALL
+Java_FieldIndicesTest_testFailed(JNIEnv *env, jclass cls) {
+  return test_failed ? JNI_TRUE : JNI_FALSE;
+}
+
+}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -85,7 +85,7 @@
     }
 
     public int run() {
-        log = new Log(System.out, verbose);
+        log = new Log(System.out);
         log.display("Parallel matrix multiplication test");
 
         Matrix a = Matrix.randomMatrix(dim);
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,13 +24,13 @@
 
 import java.net.MalformedURLException;
 
+import vm.share.gc.HeapOOMEException;
 import vm.share.gc.TriggerUnloadingByFillingMetaspace;
 import vm.share.gc.TriggerUnloadingHelper;
 import vm.share.gc.TriggerUnloadingWithWhiteBox;
 
 import metaspace.stressHierarchy.common.classloader.tree.Node;
 import metaspace.stressHierarchy.common.classloader.tree.Tree;
-import metaspace.stressHierarchy.common.exceptions.GotWrongOOMEException;
 import metaspace.stressHierarchy.common.exceptions.TimeIsOverException;
 import metaspace.stressHierarchy.common.generateHierarchy.GenerateHierarchyHelper;
 import metaspace.stressHierarchy.common.generateHierarchy.GenerateHierarchyHelper.Type;
@@ -109,8 +109,8 @@
 
             System.out.println("Whole test took " + ((System.currentTimeMillis() - startTimeStamp)/1000/60.0) +" min");
             log.info("Test PASSED");
-        } catch (GotWrongOOMEException e) {
-            log.info("GotWrongOOMEExc: " + e.getMessage());
+        } catch (HeapOOMEException e) {
+            log.info("HeapOOMEException: " + e.getMessage());
             log.info("Got wrong type of OOME. We are passing test as it breaks test logic. We have dedicated test configurations" +
             " for each OOME type provoking class unloading, that's why we are not missing test coverage here.");
         } catch (OutOfMemoryError e) {
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/exceptions/GotWrongOOMEException.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/exceptions/GotWrongOOMEException.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/exceptions/GotWrongOOMEException.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/exceptions/GotWrongOOMEException.java	1970-01-01 00:00:00.000000000 +0000
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-package metaspace.stressHierarchy.common.exceptions;
-
-/**
- * Usually this means that we got OOME:heap while trying to gain OOME:metaspace.
- * We pass test in this case as this breaks test logic. We have dedicated test configurations
- * for OOME:heap provoking class unloading, that why we are not missing test coverage here.
- */
-public class GotWrongOOMEException extends RuntimeException {
-
-    private static final long serialVersionUID = 1L;
-
-    public GotWrongOOMEException(String string) {
-        super(string);
-    }
-
-}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java	2025-04-09 19:45:33.000000000 +0000
@@ -71,7 +71,6 @@
 
         argHandler = new ArgumentHandler(args);
         log = new Log(this.out, argHandler);
-        //log.enableVerbose(true);
     }
 
     private PrintStream out;
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java	2025-04-09 19:45:33.000000000 +0000
@@ -139,13 +139,34 @@
         }
     }
 
+    // get thread ID for "startNewThread" command
+    private long getNewThreadId() throws Exception {
+        final String debugeeClassSig = "L" + getDebugeeClassName().replace('.', '/') + ";";
+        log.display("  getting classID for " + debugeeClassSig);
+        long classID = debuggee.getReferenceTypeID(debugeeClassSig);
+        log.display("  got classID: " + classID);
+
+        log.display("  getting testNewThread field value");
+        JDWP.Value value = debuggee.getStaticFieldValue(classID, "testNewThread", JDWP.Tag.THREAD);
+
+        long threadID = ((Long)value.getValue()).longValue();
+        log.display("  got threadID: " + threadID);
+        return threadID;
+    }
+
     private int createThreadStartEventRequest() {
         try {
+            long newThreadId = getNewThreadId();
             // create command packet and fill requred out data
             CommandPacket command = new CommandPacket(JDWP.Command.EventRequest.Set);
             command.addByte(JDWP.EventKind.THREAD_START);
             command.addByte(JDWP.SuspendPolicy.ALL);
-            command.addInt(0);
+            // we want the THREAD_START event only for the test thread
+            // and not any others that might be started by debuggee VM,
+            // so add THREAD_ONLY modifier
+            command.addInt(1);
+            command.addByte(JDWP.EventModifierKind.THREAD_ONLY);
+            command.addObjectID(newThreadId);
             command.setLength();
 
             transport.write(command);
@@ -175,7 +196,7 @@
         Value value;
 
         value = new Value(JDWP.Tag.INT, 0);
-        // create command with invalid trheadID, expect INVALID_OBJECT error
+        // create command with invalid threadID, expect INVALID_OBJECT error
         sendCommand(-1, value, true, JDWP.Error.INVALID_OBJECT);
 
         // create StateTestThread
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java	2025-04-09 19:45:33.000000000 +0000
@@ -51,14 +51,7 @@
 
             return true;
         } else if (command.equals(COMMAND_START_NEW_THREAD)) {
-            Thread thread = new Thread(new Runnable() {
-                public void run() {
-                    log.display("Thread exit");
-                }
-            });
-
-            thread.setName("forceEarlyReturn002a_NewThread");
-            thread.start();
+            testNewThread.start();
 
             return true;
         }
@@ -66,6 +59,21 @@
         return false;
     }
 
+    @Override
+    protected void init(String args[]) {
+        super.init(args);
+
+        // create thread for "NewThread" command in advance
+        testNewThread = new Thread(new Runnable() {
+            public void run() {
+                log.display("Thread exit");
+            }
+        });
+        testNewThread.setName("forceEarlyReturn002a_NewThread");
+    }
+
+    private static Thread testNewThread;
+
     private Thread testThreadInNative;
 
     private void stopThreadInNative() {
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,6 @@
         log = new Log(out, argHandler);
         testObjects = new Object[]{new TaggedClass(),
                                    new UntaggedClass()};
-        log.enableVerbose(true);
         log.display("Verifying reachable objects.");
         status = checkStatus(status);
         testObjects = null;
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,6 +88,9 @@
         int res = -1;
         long start_time = System.currentTimeMillis();
         while (System.currentTimeMillis() < start_time + (timeMax * 1000)) {
+            // Start each loop with a clear log buffer so we only
+            // track the run that can potentially fail:
+            log.clearLogBuffer();
             count++;
 
             // Original suspendthrd001 test block starts here:
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,7 +40,6 @@
     public static int run(String[] argv, PrintStream out) {
         ArgumentHandler argHandler = new ArgumentHandler(argv);
         Log log = new Log(out, argHandler);
-        log.enableVerbose(true);
 
         monitor = Monitor.getMemoryMonitor(log, argHandler);
         List pools = monitor.getMemoryPoolMBeans();
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,6 @@
     public static int run(String[] argv, PrintStream out) {
         ArgumentHandler argHandler = new ArgumentHandler(argv);
         Log log = new Log(out, argHandler);
-        log.enableVerbose(true); // show log output
 
         MemoryMonitor monitor = Monitor.getMemoryMonitor(log, argHandler);
         List pools = monitor.getMemoryPoolMBeans();
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -58,7 +58,7 @@
 
     @Override
     public void run() {
-        Log log = new Log(System.out, true);
+        Log log = new Log(System.out);
         // System.err is duplicated into buffer
         // it should be empty
         MyStream stream = new MyStream(System.err);
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.cpp openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.cpp
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.cpp	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.cpp	1970-01-01 00:00:00.000000000 +0000
@@ -1,169 +0,0 @@
-/*
- * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-#include "jvmdi.h"
-#include "JVMDITools.h"
-
-extern "C" {
-
-char const *TranslateEvent(jint kind) {
-    switch (kind) {
-    case JVMDI_EVENT_SINGLE_STEP:
-        return ("JVMDI_EVENT_SINGLE_STEP");
-    case JVMDI_EVENT_BREAKPOINT:
-        return ("JVMDI_EVENT_BREAKPOINT");
-    case JVMDI_EVENT_FRAME_POP:
-        return ("JVMDI_EVENT_FRAME_POP");
-    case JVMDI_EVENT_EXCEPTION:
-        return ("JVMDI_EVENT_EXCEPTION");
-    case JVMDI_EVENT_USER_DEFINED:
-        return ("JVMDI_EVENT_USER_DEFINED");
-    case JVMDI_EVENT_THREAD_START:
-        return ("JVMDI_EVENT_THREAD_START");
-    case JVMDI_EVENT_THREAD_END:
-        return ("JVMDI_EVENT_THREAD_END");
-    case JVMDI_EVENT_CLASS_PREPARE:
-        return ("JVMDI_EVENT_CLASS_PREPARE");
-    case JVMDI_EVENT_CLASS_UNLOAD:
-        return ("JVMDI_EVENT_CLASS_UNLOAD");
-    case JVMDI_EVENT_CLASS_LOAD:
-        return ("JVMDI_EVENT_CLASS_LOAD");
-    case JVMDI_EVENT_FIELD_ACCESS:
-        return ("JVMDI_EVENT_FIELD_ACCESS");
-    case JVMDI_EVENT_FIELD_MODIFICATION:
-        return ("JVMDI_EVENT_FIELD_MODIFICATION");
-    case JVMDI_EVENT_EXCEPTION_CATCH:
-        return ("JVMDI_EVENT_EXCEPTION_CATCH");
-    case JVMDI_EVENT_METHOD_ENTRY:
-        return ("JVMDI_EVENT_METHOD_ENTRY");
-    case JVMDI_EVENT_METHOD_EXIT:
-        return ("JVMDI_EVENT_METHOD_EXIT");
-    case JVMDI_EVENT_VM_INIT:
-        return ("JVMDI_EVENT_VM_INIT");
-    case JVMDI_EVENT_VM_DEATH:
-        return ("JVMDI_EVENT_VM_DEATH");
-    default:
-        return ("");
-    }
-}
-
-char const *TranslateError(jvmdiError err) {
-    switch (err) {
-    case JVMDI_ERROR_NONE:
-        return ("JVMDI_ERROR_NONE");
-    case JVMDI_ERROR_OUT_OF_MEMORY:
-        return ("JVMDI_ERROR_OUT_OF_MEMORY");
-    case JVMDI_ERROR_ACCESS_DENIED:
-        return ("JVMDI_ERROR_ACCESS_DENIED");
-    case JVMDI_ERROR_UNATTACHED_THREAD:
-        return ("JVMDI_ERROR_UNATTACHED_THREAD");
-    case JVMDI_ERROR_VM_DEAD:
-        return ("JVMDI_ERROR_VM_DEAD");
-    case JVMDI_ERROR_INTERNAL:
-        return ("JVMDI_ERROR_INTERNAL");
-    case JVMDI_ERROR_INVALID_THREAD:
-        return ("JVMDI_ERROR_INVALID_THREAD");
-    case JVMDI_ERROR_INVALID_FIELDID:
-        return ("JVMDI_ERROR_INVALID_FIELDID");
-    case JVMDI_ERROR_INVALID_METHODID:
-        return ("JVMDI_ERROR_INVALID_METHODID");
-    case JVMDI_ERROR_INVALID_LOCATION:
-        return ("JVMDI_ERROR_INVALID_LOCATION");
-    case JVMDI_ERROR_INVALID_FRAMEID:
-        return ("JVMDI_ERROR_INVALID_FRAMEID");
-    case JVMDI_ERROR_NO_MORE_FRAMES:
-        return ("JVMDI_ERROR_NO_MORE_FRAMES");
-    case JVMDI_ERROR_OPAQUE_FRAME:
-        return ("JVMDI_ERROR_OPAQUE_FRAME");
-    case JVMDI_ERROR_NOT_CURRENT_FRAME:
-        return ("JVMDI_ERROR_NOT_CURRENT_FRAME");
-    case JVMDI_ERROR_TYPE_MISMATCH:
-        return ("JVMDI_ERROR_TYPE_MISMATCH");
-    case JVMDI_ERROR_INVALID_SLOT:
-        return ("JVMDI_ERROR_INVALID_SLOT");
-    case JVMDI_ERROR_DUPLICATE:
-        return ("JVMDI_ERROR_DUPLICATE");
-    case JVMDI_ERROR_THREAD_NOT_SUSPENDED:
-        return ("JVMDI_ERROR_THREAD_NOT_SUSPENDED");
-    case JVMDI_ERROR_THREAD_SUSPENDED:
-        return ("JVMDI_ERROR_THREAD_SUSPENDED");
-    case JVMDI_ERROR_INVALID_OBJECT:
-        return ("JVMDI_ERROR_INVALID_OBJECT");
-    case JVMDI_ERROR_INVALID_CLASS:
-        return ("JVMDI_ERROR_INVALID_CLASS");
-    case JVMDI_ERROR_CLASS_NOT_PREPARED:
-        return ("JVMDI_ERROR_CLASS_NOT_PREPARED");
-    case JVMDI_ERROR_NULL_POINTER:
-        return ("JVMDI_ERROR_NULL_POINTER");
-    case JVMDI_ERROR_ABSENT_INFORMATION:
-        return ("JVMDI_ERROR_ABSENT_INFORMATION");
-    case JVMDI_ERROR_INVALID_EVENT_TYPE:
-        return ("JVMDI_ERROR_INVALID_EVENT_TYPE");
-    case JVMDI_ERROR_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_INVALID_THREAD_GROUP:
-        return ("JVMDI_ERROR_INVALID_THREAD_GROUP");
-    case JVMDI_ERROR_INVALID_PRIORITY:
-        return ("JVMDI_ERROR_INVALID_PRIORITY");
-    case JVMDI_ERROR_NOT_FOUND:
-        return ("JVMDI_ERROR_NOT_FOUND");
-    case JVMDI_ERROR_INVALID_MONITOR:
-        return ("JVMDI_ERROR_INVALID_MONITOR");
-    case JVMDI_ERROR_ILLEGAL_ARGUMENT:
-        return ("JVMDI_ERROR_ILLEGAL_ARGUMENT");
-    case JVMDI_ERROR_NOT_MONITOR_OWNER:
-        return ("JVMDI_ERROR_NOT_MONITOR_OWNER");
-    case JVMDI_ERROR_INTERRUPT:
-        return ("JVMDI_ERROR_INTERRUPT");
-    case JVMDI_ERROR_INVALID_TYPESTATE:
-        return ("JVMDI_ERROR_INVALID_TYPESTATE");
-    case JVMDI_ERROR_INVALID_CLASS_FORMAT:
-        return ("JVMDI_ERROR_INVALID_CLASS_FORMAT");
-    case JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION:
-        return ("JVMDI_ERROR_CIRCULAR_CLASS_DEFINITION");
-    case JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_ADD_METHOD_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_SCHEMA_CHANGE_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_FAILS_VERIFICATION:
-        return ("JVMDI_ERROR_FAILS_VERIFICATION");
-#ifdef JVMDI_VERSION_1_2
-    case JVMDI_ERROR_UNSUPPORTED_VERSION:
-        return ("JVMDI_ERROR_UNSUPPORTED_VERSION");
-    case JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_HIERARCHY_CHANGE_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_DELETE_METHOD_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_NAMES_DONT_MATCH:
-        return ("JVMDI_ERROR_NAMES_DONT_MATCH");
-    case JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_CLASS_MODIFIERS_CHANGE_NOT_IMPLEMENTED");
-    case JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED:
-        return ("JVMDI_ERROR_METHOD_MODIFIERS_CHANGE_NOT_IMPLEMENTED");
-#endif
-    default:
-        return ("");
-    }
-}
-
-}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.h openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.h
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.h	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/JVMDITools.h	1970-01-01 00:00:00.000000000 +0000
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-extern "C" {
-
-char const *TranslateEvent(jint kind);
-char const *TranslateError(jvmdiError err);
-
-}
diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java
--- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java	2025-01-04 20:25:18.000000000 +0000
+++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java	2025-04-09 19:45:33.000000000 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2022, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,15 +36,9 @@
 import java.util.HashSet;
 import java.util.Vector;
 
-import nsk.share.test.LazyFormatString;
 
 /**
- * This class helps to print test-execution trace messages
- * and filter them when execution mode is not verbose.
- * 

- * Verbose mode if defined by providing -verbose command line - * option, handled by ArgumentParser. Use verbose() - * method to determine which mode is used. + * This class helps to print test-execution trace messages. *

* Log provides with two main methods to print messages: *

    @@ -63,7 +57,6 @@ * To provide printing messages from different sources into one log * with distinct prefixes use internal Log.Logger class. * - * @see #verbose() * @see #complain(String) * @see #display(String) * @see ArgumentParser @@ -79,18 +72,6 @@ protected PrintStream out = null; /** - * Is log-mode verbose? - * Always enabled. - */ - private final boolean verbose = true; - - /** - * Should log messages prefixed with timestamps? - * Always enabled. - */ - private final boolean timestamp = true; - - /** * Names for trace levels */ public static final class TraceLevel { @@ -207,33 +188,16 @@ /** * Incarnate new Log for the given stream; and - * either for verbose or for non-verbose mode accordingly to - * the given verbose key. - */ - public Log(PrintStream stream, boolean verbose) { - this(stream); - } - - /** - * Incarnate new Log for the given stream; and - * either for verbose or for non-verbose mode accordingly to * the given argsHandler. */ public Log(PrintStream stream, ArgumentParser argsParser) { - this(stream, argsParser.verbose()); + this(stream); traceLevel = argsParser.getTraceLevel(); } ///////////////////////////////////////////////////////////////// /** - * Return true if log mode is verbose. - */ - public boolean verbose() { - return verbose; - } - - /** * Return true if printing errors summary at exit is enabled. */ public boolean isErrorsSummaryEnabled() { @@ -313,9 +277,6 @@ @Deprecated public synchronized void println(String message) { doPrint(message); - if (!verbose() && isVerboseOnErrorEnabled()) { - keepLog(composeLine(message)); - } } /** @@ -329,9 +290,6 @@ */ @Deprecated public synchronized void comment(String message) { - if (!verbose()) { - doPrint(message); - } } /** @@ -361,19 +319,10 @@ } /** - * Print message to the assigned output stream, - * if log mode is verbose. The message will be lost, - * if execution mode is non-verbose, and there is no error messages - * printed. + * Print message to the assigned output stream. */ public synchronized void display(Object message) { - if (verbose()) { - doPrint(message.toString()); - } else if (isVerboseOnErrorEnabled()) { - keepLog(composeLine(message.toString())); - } else { - // ignore - } + doPrint(message.toString()); } /** @@ -382,15 +331,6 @@ * into errorsBuffer. */ public synchronized void complain(Object message) { - if (!verbose() && isVerboseOnErrorEnabled()) { - PrintStream stream = findOutStream(); - stream.println("#> "); - stream.println("#> WARNING: switching log to verbose mode,"); - stream.println("#> because error is complained"); - stream.println("#> "); - stream.flush(); - enableVerbose(true); - } String msgStr = message.toString(); printError(msgStr); if (isErrorsSummaryEnabled()) { @@ -458,10 +398,7 @@ ///////////////////////////////////////////////////////////////// /** - * Redirect log to the given stream, and switch - * log mode to verbose. - * Prints errors summary to current stream, cancel current stream - * and switches to new stream. Turns on verbose mode for new stream. + * Redirect log to the given stream. * * @deprecated This method is obsolete. */ @@ -474,17 +411,10 @@ ///////////////////////////////////////////////////////////////// /** - * Print all messages from log buffer which were hidden because - * of non-verbose mode, + * Clear all messages from log buffer. */ - private synchronized void flushLogBuffer() { - if (!logBuffer.isEmpty()) { - PrintStream stream = findOutStream(); - for (int i = 0; i < logBuffer.size(); i++) { - stream.println(logBuffer.elementAt(i)); - } - stream.flush(); - } + public synchronized void clearLogBuffer() { + logBuffer.clear(); } /** @@ -511,18 +441,15 @@ * Compose line to print possible prefixing it with timestamp. */ private String composeLine(String message) { - if (timestamp) { - long time = System.currentTimeMillis(); - long ms = time % 1000; - time /= 1000; - long secs = time % 60; - time /= 60; - long mins = time % 60; - time /= 60; - long hours = time % 24; - return "[" + hours + ":" + mins + ":" + secs + "." + ms + "] " + message; - } - return message; + long time = System.currentTimeMillis(); + long ms = time % 1000; + time /= 1000; + long secs = time % 60; + time /= 60; + long mins = time % 60; + time /= 60; + long hours = time % 24; + return "[" + hours + ":" + mins + ":" + secs + "." + ms + "] " + message; } /** @@ -557,13 +484,6 @@ } /** - * Keep the given log message into logBuffer. - */ - private synchronized void keepLog(String message) { - logBuffer.addElement(message); - } - - /** * Keep the given error message into errorsBuffer. */ private synchronized void keepError(String message) { @@ -596,7 +516,7 @@ * Print errors summary if mode is verbose, flush and cancel output stream. */ protected void finalize() { - if (verbose() && isErrorsSummaryEnabled()) { + if (isErrorsSummaryEnabled()) { printErrorsSummary(); } if (out != null) diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/README openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/README --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/README 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/README 2025-04-09 19:45:33.000000000 +0000 @@ -59,8 +59,6 @@ Denotation.java, TreeNodesDenotation.java RAS mode support: RASagent.java, JVMTIagent.c - JVMDI tests support: - JVMDITools.h, JVMDITools.c Short description of subdirectories: diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AODTestRunner.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AODTestRunner.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AODTestRunner.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AODTestRunner.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -68,7 +68,7 @@ protected AODRunnerArgParser argParser; protected AODTestRunner(String[] args) { - log = new Log(System.out, true); + log = new Log(System.out); argParser = createArgParser(args); } diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AbstractJarAgent.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AbstractJarAgent.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AbstractJarAgent.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/AbstractJarAgent.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -157,7 +157,7 @@ if (name == null) throw new TestBug("Agent name wasn't specified"); - log = new Log(System.out, true); + log = new Log(System.out); } /* diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/DummyTargetApplication.java 2025-04-09 19:45:33.000000000 +0000 @@ -39,7 +39,7 @@ */ public class DummyTargetApplication { - protected Log log = new Log(System.out, true); + protected Log log = new Log(System.out); protected AODTargetArgParser argParser; diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/aod/TargetApplicationWaitingAgents.java 2025-04-09 19:45:33.000000000 +0000 @@ -213,7 +213,7 @@ if (targetApplicationInitialized) throw new TestBug("TargetApplication already initialized"); - log = new Log(System.out, true); + log = new Log(System.out); argParser = createArgParser(args); diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/JVMTITest.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/JVMTITest.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/JVMTITest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/share/jvmti/JVMTITest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -87,7 +87,7 @@ AgentsAttacher attacher = new AgentsAttacher(Utils.findCurrentVMIdUsingJPS(jdkPath), agents, - new Log(System.out, true)); + new Log(System.out)); attacher.attachAgents(); } } diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace007.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace007.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace007.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace007.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -155,6 +155,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace008.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace008.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace008.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace008.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -159,6 +159,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace009.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace009.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace009.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace009.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -159,6 +159,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace010.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace010.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace010.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace010.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -177,6 +177,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace011.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace011.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace011.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace011.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -178,6 +178,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace012.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace012.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace012.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace012.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -182,6 +182,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace013.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace013.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace013.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace013.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -170,6 +170,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace014.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace014.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace014.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace014.java 2025-04-09 19:45:33.000000000 +0000 @@ -173,6 +173,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace015.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace015.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace015.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/nsk/stress/strace/strace015.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -174,6 +174,11 @@ StackTraceElement[] all; for (int i = 1; i < THRD_COUNT; i++) { all = (StackTraceElement[]) traces.get(threads[i]); + if (all == null) { + complain("No stacktrace for thread " + threads[i].getName() + + " was found in the set of all traces"); + return false; + } int k = all.length; if (count - k > 2) { complain("wrong lengths of stack traces:\n\t" diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/compiler/coverage/parentheses/Parentheses.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/compiler/coverage/parentheses/Parentheses.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/compiler/coverage/parentheses/Parentheses.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/compiler/coverage/parentheses/Parentheses.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -69,7 +69,7 @@ public void run() throws IOException, ReflectiveOperationException { - log = new Log(System.out, verbose); + log = new Log(System.out); InstructionSequence instructionSequence = null; for (int i = 0; i < iterations * stressOptions.getIterationsFactor(); i++) { diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/share/gc/HeapOOMEException.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/HeapOOMEException.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/share/gc/HeapOOMEException.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/HeapOOMEException.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package vm.share.gc; + +/** + * This class is used to distinguish between OOME in metaspace and OOME in heap when triggering class unloading. + */ +public class HeapOOMEException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public HeapOOMEException(String string) { + super(string); + } + +} diff -Nru openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/share/gc/TriggerUnloadingByFillingMetaspace.java openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/TriggerUnloadingByFillingMetaspace.java --- openjdk-17-17.0.14+7/test/hotspot/jtreg/vmTestbase/vm/share/gc/TriggerUnloadingByFillingMetaspace.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/hotspot/jtreg/vmTestbase/vm/share/gc/TriggerUnloadingByFillingMetaspace.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,6 @@ package vm.share.gc; import nsk.share.test.ExecutionController; -import metaspace.stressHierarchy.common.exceptions.GotWrongOOMEException; import nsk.share.gc.gp.classload.GeneratedClassProducer; public class TriggerUnloadingByFillingMetaspace implements @@ -50,7 +49,7 @@ generatedClassProducer.get().create(-100500); //argument is not used. } catch (Throwable oome) { if (!isInMetaspace(oome)) { - throw new GotWrongOOMEException("Got OOME in heap while triggering OOME in metaspace. Test result can't be valid."); + throw new HeapOOMEException("Got OOME in heap while triggering OOME in metaspace. Test result can't be valid."); } gotOOME = true; } diff -Nru openjdk-17-17.0.14+7/test/jdk/ProblemList.txt openjdk-17-17.0.15+6/test/jdk/ProblemList.txt --- openjdk-17-17.0.14+7/test/jdk/ProblemList.txt 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/ProblemList.txt 2025-04-09 19:45:33.000000000 +0000 @@ -136,7 +136,6 @@ java/awt/Focus/WrongKeyTypedConsumedTest/WrongKeyTypedConsumedTest.java 8169096 macosx-all java/awt/event/KeyEvent/CorrectTime/CorrectTime.java 6626492 generic-all java/awt/EventQueue/6980209/bug6980209.java 8198615 macosx-all -java/awt/Frame/ExceptionOnSetExtendedStateTest/ExceptionOnSetExtendedStateTest.java 8198237 macosx-all java/awt/grab/EmbeddedFrameTest1/EmbeddedFrameTest1.java 7080150 macosx-all java/awt/event/InputEvent/EventWhenTest/EventWhenTest.java 8168646 generic-all java/awt/KeyboardFocusmanager/TypeAhead/TestDialogTypeAhead.java 8198626 macosx-all @@ -385,7 +384,7 @@ java/awt/Modal/MultipleDialogs/MultipleDialogs4Test.java 8198665 macosx-all java/awt/Modal/MultipleDialogs/MultipleDialogs5Test.java 8198665 macosx-all java/awt/Mouse/EnterExitEvents/DragWindowOutOfFrameTest.java 8177326 macosx-all -java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 8005021,8332158 macosx-all,linux-x64 +java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 8005021 macosx-all java/awt/Mouse/EnterExitEvents/FullscreenEnterEventTest.java 8051455 macosx-all java/awt/Mouse/MouseModifiersUnitTest/MouseModifiersUnitTest_Standard.java 7124407 macosx-all java/awt/Mouse/RemovedComponentMouseListener/RemovedComponentMouseListener.java 8157170 macosx-all @@ -421,36 +420,6 @@ java/awt/Modal/ToBack/ToBackNonModal3Test.java 8196441 macosx-all,linux-all java/awt/Modal/ToBack/ToBackNonModal4Test.java 8196441 macosx-all,linux-all java/awt/Modal/ToBack/ToBackNonModal5Test.java 8196441 macosx-all -java/awt/Modal/OnTop/OnTopAppModal1Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopAppModal2Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopAppModal3Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopAppModal4Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopAppModal5Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopAppModal6Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal1Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal2Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal3Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal4Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal5Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopDocModal6Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal1Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal2Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal3Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal4Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal5Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModal6Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless1Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless2Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless3Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless4Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless5Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopModeless6Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal1Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal2Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal3Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal4Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal5Test.java 8198666 macosx-all -java/awt/Modal/OnTop/OnTopTKModal6Test.java 8198666 macosx-all java/awt/List/SingleModeDeselect/SingleModeDeselect.java 8196367 windows-all java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java 8061235 macosx-all javax/print/PrintSEUmlauts/PrintSEUmlauts.java 8135174 generic-all @@ -494,6 +463,7 @@ java/awt/GridLayout/ComponentPreferredSize/ComponentPreferredSize.java 8238720,8324782 windows-all,macosx-all java/awt/GridLayout/ChangeGridSize/ChangeGridSize.java 8238720,8324782 windows-all,macosx-all java/awt/event/MouseEvent/FrameMouseEventAbsoluteCoordsTest/FrameMouseEventAbsoluteCoordsTest.java 8238720 windows-all +java/awt/List/HandlingKeyEventIfMousePressedTest.java 6848358 macosx-all,windows-all # Several tests which fail sometimes on macos11 java/awt/Window/MainKeyWindowTest/TestMainKeyWindow.java 8265985 macosx-all @@ -659,14 +629,12 @@ sun/security/smartcardio/TestMultiplePresent.java 8039280 generic-all sun/security/smartcardio/TestPresent.java 8039280 generic-all sun/security/smartcardio/TestTransmit.java 8039280 generic-all -com/sun/security/auth/callback/TextCallbackHandler/Password.java 8039280 generic-all com/sun/security/sasl/gsskerb/AuthOnly.java 8039280 generic-all com/sun/security/sasl/gsskerb/ConfSecurityLayer.java 8039280 generic-all com/sun/security/sasl/gsskerb/NoSecurityLayer.java 8039280 generic-all javax/security/auth/kerberos/KerberosHashEqualsTest.java 8039280 generic-all javax/security/auth/kerberos/KerberosTixDateTest.java 8039280 generic-all sun/security/provider/PolicyFile/GrantAllPermToExtWhenNoPolicy.java 8039280 generic-all -sun/security/provider/PolicyParser/ExtDirsChange.java 8039280 generic-all sun/security/provider/PolicyParser/PrincipalExpansionError.java 8039280 generic-all sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java 8316183 linux-ppc64le @@ -714,14 +682,11 @@ javax/swing/JTabbedPane/8007563/Test8007563.java 8051591 generic-all javax/swing/JTabbedPane/4624207/bug4624207.java 8064922 macosx-all javax/swing/SwingUtilities/TestBadBreak/TestBadBreak.java 8160720 generic-all -javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java 8194048 windows-all -javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java 8213562 linux-all javax/swing/JFileChooser/6798062/bug6798062.java 8146446 windows-all javax/swing/JComboBox/8182031/ComboPopupTest.java 8196465 linux-all,macosx-all javax/swing/JFileChooser/6738668/bug6738668.java 8194946 generic-all javax/swing/JInternalFrame/Test6325652.java 8224977 macosx-all javax/swing/JPopupMenu/4870644/bug4870644.java 8194130 macosx-all,linux-all -javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java 8065099,8208565 macosx-all,linux-all javax/swing/dnd/8139050/NativeErrorsInTableDnD.java 8202765 macosx-all,linux-all javax/swing/JEditorPane/6917744/bug6917744.java 8213124 macosx-all javax/swing/JRootPane/4670486/bug4670486.java 8042381 macosx-all @@ -844,9 +809,10 @@ java/awt/Modal/InvisibleParentTest/InvisibleParentTest.java 8172245 linux-all java/awt/print/Dialog/RestoreActiveWindowTest/RestoreActiveWindowTest.java 8185429 macosx-all java/awt/TrayIcon/DblClickActionEventTest/DblClickActionEventTest.html 8203867 macosx-all -java/awt/Frame/FrameStateTest/FrameStateTest.html 8203920 macosx-all,linux-all +java/awt/Frame/FrameStateTest/FrameStateTest.java 8203920 macosx-all,linux-all javax/swing/SwingUtilities/TestTextPosInPrint.java 8227025 windows-all java/awt/print/PrinterJob/ScaledText/ScaledText.java 8231226 macosx-all +java/awt/print/PrinterJob/PrintTextTest.java 8148334 generic-all java/awt/font/TextLayout/TestJustification.java 8250791 macosx-all java/awt/TrayIcon/DragEventSource/DragEventSource.java 8252242 macosx-all java/awt/FileDialog/DefaultFocusOwner/DefaultFocusOwner.java 7187728 macosx-all,linux-all diff -Nru openjdk-17-17.0.14+7/test/jdk/TEST.groups openjdk-17-17.0.15+6/test/jdk/TEST.groups --- openjdk-17-17.0.14+7/test/jdk/TEST.groups 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/TEST.groups 2025-04-09 19:45:33.000000000 +0000 @@ -570,14 +570,10 @@ :jdk_security_infra \ com/sun/crypto/provider/Cipher/AEAD/GCMIncrementByte4.java \ com/sun/crypto/provider/Cipher/AEAD/GCMIncrementDirect4.java \ - com/sun/security/auth/callback/TextCallbackHandler/Password.java \ com/sun/security/sasl/gsskerb/AuthOnly.java \ com/sun/security/sasl/gsskerb/ConfSecurityLayer.java \ com/sun/security/sasl/gsskerb/NoSecurityLayer.java \ sun/security/provider/PolicyFile/GrantAllPermToExtWhenNoPolicy.java \ - sun/security/provider/PolicyParser/ExtDirs.java \ - sun/security/provider/PolicyParser/ExtDirsChange.java \ - sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java \ sun/security/provider/PolicyParser/PrincipalExpansionError.java \ sun/security/smartcardio/TestChannel.java \ sun/security/smartcardio/TestConnect.java \ @@ -589,7 +585,8 @@ sun/security/smartcardio/TestMultiplePresent.java \ sun/security/smartcardio/TestPresent.java \ sun/security/smartcardio/TestTransmit.java \ - sun/security/tools/jarsigner/compatibility/Compatibility.java + sun/security/tools/jarsigner/compatibility/Compatibility.java \ + java/security/Policy/Root/Root.java jdk_core_manual_interactive = \ com/sun/jndi/dns/Test6991580.java \ @@ -601,6 +598,7 @@ jdk_security_manual_interactive = \ sun/security/tools/keytool/i18n.java \ java/security/Policy/Root/Root.java \ + com/sun/security/auth/callback/TextCallbackHandler/Password.java \ sun/security/krb5/config/native/TestDynamicStore.java # Test sets for running inside container environment diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/crypto/provider/KeyProtector/IterationCount.java openjdk-17-17.0.15+6/test/jdk/com/sun/crypto/provider/KeyProtector/IterationCount.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/crypto/provider/KeyProtector/IterationCount.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/crypto/provider/KeyProtector/IterationCount.java 2025-04-09 19:45:33.000000000 +0000 @@ -52,9 +52,6 @@ public class IterationCount { private static final String clientStr = "CLIENT"; - private static final String javaBinPath = - System.getProperty("java.home", ".") + File.separator + "bin" + - File.separator + "java"; public static void main(String[] args) throws Throwable { if (args[0].equals("HOST")) { @@ -78,22 +75,14 @@ System.out.println("TEST PASS - OK"); } - private static List getBasicCommand() { - List cmd = new ArrayList<>(); - cmd.add(javaBinPath); - cmd.add("-cp"); - cmd.add(System.getProperty("test.classes", ".")); - return cmd; - } - private static void executeCommand(List cmd, String expectedCount) throws Throwable { cmd.add("--add-opens=java.base/com.sun.crypto.provider=ALL-UNNAMED"); cmd.add(IterationCount.class.getName()); cmd.add(clientStr); cmd.add(expectedCount); - OutputAnalyzer out = ProcessTools.executeCommand( - cmd.toArray(new String[cmd.size()])); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(cmd); + OutputAnalyzer out = ProcessTools.executeCommand(pb); out.shouldHaveExitValue(0); } @@ -102,7 +91,7 @@ System.out.println("Test setting " + (setValue != null ? setValue : "nothing") + " as a System property"); - List cmd = getBasicCommand(); + List cmd = new ArrayList<>(); if (setValue != null) { cmd.add("-Djdk.jceks.iterationCount=" + setValue); } @@ -112,7 +101,7 @@ private static void testSecurity(String expectedCount, String setValue) throws Throwable { - testSecurity(expectedCount, setValue, getBasicCommand()); + testSecurity(expectedCount, setValue, new ArrayList<>()); } private static void testSecurity(String expectedCount, String setValue, @@ -140,15 +129,14 @@ " the Security one"); String systemValue = Integer.toString(30000); System.out.println("System value: " + systemValue); - List cmd = getBasicCommand(); + List cmd = new ArrayList<>(); cmd.add("-Djdk.jceks.iterationCount=" + systemValue); testSecurity(systemValue, Integer.toString(40000), cmd); } private static void writeJavaSecurityProp(String javaSecurityPath, String setValue) throws IOException { - try (FileOutputStream fos = new FileOutputStream( - new File(javaSecurityPath))) { + try (FileOutputStream fos = new FileOutputStream(javaSecurityPath)) { fos.write(("jdk.jceks.iterationCount=" + setValue).getBytes()); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/jdi/InterruptHangTest.java openjdk-17-17.0.15+6/test/jdk/com/sun/jdi/InterruptHangTest.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/jdi/InterruptHangTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/jdi/InterruptHangTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -62,8 +62,10 @@ for (int ii = 0; ii < 200; ii++) { answer++; try { - // Give other thread a chance to run - Thread.sleep(100); + // Give other thread a chance to interrupt. Normally only a very short + // sleep is needed, but we need to account for unexpected delays in + // the interrupt due to machine and network hiccups. + Thread.sleep(10*1000); } catch (InterruptedException ee) { System.out.println("Debuggee interruptee: interrupted at iteration: " + ii); diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java openjdk-17-17.0.15+6/test/jdk/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/jmx/remote/NotificationMarshalVersions/Client/Client.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,9 @@ import javax.management.remote.JMXServiceURL; public class Client { + + public static final int COUNTER_TIMEOUT_SECONDS = 60; + public static void run(String url) throws Exception { final int notifEmittedCnt = 10; final CountDownLatch counter = new CountDownLatch(notifEmittedCnt); @@ -84,8 +87,8 @@ System.out.println(); try { System.out.println("waiting for " + notifEmittedCnt + " notifications to arrive"); - if (!counter.await(30, TimeUnit.SECONDS)) { - throw new InterruptedException(); + if (!counter.await(COUNTER_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw new Error("Client: Counter await expired"); } if (duplNotification.get()) { System.out.println("ERROR: received duplicated notifications"); @@ -94,7 +97,7 @@ System.out.println("\nshutting down client"); } catch (InterruptedException e) { System.out.println("ERROR: notification processing thread interrupted"); - throw new Error("notification thread interrupted unexpectedly"); + throw new Error("notification thread interrupted unexpectedly", e); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java openjdk-17-17.0.15+6/test/jdk/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/management/ThreadMXBean/ThreadCpuTimeArray.java 2025-04-09 19:45:33.000000000 +0000 @@ -29,6 +29,7 @@ * getThreadUserTime(long[]). * @author Paul Hohensee * @requires vm.compMode != "Xcomp" + * @run main/othervm ThreadCpuTimeArray */ import java.lang.management.*; diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Password.java openjdk-17-17.0.15+6/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Password.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Password.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/security/auth/callback/TextCallbackHandler/Password.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,11 +23,23 @@ /* * @test - * @bug 6825240 + * @bug 6825240 6829785 * @summary Password.readPassword() echos the input when System.Console is null * @run main/manual Password */ +/* + * This scenario cannot be automated because util/Password.java verifies the given input stream is + * equal to the initialSystemIn. This prevents the test from providing a custom input stream. + * + * Steps to run the test: + * 1) Compile the class using the JDK version being tested: '/javac Password.java' + * 2) Run the test using the JDK version being tested: '/java -cp . Password' + * 3) Type in the first password, it should not be visible in the console + * 4) Type in the second password, it should be visible in the console + * 5) The final output line displays the entered passwords, both should be visible + */ + import com.sun.security.auth.callback.TextCallbackHandler; import javax.security.auth.callback.*; diff -Nru openjdk-17-17.0.14+7/test/jdk/com/sun/tools/attach/BasicTests.java openjdk-17-17.0.15+6/test/jdk/com/sun/tools/attach/BasicTests.java --- openjdk-17-17.0.14+7/test/jdk/com/sun/tools/attach/BasicTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/com/sun/tools/attach/BasicTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -171,6 +171,7 @@ System.out.println(" - Test: Load an agent that does not exist"); try { vm.loadAgent("SilverBullet.jar"); + throw new RuntimeException("AgentLoadException not thrown as expected!"); } catch (AgentLoadException x) { System.out.println(" - AgentLoadException thrown as expected!"); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Component/ComponentEventTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Component/ComponentEventTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Component/ComponentEventTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Component/ComponentEventTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,357 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Choice; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Label; +import java.awt.List; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Scrollbar; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; +import java.awt.event.InputEvent; +import java.lang.reflect.InvocationTargetException; + +import jdk.test.lib.Platform; + +/* + * @test + * @key headful + * @bug 8333403 + * @summary Test performs various operations to check components events are triggered properly. + * @library /test/lib + * @build jdk.test.lib.Platform + * @run main ComponentEventTest + */ +public class ComponentEventTest { + + private static final int DELAY = 500; + + private static Frame frame; + private static Robot robot; + + private static Component[] components; + + private static volatile Point centerPoint; + + private static volatile boolean componentHidden; + private static volatile boolean componentShown; + private static volatile boolean componentMoved; + private static volatile boolean componentResized; + + private static final ComponentListener componentListener = + new ComponentListener() { + + @Override + public void componentShown(ComponentEvent e) { + System.out.println("ComponentShown: " + e.getSource()); + componentShown = true; + } + + @Override + public void componentResized(ComponentEvent e) { + System.out.println("ComponentResized: " + e.getSource()); + componentResized = true; + } + + @Override + public void componentMoved(ComponentEvent e) { + System.out.println("ComponentMoved: " + e.getSource()); + componentMoved = true; + } + + @Override + public void componentHidden(ComponentEvent e) { + System.out.println("ComponentHidden: " + e.getSource()); + componentHidden = true; + } + }; + + private static void initializeGUI() { + frame = new Frame("Component Event Test"); + frame.setLayout(new FlowLayout()); + + Panel panel = new Panel(); + Button button = new Button("Button"); + Label label = new Label("Label"); + List list = new List(); + list.add("One"); + list.add("Two"); + list.add("Three"); + Choice choice = new Choice(); + choice.add("Red"); + choice.add("Orange"); + choice.add("Yellow"); + Checkbox checkbox = new Checkbox("Checkbox"); + Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 255); + TextField textfield = new TextField(15); + TextArea textarea = new TextArea(5, 15); + + components = new Component[] { panel, button, label, list, choice, + checkbox, scrollbar, textfield, textarea, frame }; + + for (int i = 0; i < components.length - 1; i++) { + components[i].addComponentListener(componentListener); + frame.add(components[i]); + } + frame.addComponentListener(componentListener); + + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + try { + robot = new Robot(); + robot.setAutoWaitForIdle(true); + + EventQueue.invokeAndWait(ComponentEventTest::initializeGUI); + robot.waitForIdle(); + robot.delay(DELAY); + + doTest(); + + System.out.println("Test PASSED"); + } finally { + EventQueue.invokeAndWait(ComponentEventTest::disposeFrame); + } + } + + private static void doTest() + throws InvocationTargetException, InterruptedException { + // Click the frame to ensure it gains focus + clickFrame(); + + robot.delay(DELAY); + + for (int i = 0; i < components.length; i++) { + for (boolean state : new boolean[] { true, false }) { + doTest(components[i], state); + } + } + + robot.delay(DELAY); + + System.out.println("Iconify frame"); + resetValues(); + testIconifyFrame(); + + System.out.println("Deiconify frame"); + resetValues(); + testDeiconifyFrame(); + } + + private static void clickFrame() + throws InvocationTargetException, InterruptedException { + EventQueue.invokeAndWait(() -> { + Point location = frame.getLocationOnScreen(); + Dimension size = frame.getSize(); + centerPoint = new Point(location.x + size.width / 2, + location.y + size.height / 2); + }); + + robot.mouseMove(centerPoint.x, centerPoint.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + private static void testIconifyFrame() + throws InvocationTargetException, InterruptedException { + EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.ICONIFIED)); + + robot.waitForIdle(); + robot.delay(DELAY); + if (componentShown || componentHidden || componentMoved + || componentResized) { + throw new RuntimeException( + "ComponentEvent triggered when frame is iconified"); + } + } + + private static void testDeiconifyFrame() + throws InvocationTargetException, InterruptedException { + EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.NORMAL)); + + robot.waitForIdle(); + robot.delay(DELAY); + + /* + * Because of the different behavior between MS Windows and other OS, we + * receive native events WM_SIZE and WM_MOVE on Windows when the frame + * state changes from iconified to normal. AWT sends these events to + * components when it receives the events from the native system. See + * JDK-6754618 for more information. + */ + + if (componentShown || componentHidden) { + throw new RuntimeException( + "FAIL: componentShown or componentHidden triggered " + + "when frame set to normal"); + } + + if (Platform.isWindows() && (!componentMoved || !componentResized)) { + throw new RuntimeException( + "FAIL: componentMoved or componentResized wasn't triggered " + + "when frame set to normal"); + } + if (!Platform.isWindows() && (componentMoved || componentResized)) { + throw new RuntimeException( + "FAIL: componentMoved or componentResized triggered " + + "when frame set to normal"); + } + } + + private static void doTest(final Component currentComponent, boolean enable) + throws InvocationTargetException, InterruptedException { + + System.out.println("Component " + currentComponent); + System.out.println(" enabled " + enable); + + EventQueue.invokeAndWait(() -> { + currentComponent.setEnabled(enable); + revalidateFrame(); + }); + + robot.delay(DELAY); + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setVisible(false); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (!componentHidden) { + throw new RuntimeException("FAIL: ComponentHidden not triggered for" + + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setVisible(false); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (componentHidden) { + throw new RuntimeException("FAIL: ComponentHidden triggered when " + + "setVisible(false) called for a hidden " + + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setVisible(true); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (!componentShown) { + throw new RuntimeException("FAIL: ComponentShown not triggered for " + + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setVisible(true); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (componentShown) { + throw new RuntimeException("FAIL: ComponentShown triggered when " + + "setVisible(true) called for a shown " + + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setLocation(currentComponent.getLocation().x + 1, + currentComponent.getLocation().y); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (!componentMoved) { + throw new RuntimeException("FAIL: ComponentMoved not triggered for " + + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setSize(currentComponent.getSize().width + 1, + currentComponent.getSize().height); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (!componentResized) { + throw new RuntimeException("FAIL: ComponentResized not triggered " + + "when size increases for " + currentComponent.getClass()); + } + + resetValues(); + EventQueue.invokeAndWait(() -> { + currentComponent.setSize(currentComponent.getSize().width - 1, + currentComponent.getSize().height); + revalidateFrame(); + }); + + robot.delay(DELAY); + if (!componentResized) { + throw new RuntimeException("FAIL: ComponentResized not triggered " + + "when size decreases for " + currentComponent.getClass()); + } + + System.out.println("\n"); + } + + private static void revalidateFrame() { + frame.invalidate(); + frame.validate(); + } + + private static void resetValues() { + componentShown = false; + componentHidden = false; + componentMoved = false; + componentResized = false; + } + + private static void disposeFrame() { + if (frame != null) { + frame.dispose(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/DefaultFrameIconTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DefaultFrameIconTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/DefaultFrameIconTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DefaultFrameIconTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.Window; +import java.util.List; + +/* + * @test + * @bug 4240766 8259023 + * @summary Frame Icon is wrong - should be Coffee Cup or Duke image icon + * @requires (os.family == "windows") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual DefaultFrameIconTest +*/ + +public class DefaultFrameIconTest { + + private static final String INSTRUCTIONS = """ + You should see a dialog and a frame. + If both have Coffee Cup or Duke image icon in the upper left corner, + the test passes, otherwise it fails. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("DefaultFrameIconTest Instructions") + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(DefaultFrameIconTest::createAndShowUI) + .positionTestUIRightRow() + .build() + .awaitAndCheck(); + } + + private static List createAndShowUI() { + Frame testFrame = new Frame("Frame DefaultFrameIconTest"); + Dialog testDialog = new Dialog(testFrame, "Dialog DefaultFrameIconTest"); + + testDialog.setSize(250, 100); + + testFrame.setSize(250, 100); + return List.of(testFrame, testDialog); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/DisposeTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DisposeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/DisposeTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/DisposeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.imageio.ImageIO; +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +/* + * @test + * @key headful + * @bug 4127271 + * @summary Tests that disposing of a Frame with MenuBar removes all traces + * of the Frame from the screen. + */ + +public class DisposeTest { + private static Frame backgroundFrame; + private static Frame testedFrame; + + private static final Rectangle backgroundFrameBounds = + new Rectangle(100, 100, 200, 200); + private static final Rectangle testedFrameBounds = + new Rectangle(150, 150, 100, 100); + + private static Robot robot; + + public static void main(String[] args) throws Exception { + robot = new Robot(); + try { + EventQueue.invokeAndWait(DisposeTest::initAndShowGui); + robot.waitForIdle(); + robot.delay(500); + EventQueue.invokeAndWait(testedFrame::dispose); + robot.waitForIdle(); + robot.delay(500); + test(); + } finally { + EventQueue.invokeAndWait(() -> { + backgroundFrame.dispose(); + testedFrame.dispose(); + }); + } + } + + private static void test() { + BufferedImage bi = robot.createScreenCapture(backgroundFrameBounds); + int redPix = Color.RED.getRGB(); + + for (int x = 0; x < bi.getWidth(); x++) { + for (int y = 0; y < bi.getHeight(); y++) { + if (bi.getRGB(x, y) != redPix) { + try { + ImageIO.write(bi, "png", + new File("failure.png")); + } catch (IOException ignored) {} + throw new RuntimeException("Test failed"); + } + } + } + } + + private static void initAndShowGui() { + backgroundFrame = new Frame("DisposeTest background"); + backgroundFrame.setUndecorated(true); + backgroundFrame.setBackground(Color.RED); + backgroundFrame.setBounds(backgroundFrameBounds); + backgroundFrame.setVisible(true); + + testedFrame = new UglyFrame(); + } + + static class UglyFrame extends Frame { + public UglyFrame() { + super("DisposeTest"); + MenuBar mb = new MenuBar(); + Menu m = new Menu("menu"); + mb.add(m); + setMenuBar(mb); + setBounds(testedFrameBounds); + setVisible(true); + } + } +} + diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameDialogMixedTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameDialogMixedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameDialogMixedTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameDialogMixedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.Color; +import java.awt.Dialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Point; + +/* + * @test + * @bug 4340727 + * @summary Tests that undecorated property is set correctly + * when Frames and Dialogs are mixed. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FrameDialogMixedTest + */ + +public class FrameDialogMixedTest { + private static final int SIZE = 100; + + private static final String INSTRUCTIONS = """ + When the test starts, a RED UNDECORATED Frame is seen. + Click on "Create Dialog" button, you should see a GREEN UNDECORATED Dialog. + If both the frame and the dialog are undecorated press PASS otherwise FAIL."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Undecorated Frame & Dialog Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(FrameDialogMixedTest::createUI) + .build() + .awaitAndCheck(); + } + + private static Frame createUI() { + Frame frame = new Frame("Undecorated Frame"); + frame.setSize(SIZE, SIZE); + frame.setBackground(Color.RED); + frame.setUndecorated(true); + frame.setLayout(new FlowLayout(FlowLayout.CENTER)); + + Button button = new Button("Create Dialog"); + button.addActionListener(e -> { + Dialog dialog = new Dialog(frame); + Point frameLoc = frame.getLocationOnScreen(); + dialog.setBounds(frameLoc.x + frame.getSize().width + 5, + frameLoc.y, + SIZE, SIZE); + dialog.setBackground(Color.GREEN); + dialog.setUndecorated(true); + dialog.setVisible(true); + }); + + frame.add(button); + return frame; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FramePaintTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FramePaintTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FramePaintTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FramePaintTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Graphics; + +/* + * @test + * @bug 4023385 + * @summary resizing a frame causes too many repaints + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FramePaintTest +*/ + +public class FramePaintTest { + private static final String INSTRUCTIONS = """ + You should see a Frame titled "Repaint Test", filled with colored blocks. + + Resize the frame several times, both inward as well as outward. + + The blocks should move to fill the window without any flashes or + glitches which ensures that repaint is not done excessively + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("FramePaintTest Instructions") + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(ResizeLW::new) + .build() + .awaitAndCheck(); + } + + static class ResizeLW extends Frame { + + public ResizeLW() { + super("Repaint Test"); + setBackground(Color.red); + setLayout(new FlowLayout()); + setSize(300, 300); + + for (int i = 0; i < 10; i++) { + add(new ColorComp(Color.blue)); + add(new ColorComp(Color.green)); + } + } + + private static class ColorComp extends Component { + public ColorComp(Color c) { + super(); + setBackground(c); + } + + public void paint(Graphics g) { + g.setColor(getBackground()); + g.fillRect(0, 0, getWidth(), getHeight()); + } + + public Dimension getPreferredSize() { + return new Dimension(50, 50); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.html openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ - - - - - FrameStateTest - - - -

    FrameStateTest
    Bug ID: 4157271

    -

    This test checks that when setState(Frame.ICONIFIED) is called before - setVisible(true) the Frame is shown in the proper iconified state. - The problem was that it did not honor the initial iconic state, but - instead was shown in the NORMAL state.

    -

    See the dialog box (usually in upper left corner) for instructions

    - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/FrameStateTest/FrameStateTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,102 +21,131 @@ * questions. */ -/* - test - @bug 4157271 - @summary Checks that when a Frame is created it honors the state it - was set to. The bug was that if setState(Frame.ICONIFIED) was - called before setVisible(true) the Frame would be shown in NORMAL - state instead of ICONIFIED. - @author JTG East Team: area=awt.Frame - @run applet/manual=yesno FrameStateTest.html -*/ +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Deque; +import javax.swing.JPanel; +import javax.swing.Timer; -/** - * FrameStateTest.java - * - * summary: Checks that when setState(Frame.ICONIFIED) is called before - * setVisible(true) the Frame is shown in the proper iconified state. - * The problem was that it did not honor the initial iconic state, but - * instead was shown in the NORMAL state. +/* + * @test + * @bug 4157271 + * @summary Checks that when a Frame is created it honors the state it + * was set to. The bug was that if setState(Frame.ICONIFIED) was + * called before setVisible(true) the Frame would be shown in NORMAL + * state instead of ICONIFIED. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FrameStateTest */ -import java.awt.event.*; -import java.awt.*; -import java.lang.*; -import java.applet.Applet; - - -public class FrameStateTest extends Applet implements ActionListener, ItemListener{ - - Button btnCreate = new Button("Create Frame"); - Button btnDispose = new Button("Dispose Frame"); - CheckboxGroup cbgState = new CheckboxGroup(); - CheckboxGroup cbgResize = new CheckboxGroup(); - Checkbox cbIconState = new Checkbox("Frame state ICONIFIED",cbgState,false); - Checkbox cbNormState = new Checkbox("Frame state NORMAL",cbgState,true); - Checkbox cbNonResize = new Checkbox("Frame Nonresizable",cbgResize,false); - Checkbox cbResize = new Checkbox("Frame Resizable",cbgResize,true); - int iState = 0; - boolean bResize = true; - CreateFrame icontst; - - public void init() { - this.setLayout (new BorderLayout ()); - - String[] instructions = - { - "Steps to try to reproduce this problem:", - "When this test is run an Applet Viewer window will display. In the", - "Applet Viewer window select the different options for the Frame (i.e.", - "{Normal, Non-resizalbe}, {Normal, Resizable}, {Iconified, Resizable},", - "{Iconified, Non-resizalbe}). After chosing the Frame's state click the", - "Create Frame button. After the Frame (Frame State Test (Window2)) comes", - "up make sure the proper behavior occurred (Frame shown in proper state).", - "Click the Dispose button to close the Frame. Do the above steps for all", - "the different Frame state combinations available. If you observe the", - "proper behavior the test has passed, Press the Pass button. Otherwise", - "the test has failed, Press the Fail button.", - "Note: In Frame State Test (Window2) you can also chose the different", - "buttons to see different Frame behavior. An example of a problem that", - "has been seen, With the Frame nonresizable you can not iconify the Frame." - }; - Sysout.createDialogWithInstructions( instructions ); - - btnDispose.setEnabled(false); - add(btnCreate, BorderLayout.NORTH); - add(btnDispose, BorderLayout.SOUTH); - - Panel p = new Panel(new GridLayout(0,1)); - p.add(cbIconState); - p.add(cbResize); - add(p, BorderLayout.WEST); - - p = new Panel(new GridLayout(0,1)); - p.add(cbNormState); - p.add(cbNonResize); - add(p, BorderLayout.EAST); - - // Add Listeners - btnDispose.addActionListener(this); - btnCreate.addActionListener(this); - cbNormState.addItemListener(this); - cbResize.addItemListener(this); - cbIconState.addItemListener(this); - cbNonResize.addItemListener(this); +public class FrameStateTest implements ActionListener { - resize(600, 200); + private static final String INSTRUCTIONS = """ +

    + This test checks that when setState(Frame.ICONIFIED) is called before + setVisible(true) the Frame is shown in the proper iconified state. + The problem was that it did not honor the initial iconic state, but + instead was shown in the NORMAL state. +


    + Steps to try to reproduce this problem: +

    + Select the different options for the Frame: +

      +
    • {Normal, Non-resizable}
    • +
    • {Normal, Resizable}
    • +
    • {Iconified, Resizable}
    • +
    • {Iconified, Non-resizable}
    • +
    + After choosing the Frame's state click the + Create Frame button.
    + After the Frame (Frame State Test (Window2)) comes up make sure the + proper behavior occurred (Frame shown in proper state).
    + Click the Dispose button to close the Frame.
    +


    + + Do the above steps for all the different Frame state combinations + available.
    + For "Hide, Iconify and Show" case, the frame is hidden then iconified + hence Window2 is not seen on-screen when shown as the frame is still + in the ICONIFIED state. Window2 is visible on-screen when it is restored + to NORMAL state as observed with "Hide, Iconify, Show and Restore" case. +

    + + If you observe the proper behavior for all the combinations, + press PASS else FAIL.
    +

    + Note: In Frame State Test (Window2) you can also chose the different + buttons to see different Frame behavior.
    An example of a problem that + has been seen, with the Frame non-resizable you can not iconify the Frame. +

    + + + """; + + public static final int DELAY = 1000; + + Button btnCreate = new Button("Create Frame"); + Button btnDispose = new Button("Dispose Frame"); + CheckboxGroup cbgState = new CheckboxGroup(); + CheckboxGroup cbgResize = new CheckboxGroup(); + Checkbox cbIconState = new Checkbox("Frame State ICONIFIED", cbgState, true); + Checkbox cbNormState = new Checkbox("Frame State NORMAL", cbgState, false); + Checkbox cbNonResize = new Checkbox("Frame Non-Resizable", cbgResize, false); + Checkbox cbResize = new Checkbox("Frame Resizable", cbgResize, true); + + CreateFrame icontst; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("Frame State and Size Test Instructions") + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .rows(27) + .columns(70) + .logArea(6) + .splitUIBottom(() -> new FrameStateTest().createPanel()) + .build() + .awaitAndCheck(); + } + + public JPanel createPanel() { + JPanel panel = new JPanel(); + panel.setLayout(new GridLayout(0, 3)); + btnDispose.setEnabled(false); + + panel.add(cbIconState); + panel.add(cbResize); + panel.add(btnCreate); + panel.add(cbNormState); + panel.add(cbNonResize); + panel.add(btnDispose); - }//End init() - - public void actionPerformed(ActionEvent evt) { + btnDispose.addActionListener(this); + btnCreate.addActionListener(this); + return panel; + } + public void actionPerformed(ActionEvent evt) { if (evt.getSource() == btnCreate) { btnCreate.setEnabled(false); btnDispose.setEnabled(true); - icontst = new CreateFrame(iState, bResize); - icontst.show(); + icontst = new CreateFrame(cbIconState.getState(), cbResize.getState()); + icontst.setVisible(true); } else if (evt.getSource() == btnDispose) { btnCreate.setEnabled(true); btnDispose.setEnabled(false); @@ -124,336 +153,172 @@ } } - public void itemStateChanged(ItemEvent evt) { + static class CreateFrame extends Frame + implements ActionListener, WindowListener { - if (cbNormState.getState()) iState = 0; - if (cbIconState.getState()) iState = 1; - if (cbResize.getState()) bResize = true; - if (cbNonResize.getState()) bResize = false; + Button b1, b2, b3, b4, b5, b6, b7; + boolean isResizable; + String name = "Frame State Test"; + + CreateFrame(boolean iconified, boolean resizable) { + setTitle("Test Window (Window 2)"); + + isResizable = resizable; + + PassFailJFrame.log("CREATING FRAME - Initially " + + ((iconified) ? "ICONIFIED" : "NORMAL (NON-ICONIFIED)") + " and " + + ((isResizable) ? "RESIZABLE" : "NON-RESIZABLE")); + + setLayout(new FlowLayout()); + add(b1 = new Button("Resizable")); + add(b2 = new Button("Resize")); + add(b3 = new Button("Iconify")); + add(b4 = new Button("Iconify and Restore")); + add(b5 = new Button("Hide and Show")); + add(b6 = new Button("Hide, Iconify and Show")); + add(b7 = new Button("Hide, Iconify, Show and Restore")); + b1.addActionListener(this); + b2.addActionListener(this); + b3.addActionListener(this); + b4.addActionListener(this); + b5.addActionListener(this); + b6.addActionListener(this); + b7.addActionListener(this); + addWindowListener(this); + + setBounds(100, 2, 300, 200); + setState(iconified ? Frame.ICONIFIED : Frame.NORMAL); + setResizable(isResizable); + setVisible(true); + } - } + /** + * Calls all runnables on EDT with a {@code DELAY} delay before each run. + * @param runnables to run + */ + private static void delayedActions(Runnable... runnables) { + setTimer(new ArrayDeque<>(Arrays.asList(runnables))); + } -}// class FrameStateTest + private static void setTimer(Deque deque) { + if (deque == null || deque.isEmpty()) return; + Timer timer = new Timer(DELAY, e -> { + deque.pop().run(); + setTimer(deque); + }); + timer.setRepeats(false); + timer.start(); + } -class CreateFrame extends Frame implements ActionListener , WindowListener { + public void actionPerformed(ActionEvent e) { + if (e.getSource() == b2) { + Rectangle r = this.getBounds(); + r.width += 10; + stateLog(" - button pressed - setting bounds on Frame to: " + r); + setBounds(r); + validate(); + } else if (e.getSource() == b1) { + isResizable = !isResizable; + stateLog(" - button pressed - setting Resizable to: " + isResizable); + ((Frame) (b1.getParent())).setResizable(isResizable); + } else if (e.getSource() == b3) { + stateLog(" - button pressed - setting Iconic: "); + ((Frame) (b1.getParent())).setState(Frame.ICONIFIED); + stateLog(); + } else if (e.getSource() == b4) { + stateLog(" - button pressed - setting Iconic: "); + ((Frame) (b1.getParent())).setState(Frame.ICONIFIED); + stateLog(); + delayedActions(() -> { + stateLog(" - now restoring: "); + ((Frame) (b1.getParent())).setState(Frame.NORMAL); + stateLog(); + }); + } else if (e.getSource() == b5) { + stateLog(" - button pressed - hiding : "); + b1.getParent().setVisible(false); + stateLog(); + delayedActions(() -> { + stateLog(" - now reshowing: "); + b1.getParent().setVisible(true); + stateLog(); + }); + } else if (e.getSource() == b6) { + stateLog(" - button pressed - hiding : "); + b1.getParent().setVisible(false); + stateLog(); + delayedActions( + () -> { + stateLog(" - setting Iconic: "); + ((Frame) (b1.getParent())).setState(Frame.ICONIFIED); + }, + () -> { + stateLog(" - now reshowing: "); + b1.getParent().setVisible(true); + stateLog(); + } + ); + } else if (e.getSource() == b7) { + stateLog(" - button pressed - hiding : "); + b1.getParent().setVisible(false); + stateLog(); + + delayedActions( + () -> { + stateLog(" - setting Iconic: "); + ((Frame) (b1.getParent())).setState(Frame.ICONIFIED); + }, + () -> { + stateLog(" - now reshowing: "); + b1.getParent().setVisible(true); + stateLog(); + }, + () -> { + stateLog(" - now restoring: "); + ((Frame) (b1.getParent())).setState(Frame.NORMAL); + stateLog(); + } + ); + } + } - static int e=0; - static int u=0; - static int p=0; - static int i=0; - static int v=0; + public void windowActivated(WindowEvent e) { + stateLog("Activated"); + } - Button b1, b2, b3, b4, b5, b6, b7; - boolean resizable = true; - boolean iconic = false; - String name = "Frame State Test"; + public void windowClosed(WindowEvent e) { + stateLog("Closed"); + } - CreateFrame (int iFrameState, boolean bFrameResizable) { + public void windowClosing(WindowEvent e) { + ((Window) (e.getSource())).dispose(); + stateLog("Closing"); + } - setTitle("Frame State Test (Window 2)"); + public void windowDeactivated(WindowEvent e) { + stateLog("Deactivated"); + } - if (iFrameState == 1) { - iconic = true; - } + public void windowDeiconified(WindowEvent e) { + stateLog("Deiconified"); + } - if (!(bFrameResizable)) { - resizable = false; - } + public void windowIconified(WindowEvent e) { + stateLog("Iconified"); + } - System.out.println("CREATING FRAME - Initially "+ - ((iconic) ? "ICONIFIED" : "NORMAL (NON-ICONIFIED)") + " and " + - ((resizable) ? "RESIZABLE" : "NON-RESIZABLE") ); - - Sysout.println("CREATING FRAME - Initially "+ - ((iconic) ? "ICONIFIED" : "NORMAL (NON-ICONIFIED)") + " and " + - ((resizable) ? "RESIZABLE" : "NON-RESIZABLE") ); - - setLayout(new FlowLayout() ); - b1 = new Button("resizable"); - add(b1); - b2 = new Button("resize"); - add(b2); - b3 = new Button("iconify"); - add(b3); - b4 = new Button("iconify and restore"); - add(b4); - b5 = new Button("hide and show"); - add(b5); - b6 = new Button("hide, iconify and show"); - add(b6); - b7 = new Button("hide, iconify, show, and restore"); - add(b7); - b1.addActionListener(this); - b2.addActionListener(this); - b3.addActionListener(this); - b4.addActionListener(this); - b5.addActionListener(this); - b6.addActionListener(this); - b7.addActionListener(this); - addWindowListener(this); - - setBounds(100,2,200, 200); - setState(iconic ? Frame.ICONIFIED: Frame.NORMAL); - setResizable(resizable); - pack(); - setVisible(true); - - } - - public void actionPerformed ( ActionEvent e ) - { - if ( e.getSource() == b2 ) { - Rectangle r = this.getBounds(); - r.width += 10; - System.out.println(" - button pressed - setting bounds on Frame to: "+r); - setBounds(r); - validate(); - } else if ( e.getSource() == b1 ) { - resizable = !resizable; - System.out.println(" - button pressed - setting Resizable to: "+resizable); - ((Frame)(b1.getParent())).setResizable(resizable); - } else if ( e.getSource() == b3 ) { - System.out.println(" - button pressed - setting Iconic: "); - dolog(); - ((Frame)(b1.getParent())).setState(Frame.ICONIFIED); - dolog(); - } else if ( e.getSource() == b4 ) { - System.out.println(" - button pressed - setting Iconic: "); - dolog(); - ((Frame)(b1.getParent())).setState(Frame.ICONIFIED); - dolog(); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - now restoring: "); - ((Frame)(b1.getParent())).setState(Frame.NORMAL); - dolog(); - } else if ( e.getSource() == b5 ) { - System.out.println(" - button pressed - hiding : "); - dolog(); - ((Frame)(b1.getParent())).setVisible(false); - dolog(); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - now reshowing: "); - ((Frame)(b1.getParent())).setVisible(true); - dolog(); - } else if ( e.getSource() == b6 ) { - System.out.println(" - button pressed - hiding : "); - dolog(); - ((Frame)(b1.getParent())).setVisible(false); - dolog(); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - setting Iconic: "); - dolog(); - ((Frame)(b1.getParent())).setState(Frame.ICONIFIED); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - now reshowing: "); - ((Frame)(b1.getParent())).setVisible(true); - dolog(); - } else if ( e.getSource() == b7 ) { - System.out.println(" - button pressed - hiding : "); - dolog(); - ((Frame)(b1.getParent())).setVisible(false); - dolog(); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - setting Iconic: "); - dolog(); - ((Frame)(b1.getParent())).setState(Frame.ICONIFIED); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - now reshowing: "); - ((Frame)(b1.getParent())).setVisible(true); - dolog(); - try { - Thread.sleep(1000); - } catch (Exception ex) {}; - System.out.println(" - now restoring: "); - ((Frame)(b1.getParent())).setState(Frame.NORMAL); - dolog(); - } - } + public void windowOpened(WindowEvent e) { + stateLog("Opened"); + } - public void windowActivated(WindowEvent e) { - System.out.println(name + " Activated"); - dolog(); - } - public void windowClosed(WindowEvent e) { - System.out.println(name + " Closed"); - dolog(); - } - public void windowClosing(WindowEvent e) { - ((Window)(e.getSource())).dispose(); - System.out.println(name + " Closing"); - dolog(); - } - public void windowDeactivated(WindowEvent e) { - System.out.println(name + " Deactivated"); - dolog(); - } - public void windowDeiconified(WindowEvent e) { - System.out.println(name + " Deiconified"); - dolog(); - } - public void windowIconified(WindowEvent e) { - System.out.println(name + " Iconified"); - dolog(); - } - public void windowOpened(WindowEvent e) { - System.out.println(name + " Opened"); - dolog(); - } + public void stateLog(String message) { + PassFailJFrame + .log("[Current State = %d] %s %s".formatted(getState(), name, message)); + } - public void dolog() { - System.out.println(" getState returns: "+getState()); + public void stateLog() { + PassFailJFrame.log("[Current State = " + getState() + "]"); + } } } - -// }// class FrameStateTest - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog - { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - int scrollNone = TextArea.SCROLLBARS_NONE; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 10, maxStringLength, scrollBoth ); - add("South", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MaximizeUndecoratedTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MaximizeUndecoratedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MaximizeUndecoratedTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MaximizeUndecoratedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.stream.Stream; +import javax.imageio.ImageIO; + +import jtreg.SkippedException; + +/* + * @test + * @key headful + * @bug 4862945 + * @summary Undecorated frames miss certain mwm functions in the mwm hints. + * @library /test/lib + * @build jtreg.SkippedException + * @run main MaximizeUndecoratedTest + */ + +public class MaximizeUndecoratedTest { + private static final int SIZE = 300; + private static final int OFFSET = 5; + + private static Frame frame; + private static Robot robot; + + private static volatile Dimension screenSize; + private static volatile Rectangle maxBounds; + + public static void main(String[] args) throws Exception { + if (!Toolkit.getDefaultToolkit() + .isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { + throw new SkippedException("Test is not applicable as" + + " the Window manager does not support MAXIMIZATION"); + } + + try { + robot = new Robot(); + + EventQueue.invokeAndWait(MaximizeUndecoratedTest::createUI); + robot.waitForIdle(); + robot.delay(1000); + + EventQueue.invokeAndWait(() -> { + screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getMaximumWindowBounds(); + System.out.println("Maximum Window Bounds: " + maxBounds); + frame.setExtendedState(Frame.MAXIMIZED_BOTH); + }); + robot.waitForIdle(); + robot.delay(500); + + // Colors sampled at top-left, top-right, bottom-right & bottom-left + // corners of maximized frame. + Point[] points = new Point[] { + new Point(maxBounds.x + OFFSET, maxBounds.y + OFFSET), + new Point(maxBounds.width - OFFSET, maxBounds.y + OFFSET), + new Point(maxBounds.width - OFFSET, maxBounds.height - OFFSET), + new Point(maxBounds.x + OFFSET, maxBounds.height - OFFSET) + }; + + if (!Stream.of(points) + .map(p -> robot.getPixelColor(p.x, p.y)) + .allMatch(c -> c.equals(Color.GREEN))) { + saveScreenCapture(); + throw new RuntimeException("Test Failed !! Frame not maximized."); + } + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.setExtendedState(Frame.NORMAL); + frame.dispose(); + } + }); + } + } + + private static void createUI() { + frame = new Frame("Test Maximization of Frame"); + frame.setSize(SIZE, SIZE); + frame.setBackground(Color.GREEN); + frame.setResizable(true); + frame.setUndecorated(true); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void saveScreenCapture() { + BufferedImage image = robot.createScreenCapture(new Rectangle(new Point(), + screenSize)); + try { + ImageIO.write(image, "png", new File("MaximizedFrame.png")); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MenuCrash.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MenuCrash.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MenuCrash.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MenuCrash.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,168 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.CheckboxMenuItem; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.TextField; +import java.awt.Window; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.List; + +/* + * @test + * @bug 4133279 + * @summary Clicking in menu in inactive frame crashes application + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MenuCrash + */ +public class MenuCrash { + + private static final String INSTRUCTIONS = """ + Two frames will appear, alternate between frames by clicking on the + menubar of the currently deactivated frame and verify no crash occurs. + + Try mousing around the menus and choosing various items to see the menu + item name reflected in the text field. Note that CheckBoxMenuItems do + not fire action events so the check menu item (Item 03) will not change + the field. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("MenuCrash Instructions") + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(MenuCrash::createAndShowUI) + .positionTestUIRightRow() + .build() + .awaitAndCheck(); + } + + + private static List createAndShowUI() { + Frame frame1 = new MenuFrame("Frame 1 MenuCrash"); + Frame frame2 = new MenuFrame("Frame 2 MenuCrash"); + + frame1.setSize(300, 200); + frame2.setSize(300, 200); + + frame1.validate(); + frame2.validate(); + + return List.of(frame1, frame2); + } + + static class MenuFrame extends Frame { + private final TextField field; + + MenuFrame(String name) { + super(name); + setLayout(new FlowLayout()); + + Button removeMenus = new Button("Remove Menus"); + removeMenus.addActionListener(ev -> remove(getMenuBar())); + + Button addMenus = new Button("Add Menus"); + addMenus.addActionListener(ev -> setupMenus()); + + add(removeMenus); + add(addMenus); + field = new TextField(20); + add(field); + + addWindowListener( + new WindowAdapter() { + public void windowActivated(WindowEvent e) { + setupMenus(); + } + } + ); + + addComponentListener( + new ComponentAdapter() { + public void componentResized(ComponentEvent e) { + System.out.println(MenuFrame.this); + } + } + ); + + pack(); + } + + private void addMenuListeners() { + MenuBar menuBar = getMenuBar(); + + for (int nMenu = 0; nMenu < menuBar.getMenuCount(); nMenu++) { + Menu menu = menuBar.getMenu(nMenu); + for (int nMenuItem = 0; nMenuItem < menu.getItemCount(); nMenuItem++) { + MenuItem item = menu.getItem(nMenuItem); + item.addActionListener(ev -> field.setText(ev.getActionCommand())); + } + } + } + + private void setupMenus() { + MenuItem miSetLabel = new MenuItem("Item 01"); + MenuItem miSetEnabled = new MenuItem("Item 02"); + CheckboxMenuItem miSetState = new CheckboxMenuItem("Item 03"); + MenuItem miAdded = new MenuItem("Item 04 Added"); + + MenuBar menuBar = new MenuBar(); + Menu menu1 = new Menu("Menu 01"); + menu1.add(miSetLabel); + menu1.add(miSetEnabled); + menu1.add(miSetState); + menuBar.add(menu1); + setMenuBar(menuBar); + + // now that the peers are created, screw + // around with the menu items + miSetLabel.setLabel("Menu 01 - SetLabel"); + miSetEnabled.setEnabled(false); + miSetState.setState(true); + menu1.add(miAdded); + menu1.remove(miAdded); + menu1.addSeparator(); + menu1.add(miAdded); + + Menu menu2 = new Menu("Menu 02"); + menuBar.add(menu2); + menuBar.remove(menu2); + menuBar.add(menu2); + menu2.add(new MenuItem("Foo")); + menu1.setLabel("Menu Number 1"); + menu2.setLabel("Menu Number 2"); + + addMenuListeners(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MinimizeUndecoratedTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MinimizeUndecoratedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Frame/MinimizeUndecoratedTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Frame/MinimizeUndecoratedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.imageio.ImageIO; + +import jtreg.SkippedException; + +/* + * @test + * @key headful + * @bug 6251941 + * @summary Undecorated frames should be minimizable. + * @library /test/lib + * @build jtreg.SkippedException + * @run main MinimizeUndecoratedTest + */ + +public class MinimizeUndecoratedTest { + private static final int SIZE = 300; + private static final CountDownLatch isMinimized = new CountDownLatch(1); + + private static Frame frame; + private static Robot robot; + + private static volatile Point frameLoc; + + public static void main(String[] args) throws Exception { + if (!Toolkit.getDefaultToolkit() + .isFrameStateSupported(Frame.ICONIFIED)) { + throw new SkippedException("Test is not applicable as" + + " the Window manager does not support MINIMIZATION"); + } + + try { + robot = new Robot(); + EventQueue.invokeAndWait(MinimizeUndecoratedTest::createUI); + robot.waitForIdle(); + robot.delay(1000); + + EventQueue.invokeAndWait(() -> frameLoc = frame.getLocationOnScreen()); + + Color beforeColor = robot.getPixelColor(frameLoc.x + SIZE / 2, + frameLoc.y + SIZE / 2); + + EventQueue.invokeAndWait(() -> frame.setExtendedState(Frame.ICONIFIED)); + robot.waitForIdle(); + robot.delay(500); + + if (!isMinimized.await(8, TimeUnit.SECONDS)) { + throw new RuntimeException("Window iconified event not received."); + } + + EventQueue.invokeAndWait(() -> System.out.println("Frame state: " + + frame.getExtendedState())); + Color afterColor = robot.getPixelColor(frameLoc.x + SIZE / 2, + frameLoc.y + SIZE / 2); + + if (beforeColor.equals(afterColor)) { + saveScreenCapture(); + throw new RuntimeException("Color before & after minimization : " + + beforeColor + " vs " + afterColor + "\n" + + "Test Failed !! Frame not minimized."); + } + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.setExtendedState(Frame.NORMAL); + frame.dispose(); + } + }); + } + } + + private static void createUI() { + frame = new Frame("Test Minimization of Frame"); + frame.setSize(SIZE, SIZE); + frame.setBackground(Color.GREEN); + frame.setResizable(true); + frame.setUndecorated(true); + frame.addWindowStateListener(new WindowAdapter() { + @Override + public void windowStateChanged(WindowEvent e) { + if (e.getNewState() == Frame.ICONIFIED) { + System.out.println("Window iconified event received."); + isMinimized.countDown(); + } + } + }); + + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void saveScreenCapture() { + Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + BufferedImage image = robot.createScreenCapture(new Rectangle(new Point(), + screenSize)); + try { + ImageIO.write(image, "png", new File("MinimizedFrame.png")); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/FullScreen/SetFullScreenTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/FullScreen/SetFullScreenTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/FullScreen/SetFullScreenTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/FullScreen/SetFullScreenTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Frame; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Robot; +import jtreg.SkippedException; + +import static java.awt.EventQueue.invokeAndWait; + +/* + * @test + * @key headful + * @bug 8312518 + * @library /test/lib + * @summary Setting fullscreen window using setFullScreenWindow() shows up + * as black screen on newer macOS versions (13 & 14). + */ + +public class SetFullScreenTest { + private static Frame frame; + private static GraphicsDevice gd; + private static Robot robot; + private static volatile int width; + private static volatile int height; + + public static void main(String[] args) throws Exception { + try { + robot = new Robot(); + invokeAndWait(() -> { + gd = GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice(); + if (!gd.isFullScreenSupported()) { + throw new SkippedException("Full Screen mode not supported"); + } + }); + + invokeAndWait(() -> { + frame = new Frame("Test FullScreen mode"); + frame.setBackground(Color.RED); + frame.setSize(100, 100); + frame.setLocation(10, 10); + frame.setVisible(true); + }); + robot.delay(1000); + + invokeAndWait(() -> gd.setFullScreenWindow(frame)); + robot.waitForIdle(); + robot.delay(300); + + invokeAndWait(() -> { + width = gd.getFullScreenWindow().getWidth(); + height = gd.getFullScreenWindow().getHeight(); + }); + + if (!robot.getPixelColor(width / 2, height / 2).equals(Color.RED)) { + System.err.println("Actual color: " + robot.getPixelColor(width / 2, height / 2) + + " Expected color: " + Color.RED); + throw new RuntimeException("Test Failed! Window not in full screen mode"); + } + } finally { + if (frame != null) { + frame.dispose(); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Graphics2D/ScaledTransform/ScaledTransform.java openjdk-17-17.0.15+6/test/jdk/java/awt/Graphics2D/ScaledTransform/ScaledTransform.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Graphics2D/ScaledTransform/ScaledTransform.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Graphics2D/ScaledTransform/ScaledTransform.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,7 @@ * questions. */ import java.awt.Dialog; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; @@ -29,63 +30,93 @@ import java.awt.GraphicsEnvironment; import java.awt.Panel; import java.awt.geom.AffineTransform; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /* * @test * @bug 8069361 * @key headful * @summary SunGraphics2D.getDefaultTransform() does not include scale factor - * @author Alexander Scherbatiy - * @run main ScaledTransform + * @run main/timeout=300 ScaledTransform */ public class ScaledTransform { - private static volatile boolean passed = false; + private static volatile CountDownLatch painted; + private static volatile boolean passed; + private static volatile Dialog dialog; + private static volatile long startTime; + private static volatile long endTime; - public static void main(String[] args) { + public static void main(String[] args) throws Exception { GraphicsEnvironment ge = GraphicsEnvironment. getLocalGraphicsEnvironment(); - if (ge.isHeadlessInstance()) { - return; - } - for (GraphicsDevice gd : ge.getScreenDevices()) { - for (GraphicsConfiguration gc : gd.getConfigurations()) { - testScaleFactor(gc); + System.out.println("Screen = " + gd); + test(gd.getDefaultConfiguration()); + /* Don't want to run too long. Test the default and up to 10 more */ + GraphicsConfiguration[] configs = gd.getConfigurations(); + for (int c = 0; c < configs.length && c < 10; c++) { + test(configs[c]); } } } - private static void testScaleFactor(final GraphicsConfiguration gc) { - final Dialog dialog = new Dialog((Frame) null, "Test", true, gc); - + static void test(GraphicsConfiguration gc) throws Exception { try { - dialog.setSize(100, 100); - Panel panel = new Panel() { - - @Override - public void paint(Graphics g) { - if (g instanceof Graphics2D) { - AffineTransform gcTx = gc.getDefaultTransform(); - AffineTransform gTx - = ((Graphics2D) g).getTransform(); - passed = gcTx.getScaleX() == gTx.getScaleX() - && gcTx.getScaleY() == gTx.getScaleY(); - } else { - passed = true; - } - dialog.setVisible(false); - } - }; - dialog.add(panel); - dialog.setVisible(true); - + /* reset vars for each run */ + passed = false; + dialog = null; + painted = new CountDownLatch(1); + EventQueue.invokeLater(() -> showDialog(gc)); + startTime = System.currentTimeMillis(); + endTime = startTime; + if (!painted.await(5, TimeUnit.SECONDS)) { + throw new RuntimeException("Panel is not painted!"); + } + System.out.println("Time to paint = " + (endTime - startTime) + "ms."); if (!passed) { throw new RuntimeException("Transform is not scaled!"); } } finally { - dialog.dispose(); + EventQueue.invokeAndWait(() -> disposeDialog()); } } + + private static void showDialog(final GraphicsConfiguration gc) { + System.out.println("Creating dialog for gc=" + gc + " with tx=" + gc.getDefaultTransform()); + dialog = new Dialog((Frame) null, "ScaledTransform", true, gc); + dialog.setSize(300, 100); + + Panel panel = new Panel() { + + @Override + public void paint(Graphics g) { + System.out.println("Painting panel"); + if (g instanceof Graphics2D g2d) { + AffineTransform gcTx = gc.getDefaultTransform(); + AffineTransform gTx = g2d.getTransform(); + System.out.println("GTX = " + gTx); + passed = (gcTx.getScaleX() == gTx.getScaleX()) && + (gcTx.getScaleY() == gTx.getScaleY()); + } else { + passed = true; + } + endTime = System.currentTimeMillis(); + painted.countDown(); + System.out.println("Painted panel"); + } + }; + dialog.add(panel); + dialog.setVisible(true); + } + + private static void disposeDialog() { + if (dialog != null) { + System.out.println("Disposing dialog"); + dialog.setVisible(false); + dialog.dispose(); + } + } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/GraphicsConfiguration/NonDefaultGC.java openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/NonDefaultGC.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/GraphicsConfiguration/NonDefaultGC.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/NonDefaultGC.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4131642 + * @summary This test shows the ability to create Frames, Windows + * and Canvases with a GraphicsConfiguration. The test should show a number + * of windows with RGB stripes in according to the number of the + * GraphicsConfigurations for each screen. It also displays the size of + * the screen and the GraphicsConfiguration.toString(). + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual NonDefaultGC + */ + +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +public class NonDefaultGC { + + private static final String INSTRUCTIONS = """ + This test shows the ability to create Frames, Windows and Canvases + with a GraphicsConfiguration. + The test should show a number of windows with RGB stripes according + to the number of the GraphicsConfigurations for each screen. + The window also contains text which displays the size of the screen + and the output GraphicsConfiguration.toString(). + The test passes if every screen displays at least one such window. + """; + + public static void main(String[] argv) throws Exception { + SwingUtilities.invokeAndWait(NonDefaultGC::createUI); + PassFailJFrame.builder() + .title("GraphicsConfigurationTest") + .instructions(INSTRUCTIONS) + .testTimeOut(5) + .rows(12) + .columns(45) + .build() + .awaitAndCheck(); + + } + + private static void createUI() { + + GraphicsEnvironment ge = GraphicsEnvironment. + getLocalGraphicsEnvironment(); + GraphicsDevice[] gs = ge.getScreenDevices(); + for (int j = 0; j < gs.length; j++) { + GraphicsDevice gd = gs[j]; + GraphicsConfiguration[] gc = gd.getConfigurations(); + for (int i=0; i < gc.length; i++) { + JFrame f = new JFrame(gs[j].getDefaultConfiguration()); + PassFailJFrame.addTestWindow(f); // to ensure it is disposed. + GCCanvas c = new GCCanvas(gc[i]); + Rectangle gcBounds = gc[i].getBounds(); + int xoffs = gcBounds.x; + int yoffs = gcBounds.y; + f.getContentPane().add(c); + f.setTitle("Screen# "+ j +", GC# "+ i); + f.setSize(300, 150); + f.setLocation((i*50)+xoffs, (i*60)+yoffs); + f.show(); + } + } + } +} + +class GCCanvas extends Canvas { + + GraphicsConfiguration gc; + Rectangle bounds; + + public GCCanvas(GraphicsConfiguration gc) { + super(gc); + this.gc = gc; + bounds = gc.getBounds(); + } + + public Dimension getPreferredSize() { + return new Dimension(300, 150); + } + + public void paint(Graphics g) { + g.setColor(Color.red); + g.fillRect(0, 0, 100, 150); + g.setColor(Color.green); + g.fillRect(100, 0, 100, 150); + g.setColor(Color.blue); + g.fillRect(200, 0, 100, 150); + g.setColor(Color.black); + g.drawString("ScreenSize="+bounds.width+"X"+ bounds.height, 10, 15); + g.drawString(gc.toString(), 10, 30); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/GraphicsConfiguration/Position.java openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/Position.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/GraphicsConfiguration/Position.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/GraphicsConfiguration/Position.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4271200 + * @summary This test should show that the default position of a Frame + * should be on the physical screen for the GraphicsConfiguration. + * The togglebutton shows and hides an empty frame on the second monitor. + * The frame should be positioned at 0, 0 and is shown and hidden by clicking the button. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual Position + */ + +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; + +public class Position extends JPanel implements ActionListener { + + static final String INSTRUCTIONS = """ + This test should show that the default position of a Frame + should be on the physical screen for the specified GraphicsConfiguration. + There is a window "Show/Hide" button. + The button alternatively shows and hides an empty frame on the second monitor. + The frame should be positioned at 0, 0 and is shown and hidden by clicking the button. + The test passes if it behaves as described and fails otherwise. + """; + + static volatile GraphicsDevice gd[]; + static volatile JFrame secondFrame; + static volatile boolean on = true; + + public Position() { + JPanel p = new JPanel(); + JButton b = new JButton("Show/Hide Window on other screen"); + b.addActionListener(this); + p.add(b); + add(p); + } + + public void actionPerformed(ActionEvent e) { + if (secondFrame == null) { + secondFrame = new JFrame("screen1", gd[1].getDefaultConfiguration()); + secondFrame.setSize(500, 500); + PassFailJFrame.addTestWindow(secondFrame); + } + secondFrame.setVisible(on); + on = !on; + } + + public static void main(String[] args) throws Exception { + + gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); + if (gd.length < 2) { /* test runs only on a multi-screen environment */ + return; + } + + PassFailJFrame.builder() + .title("Screen Device Position Test") + .instructions(INSTRUCTIONS) + .testTimeOut(5) + .rows(10) + .columns(50) + .splitUIBottom(Position::new) + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/List/HandlingKeyEventIfMousePressedTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/List/HandlingKeyEventIfMousePressedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/List/HandlingKeyEventIfMousePressedTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/List/HandlingKeyEventIfMousePressedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6293432 + * @summary Key events ('SPACE', 'UP', 'DOWN') aren't blocked + * if mouse is kept in 'PRESSED' state for List + * @key headful + * @run main HandlingKeyEventIfMousePressedTest + */ + +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.List; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.InputEvent; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseMotionAdapter; + +public class HandlingKeyEventIfMousePressedTest { + + static Frame frame; + static List list; + static volatile Point loc; + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(100); + try { + EventQueue.invokeAndWait(() -> createUI()); + robot.waitForIdle(); + robot.delay(1000); + EventQueue.invokeAndWait(() -> { + loc = list.getLocationOnScreen(); + }); + robot.mouseMove(loc.x + 10, loc.y + 10); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + + // key pressing when the mouse is kept in the 'pressed' state + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + + int selectedIndex = list.getSelectedIndex(); + if (selectedIndex != 0) { + throw new RuntimeException("Test failed: list.getCurrentItem = " + selectedIndex); + } + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + private static void createUI() { + frame = new Frame("HandlingKeyEventIfMousePressedTest"); + list = new List(10, false); + + list.add("111"); + list.add("222"); + list.add("333"); + list.add("444"); + frame.add(list); + + addListeners(); + + frame.setLayout(new FlowLayout()); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + // added in order to have more information in failed case + private static void addListeners() { + + list.addMouseMotionListener( + new MouseMotionAdapter() { + @Override + public void mouseDragged(MouseEvent me) { + System.out.println(me); + } + + @Override + public void mouseMoved(MouseEvent me) { + System.out.println(me); + } + }); + + list.addMouseListener( + new MouseAdapter(){ + public void mousePressed(MouseEvent me) { + System.out.println(me); + } + public void mouseClicked(MouseEvent me) { + System.out.println(me); + } + public void mouseEntered(MouseEvent me) { + System.out.println(me); + } + public void mouseExited(MouseEvent me) { + System.out.println(me); + } + public void mouseReleased(MouseEvent me) { + System.out.println(me); + } + }); + + list.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent ae) { + System.out.println(ae); + } + }); + + list.addItemListener( + new ItemListener() { + public void itemStateChanged(ItemEvent ie) { + System.out.println(ie); + } + }); + + list.addFocusListener( + new FocusAdapter() { + public void focusGained(FocusEvent fe) { + System.out.println(fe); + } + public void focusLost(FocusEvent fe) { + System.out.println(fe); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/List/KeyEventsTest/KeyEventsTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -21,17 +21,6 @@ * questions. */ -/* - @test - @key headful - @bug 6190768 6190778 - @summary Tests that triggering events on AWT list by pressing CTRL + HOME, - CTRL + END, PG-UP, PG-DOWN similar Motif behavior - @library /test/lib - @build jdk.test.lib.Platform - @run main KeyEventsTest -*/ - import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.KeyboardFocusManager; @@ -50,6 +39,17 @@ import jdk.test.lib.Platform; +/* + * @test + * @key headful + * @bug 6190768 6190778 + * @requires os.family != "mac" + * @summary Tests that triggering events on AWT list by pressing CTRL + HOME, + * CTRL + END, PG-UP, PG-DOWN similar Motif behavior + * @library /test/lib + * @build jdk.test.lib.Platform + * @run main KeyEventsTest + */ public class KeyEventsTest { TestState currentState; final Object LOCK = new Object(); @@ -261,13 +261,7 @@ private void doTest() throws Exception { - boolean isWin = false; - if (Platform.isWindows()) { - isWin = true; - } else if (Platform.isOSX()) { - System.out.println("Not for OS X"); - return; - } + boolean isWin = Platform.isWindows(); System.out.println("multiple? selectedMoved? ?scrollMoved keyID? template? action?"); test(new TestState(false, false, false, KeyEvent.VK_PAGE_UP, isWin?false:false)); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/List/ListActionEventTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/List/ListActionEventTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/List/ListActionEventTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/List/ListActionEventTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4089604 + * @summary Enter key doesn't fire List actionPerformed as specified + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual ListActionEventTest +*/ + +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.List; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +public class ListActionEventTest { + + private static final String INSTRUCTIONS = """ + A frame will be shown. + 1. Click any item in the list (say item 1) in the frame + 2. A message 'ItemSelected' is displayed on the message window. + 3. Press the return key on the selected item. + 4. If the text 'ActionPerformed' is displayed on the message window, + then press PASS else press FAIL."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("ListActionEventTest Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(35) + .testUI(ListActionEventTest::createTestUI) + .logArea() + .build() + .awaitAndCheck(); + } + + private static Frame createTestUI() { + Frame frame = new Frame("ListActionEventTest frame"); + + Panel pnl1 = new Panel(); + frame.add(pnl1); + pnl1.setLayout(new BorderLayout()); + + List list = new List(); + for (int i = 0; i < 5; i++) { + list.addItem("Item " + i); + } + pnl1.add(list); + + list.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent ev) { + PassFailJFrame.log("ActionPerformed"); + } + }); + + list.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent ev) { + PassFailJFrame.log("ItemSelected"); + } + }); + frame.pack(); + return frame; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/List/MultiSelectionListHorizScrollbar.java openjdk-17-17.0.15+6/test/jdk/java/awt/List/MultiSelectionListHorizScrollbar.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/List/MultiSelectionListHorizScrollbar.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/List/MultiSelectionListHorizScrollbar.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4102881 + * @summary Ensure multiple selection Lists have horizontal scrollbars when necessary + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MultiSelectionListHorizScrollbar +*/ + +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.List; + +public class MultiSelectionListHorizScrollbar { + + private static final String INSTRUCTIONS = """ + Resize the frame so that the lists are not wide enough + to fully display the lines of text they contain. + Once the lists are in this state, press pass + if both lists display an horizontal scrollbar. Otherwise press fail."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("MultiSelectionListHorizScrollbar Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(35) + .testUI(MultiSelectionListHorizScrollbar::createTestUI) + .build() + .awaitAndCheck(); + } + + private static Frame createTestUI() { + Frame frame = new Frame("MultiSelectionListHorizScrollbar Frame"); + List singleList = new List(3); + List multiList = new List(3, true); + + frame.setLayout(new GridLayout(1, 2)); + frame.add(singleList); + frame.add(multiList); + + singleList.addItem("This is the 1st item in the list! Does it scroll horizontally??"); + singleList.addItem("This is the 2nd item in the list! Does it scroll horizontally??"); + singleList.addItem("This is the 4th item in the list! Does it scroll horizontally??"); + singleList.addItem("This is the 5th item in the list! Does it scroll horizontally??"); + singleList.addItem("This is the 6th item in the list! Does it scroll horizontally??"); + + multiList.addItem("This is the 1st item in the list! Does it scroll horizontally??"); + multiList.addItem("This is the 2nd item in the list! Does it scroll horizontally??"); + multiList.addItem("This is the 4th item in the list! Does it scroll horizontally??"); + multiList.addItem("This is the 5th item in the list! Does it scroll horizontally??"); + multiList.addItem("This is the 6th item in the list! Does it scroll horizontally??"); + + frame.pack(); + return frame; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/List/RepaintAfterResize.java openjdk-17-17.0.15+6/test/jdk/java/awt/List/RepaintAfterResize.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/List/RepaintAfterResize.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/List/RepaintAfterResize.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6308295 + * @summary XAWTduplicate list item is displayed + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual RepaintAfterResize +*/ + +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.List; + +public class RepaintAfterResize { + + private static final String INSTRUCTIONS = """ + 1) A Frame appears with a list + 2) Resize somehow the frame using mouse + 3) Move down the vertical scrollbar of the list + 4) If you see that two selected items are displayed then the test failed. + Otherwise, the test passed."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("RepaintAfterResize Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(35) + .testUI(RepaintAfterResize::createTestUI) + .build() + .awaitAndCheck(); + } + + private static Frame createTestUI() { + Frame frame = new Frame("RepaintAfterResize Frame"); + List list = new List(4, false); + + frame.setLayout (new FlowLayout ()); + list.setBounds(100, 100, 100, 100); + for (int i = 0 ; i < 7 ; i++) { + list.add(" " + i); + } + frame.add(list); + list.select(3); + + frame.setSize(100, 100); + return frame; + + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/ActionCommandTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/ActionCommandTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/ActionCommandTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/ActionCommandTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4079449 + * @key headful + * @summary MenuItem objects return null if they are activated by shortcut + */ + +import java.awt.Dialog; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Point; +import java.awt.Robot; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + +import static java.awt.event.KeyEvent.VK_CONTROL; +import static java.awt.event.KeyEvent.VK_META; + +public class ActionCommandTest implements ActionListener { + + static volatile Frame frame; + static volatile boolean event = false; + static volatile boolean failed = false; + static final String ITEMTEXT = "Testitem"; + + static void createUI() { + frame = new Frame("ActionCommand Menu Shortcut Test"); + MenuBar mb = new MenuBar(); + Menu m = new Menu("Test"); + MenuItem mi = new MenuItem(ITEMTEXT, new MenuShortcut(KeyEvent.VK_T)); + mi.addActionListener(new ActionCommandTest()); + m.add(mi); + mb.add(m); + frame.setMenuBar(mb); + frame.setBounds(50, 400, 200, 200); + frame.setVisible(true); + } + + public static void main(String[] args ) throws Exception { + + EventQueue.invokeAndWait(ActionCommandTest::createUI); + try { + Robot robot = new Robot(); + + robot.waitForIdle(); + robot.delay(2000); + + // Ensure window has focus + Point p = frame.getLocationOnScreen(); + robot.mouseMove(p.x + frame.getWidth() / 2, p.y + frame.getHeight() / 2); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(2000); + + // invoke short cut. + robot.keyPress(KeyEvent.VK_T); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_T); + robot.waitForIdle(); + robot.delay(2000); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + if (failed) { + throw new RuntimeException("No actioncommand"); + } + } + + // Since no ActionCommand is set, this should be the menuitem's label. + public void actionPerformed(ActionEvent e) { + event = true; + String s = e.getActionCommand(); + if (s == null || !s.equals(ITEMTEXT)) { + failed = true; + } + } + +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/CheckMenuShortcut.java openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/CheckMenuShortcut.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/CheckMenuShortcut.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/CheckMenuShortcut.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4167811 + * @summary tests that shortcuts work for Checkbox menu items + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual CheckMenuShortcut +*/ + +import java.awt.CheckboxMenuItem; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Insets; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Panel; +import java.awt.Rectangle; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.event.KeyEvent; + +public class CheckMenuShortcut implements ActionListener, ItemListener { + + static final String INSTRUCTIONS = """ + A window that contains a text area will be displayed. + The window will have a menu labeled 'Window Menu'. Click on the menu to see its items. + + The two menu items should have shortcuts which in order are : Ctrl-A, Ctrl-I. + On macOS these will be Command-A, Command-I. + + If the second item only has the label 'checkbox item' and no shortcut + ie none of Ctrl-I or Ctrl-i, or Command-I or Command-i on macOS painted on it, the test FAILS. + + The same second item - labeled 'checkbox item' is in fact a Checkbox menu item. + The menu item should NOT be checked (eg no tick mark). + + Dismiss the menu by clicking inside the window, do not select any of menu items. + After that press Ctrl-i, (Command-i on macOS). + + After that click on the menu again. If the second menu item 'checkbox item' is now + checked, the test PASSES, if it is not checked, the test FAILS. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("CheckboxMenuItem Shortcut Test Instructions") + .instructions(INSTRUCTIONS) + .columns(60) + .logArea() + .testUI(CheckMenuShortcut::createUI) + .build() + .awaitAndCheck(); + } + + + static Frame createUI() { + + MenuBar mainMenu; + Menu menu; + MenuItem action; + CheckboxMenuItem item; + TextArea pane; + + boolean isMac = System.getProperty("os.name").startsWith("Mac"); + String ctrlA = (isMac) ? "Command-A" : "Ctrl-A"; + String ctrlI = (isMac) ? "Command-I" : "Ctrl-I"; + + CheckMenuShortcut cms = new CheckMenuShortcut(); + Frame frame = new Frame("CheckMenuShortcut"); + + mainMenu = new MenuBar(); + menu = new Menu("Window Menu"); + + action = new MenuItem("action"); + action.setShortcut(new MenuShortcut(KeyEvent.VK_A, false)); + action.addActionListener(cms); + action.setActionCommand("action"); + menu.add(action); + + item = new CheckboxMenuItem("checkbox item", false); + item.setShortcut(new MenuShortcut(KeyEvent.VK_I,false)); + item.addItemListener(cms); + item.addActionListener(cms); + menu.add(item); + + mainMenu.add(menu); + + frame.setMenuBar(mainMenu); + + pane = new TextArea(ctrlA + " -- action menu test\n", 10, 40, TextArea.SCROLLBARS_VERTICAL_ONLY); + Dimension mySize = frame.getSize(); + Insets myIns = frame.getInsets(); + pane.setBounds(new Rectangle(mySize.width - myIns.left - myIns.right, + mySize.height - myIns.top - myIns.bottom)); + pane.setLocation(myIns.left,myIns.top); + frame.add(pane); + + pane.append(ctrlI + " -- item menu test\n"); + + frame.pack(); + return frame; + } + + public void itemStateChanged(ItemEvent evt) { + PassFailJFrame.log("Got item: " + evt.getItem() + "\n"); + } + + public void actionPerformed(ActionEvent evt) { + PassFailJFrame.log("Got action: " + evt.getActionCommand() + "\n"); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/FunctionKeyShortcut.java openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/FunctionKeyShortcut.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/FunctionKeyShortcut.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/FunctionKeyShortcut.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4034665 + * @key headful + * @summary Function keys should work correctly as shortcuts + */ + +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + +import static java.awt.event.KeyEvent.VK_CONTROL; +import static java.awt.event.KeyEvent.VK_META; + +public class FunctionKeyShortcut implements ActionListener { + + static volatile Frame frame; + static volatile boolean event = false; + static volatile boolean failed = false; + + static final boolean isMac = System.getProperty("os.name").contains("OS X"); + + static void createUI() { + frame = new Frame("Function Key Menu Shortcut Test"); + MenuBar mb = new MenuBar(); + Menu m = new Menu("Test"); + MenuItem mi1 = new MenuItem("Function key 1", new MenuShortcut(KeyEvent.VK_F1)); + MenuItem mi2 = new MenuItem("Function key 2", new MenuShortcut(KeyEvent.VK_F2)); + MenuItem mi3 = new MenuItem("Function key 3", new MenuShortcut(KeyEvent.VK_F3)); + MenuItem mi4 = new MenuItem("Function key 4", new MenuShortcut(KeyEvent.VK_F4)); + MenuItem mi5 = new MenuItem("Function key 5", new MenuShortcut(KeyEvent.VK_F5)); + MenuItem mi6 = new MenuItem("Function key 6", new MenuShortcut(KeyEvent.VK_F6)); + MenuItem mi7 = new MenuItem("Function key 7", new MenuShortcut(KeyEvent.VK_F7)); + MenuItem mi8 = new MenuItem("Function key 8", new MenuShortcut(KeyEvent.VK_F8)); + MenuItem mi9 = new MenuItem("Function key 8", new MenuShortcut(KeyEvent.VK_F9)); + + FunctionKeyShortcut fks = new FunctionKeyShortcut(); + mi1.addActionListener(fks); + mi2.addActionListener(fks); + mi3.addActionListener(fks); + mi4.addActionListener(fks); + mi5.addActionListener(fks); + mi6.addActionListener(fks); + mi7.addActionListener(fks); + mi8.addActionListener(fks); + mi9.addActionListener(fks); + + m.add(mi1); + m.add(mi2); + m.add(mi3); + m.add(mi4); + m.add(mi5); + m.add(mi6); + m.add(mi7); + m.add(mi8); + m.add(mi9); + + mb.add(m); + frame.setMenuBar(mb); + frame.setBounds(50,400,200,200); + frame.setVisible(true); + } + + public static void main(String[] args ) throws Exception { + + EventQueue.invokeAndWait(FunctionKeyShortcut::createUI); + try { + Robot robot = new Robot(); + + robot.waitForIdle(); + robot.delay(2000); + + // Ensure window has focus + Point p = frame.getLocationOnScreen(); + robot.mouseMove(p.x + frame.getWidth() / 2, p.y + frame.getHeight() / 2); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(2000); + + int mod = (isMac) ? KeyEvent.VK_META : KeyEvent.VK_CONTROL; + robot.keyPress(mod); + robot.keyPress(KeyEvent.VK_F1); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_F1); + robot.keyRelease(mod); + robot.waitForIdle(); + robot.delay(2000); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + if (!event || failed) { + throw new RuntimeException("No actioncommand"); + } + } + + public void actionPerformed(ActionEvent e) { + System.out.println("Got " + e); + String s = e.getActionCommand(); + event = true; + if (s == null || !s.equals("Function key 1")) { + failed = true; + } + } + +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/MenuItemShortcutReplaceTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/MenuItemShortcutReplaceTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/MenuShortcut/MenuItemShortcutReplaceTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/MenuShortcut/MenuItemShortcutReplaceTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4080225 + * @summary A replaced menu shortcut does not draw in the menu. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MenuItemShortcutReplaceTest + */ + +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.MenuShortcut; +import java.awt.Panel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; + +/* + * Manual test because visual verification of the shortcut being painted is required. + */ + +public class MenuItemShortcutReplaceTest implements ActionListener { + + static boolean isMac = System.getProperty("os.name").startsWith("Mac"); + static String shortcut = (isMac) ? "Cmd" : "Ctrl"; + static String instructions = + "1. On the frame 'MenuItem Shortcut Replace Test' click on the Menu 'Click here'.\n" + + " You will see a MenuItem 'MenuItem1' with the shortcut key displayed as" + + " '" + shortcut + "+M'.\n" + + "2. Click the 'Change Shortcutkey' button.\n" + + "3. Now click on the Menu again to see the MenuItem.\n" + + "4. If the shortcut key displayed near the MenuItem is changed to " + + "'" + shortcut + "+C', press 'Pass' else press 'Fail'"; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("MenuItem Shortcut Replace Test Instructions") + .instructions(instructions) + .columns(60) + .logArea() + .testUI(MenuItemShortcutReplaceTest::createUI) + .build() + .awaitAndCheck(); + + } + + static volatile Button change; + static volatile MenuItem mi; + static volatile MenuShortcut ms; + + static Frame createUI() { + Frame frame = new Frame("MenuItem Shortcut Replace Test"); + MenuBar mb = new MenuBar(); + change = new Button("Change ShortcutKey"); + Panel p = new Panel(); + p.add(change); + MenuItemShortcutReplaceTest misrt = new MenuItemShortcutReplaceTest(); + change.addActionListener(misrt); + Menu m = new Menu("Click here"); + mb.add(m); + mi = new MenuItem("MenuItem1"); + m.add(mi); + mi.addActionListener(misrt); + frame.setMenuBar(mb); + //Set the shortcut key for the menuitem + ms = new MenuShortcut(KeyEvent.VK_M); + mi.setShortcut(ms); + frame.add(p, BorderLayout.SOUTH); + frame.setSize(300, 300); + return frame; + } + + public void actionPerformed(ActionEvent e) { + //change the shortcut key + if (e.getSource() == change) { + ms = new MenuShortcut(KeyEvent.VK_C); + mi.setShortcut(ms); + PassFailJFrame.log("Shortcut key set to "+shortcut+"C"); + } + if (e.getSource() == mi) { + PassFailJFrame.log("MenuItem Selected"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/GlassPaneOverlappingTestBase.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -128,7 +128,7 @@ tests fail starting after failing mixing tests but always pass alone. */ Util.waitForIdle(robot); - ancestorLoc.translate(isOel7() ? 5 : f.getWidth() / 2 - 15, 2); + ancestorLoc.translate(isOel7orLater() ? 5 : f.getWidth() / 2 - 15, 2); robot.mouseMove(ancestorLoc.x, ancestorLoc.y); Util.waitForIdle(robot); robot.mousePress(InputEvent.BUTTON1_MASK); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Mixing/AWT_Mixing/SimpleOverlappingTestBase.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ import java.awt.*; import java.awt.event.*; +import java.util.regex.*; import javax.swing.*; import test.java.awt.regtesthelpers.Util; @@ -142,7 +143,7 @@ JFrame ancestor = (JFrame)(testedComponent.getTopLevelAncestor()); if( ancestor != null ) { Point ancestorLoc = ancestor.getLocationOnScreen(); - ancestorLoc.translate(isOel7() ? 5 : + ancestorLoc.translate(isOel7orLater() ? 5 : ancestor.getWidth() / 2 - 15, 2); robot.mouseMove(ancestorLoc.x, ancestorLoc.y); Util.waitForIdle(robot); @@ -158,10 +159,18 @@ return wasLWClicked; } - public boolean isOel7() { - return System.getProperty("os.name").toLowerCase() - .contains("linux") && System.getProperty("os.version") - .toLowerCase().contains("el7"); + public boolean isOel7orLater() { + if (System.getProperty("os.name").toLowerCase().contains("linux") && + System.getProperty("os.version").toLowerCase().contains("el")) { + Pattern p = Pattern.compile("el(\\d+)"); + Matcher m = p.matcher(System.getProperty("os.version")); + if (m.find()) { + try { + return Integer.parseInt(m.group(1)) >= 7; + } catch (NumberFormatException nfe) {} + } + } + return false; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Mouse/EnterExitEvents/ResizingFrameTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,12 +27,19 @@ * @bug 7154048 * @summary Programmatically resized window does not receive mouse entered/exited events * @author alexandr.scherbatiy area=awt.event + * @library /test/lib + * @build jdk.test.lib.Platform * @run main ResizingFrameTest */ -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; +import java.awt.Frame; +import java.awt.Robot; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +import jdk.test.lib.Platform; public class ResizingFrameTest { @@ -41,6 +48,9 @@ private static JFrame frame; public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + return; + } Robot robot = new Robot(); robot.setAutoDelay(50); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Multiscreen/MultiScreenLocationTest/MultiScreenLocationTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -70,9 +70,12 @@ GraphicsConfiguration gc = gd.getDefaultConfiguration(); Rectangle screen = gc.getBounds(); Robot robot = new Robot(gd); + robot.setAutoDelay(250); + robot.waitForIdle(); // check Robot.mouseMove() robot.mouseMove(screen.x + mouseOffset.x, screen.y + mouseOffset.y); + robot.waitForIdle(); Point mouse = MouseInfo.getPointerInfo().getLocation(); Point point = screen.getLocation(); point.translate(mouseOffset.x, mouseOffset.y); @@ -100,6 +103,16 @@ || image.getRGB(image.getWidth() - 1, 0) != rgb || image.getRGB(image.getWidth() - 1, image.getHeight() - 1) != rgb || image.getRGB(0, image.getHeight() - 1) != rgb) { + System.out.println("Robot.createScreenCapture Expected: " + + String.format("0x%08X",rgb)); + System.out.println("Robot.createScreenCapture Top Left Actual: " + + String.format("0x%08X",image.getRGB(0, 0))); + System.out.println("Robot.createScreenCapture Top Right Actual: " + + String.format("0x%08X",image.getRGB(image.getWidth() - 1, 0))); + System.out.println("Robot.createScreenCapture Bottom Right Actual: " + + String.format("0x%08X",image.getRGB(image.getWidth() - 1, image.getHeight() - 1))); + System.out.println("Robot.createScreenCapture Top Left Actual: " + + String.format("0x%08X",image.getRGB(0, image.getHeight() - 1))); throw new RuntimeException( getErrorText("Robot.createScreenCapture", i)); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/PrintJob/PrintCheckboxTest/PrintCheckboxManualTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/PrintJob/PrintCheckboxTest/PrintCheckboxManualTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/PrintJob/PrintCheckboxTest/PrintCheckboxManualTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/PrintJob/PrintCheckboxTest/PrintCheckboxManualTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,84 +22,52 @@ */ /* - @test - @bug 5045936 5055171 - @summary Tests that there is no ClassCastException thrown in printing - checkbox and scrollbar with XAWT - @key printer - @run applet/manual=yesno PrintCheckboxManualTest.html -*/ - -// Note there is no @ in front of test above. This is so that the -// harness will not mistake this file as a test file. It should -// only see the html file as a test file. (the harness runs all -// valid test files, so it would run this test twice if this file -// were valid as well as the html file.) -// Also, note the area= after Your Name in the author tag. Here, you -// should put which functional area the test falls in. See the -// AWT-core home page -> test areas and/or -> AWT team for a list of -// areas. - - - -import java.awt.*; -import java.awt.event.*; - - -//Manual tests should run as applet tests if possible because they -// get their environments cleaned up, including AWT threads, any -// test created threads, and any system resources used by the test -// such as file descriptors. (This is normally not a problem as -// main tests usually run in a separate VM, however on some platforms -// such as the Mac, separate VMs are not possible and non-applet -// tests will cause problems). Also, you don't have to worry about -// synchronisation stuff in Applet tests the way you do in main -// tests... - - -public class PrintCheckboxManualTest extends Panel -{ - //Declare things used in the test, like buttons and labels here - Frame f; - - public static void main(String[] args) { - PrintCheckboxManualTest a = new PrintCheckboxManualTest(); + * @test + * @bug 5045936 5055171 + * @summary Tests that there is no ClassCastException thrown in printing + * checkbox and scrollbar with XAWT + * @key printer + * @requires (os.family == "linux") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual PrintCheckboxManualTest + */ - a.init(); - a.start(); +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GridLayout; +import java.awt.Panel; +import java.awt.PrintJob; +import java.awt.Scrollbar; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class PrintCheckboxManualTest extends Panel { + + private static final String INSTRUCTIONS = """ + This test is for Linux with XToolkit ONLY!, + 1. Click the 'Print' button on the frame + 2. Select a printer in the print dialog and proceed + 3. If the frame with checkbox and button on it + is printed without any exception test PASSED else FAILED. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Instructions") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(PrintCheckboxManualTest::createTestUI) + .build() + .awaitAndCheck(); } - public void init() - { - //Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - - String[] instructions = - { - "Linux or Solaris with XToolkit ONLY!", - "1. Click the 'Print' button on the frame", - "2. Select a printer in the print dialog and proceed", - "3. If the frame with checkbox and button on it is printed successfully test PASSED else FAILED" - }; - Sysout.createDialogWithInstructions( instructions ); - - }//End init() + private static Frame createTestUI() { - public void start () - { - //Get things going. Request focus, set size, et cetera - setSize (200,200); - setVisible(true); - validate(); - - //What would normally go into main() will probably go here. - //Use System.out.println for diagnostic messages that you want - // to read after the test is done. - //Use Sysout.println for messages you want the tester to read. - - f = new Frame("Print checkbox"); + Frame f = new Frame("Print checkbox"); f.setLayout(new GridLayout(2, 2)); f.setSize(200, 100); @@ -111,185 +79,26 @@ f.add(sb); Button b = new Button("Print"); - b.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent ev) - { - PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(f, "PrintCheckboxManualTest", null); - if (pj != null) - { - try - { - Graphics g = pj.getGraphics(); - f.printAll(g); - g.dispose(); - pj.end(); - Sysout.println("Test PASSED"); - } - catch (ClassCastException cce) - { - Sysout.println("Test FAILED: ClassCastException"); -// throw new RuntimeException("Test FAILED: ClassCastException", cce); - } - catch (Exception e) - { - Sysout.println("Test FAILED: unknown Exception"); -// throw new Error("Test FAILED: unknown exception", e); - } + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ev) { + PrintJob pj = Toolkit.getDefaultToolkit(). + getPrintJob(f, "PrintCheckboxManualTest", + null); + if (pj != null) { + try { + Graphics g = pj.getGraphics(); + f.printAll(g); + g.dispose(); + pj.end(); + } catch (ClassCastException cce) { + throw new RuntimeException("Test FAILED: ClassCastException", cce); + } catch (Exception e) { + throw new Error("Test FAILED: unknown exception", e); + } } - } + } }); f.add(b); - - f.setVisible(true); - }// start() - - //The rest of this class is the actions which perform the test... - - //Use Sysout.println to communicate with the user NOT System.out!! - //Sysout.println ("Something Happened!"); - -} - -/* Place other classes related to the test after this line */ - - - - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); + return f; } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/Robot/ScreenCaptureRobotTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2000, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.GraphicsEnvironment; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; + +/* + * @test + * @key headful + * @bug 8342098 + * @summary Verify that the image captured from the screen using a Robot + * and the source image are same. + * @requires os.family == "mac" + * @run main/othervm ScreenCaptureRobotTest + */ + +/* + * @test + * @key headful + * @bug 8342098 + * @summary Verify that the image captured from the screen using a Robot + * and the source image are same. + * @requires os.family != "mac" + * @run main/othervm -Dsun.java2d.uiScale=1 ScreenCaptureRobotTest + */ +public class ScreenCaptureRobotTest { + + private static final int IMAGE_WIDTH = 200; + private static final int IMAGE_HEIGHT = 100; + private static final int OFFSET = 10; + + private static Frame frame; + private static Canvas canvas; + + private static BufferedImage realImage; + + private static volatile Point point; + + public static void main(String[] args) throws Exception { + try { + EventQueue.invokeAndWait(ScreenCaptureRobotTest::initializeGUI); + doTest(); + } finally { + EventQueue.invokeAndWait(ScreenCaptureRobotTest::disposeFrame); + } + } + + private static void initializeGUI() { + frame = new Frame("ScreenCaptureRobotTest Frame"); + realImage = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .getDefaultConfiguration() + .createCompatibleImage(IMAGE_WIDTH, IMAGE_HEIGHT); + + Graphics g = realImage.createGraphics(); + g.setColor(Color.YELLOW); + g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT); + g.setColor(Color.RED); + g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20)); + g.drawString("Capture This", 10, 40); + g.dispose(); + + canvas = new ImageCanvas(); + canvas.setBackground(Color.YELLOW); + canvas.setPreferredSize(new Dimension(IMAGE_WIDTH + (OFFSET * 2), + IMAGE_HEIGHT + (OFFSET * 2))); + frame.setLayout(new BorderLayout()); + frame.add(canvas); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void doTest() throws Exception { + Robot robot = new Robot(); + robot.mouseMove(0, 0); + robot.waitForIdle(); + robot.delay(500); + + EventQueue.invokeAndWait(() -> point = canvas.getLocationOnScreen()); + + Rectangle rect = new Rectangle(point.x + OFFSET, point.y + OFFSET, + IMAGE_WIDTH, IMAGE_HEIGHT); + + BufferedImage capturedImage = robot.createScreenCapture(rect); + + if (!compareImages(capturedImage, realImage)) { + String errorMessage = "FAIL : Captured Image is different from " + + "the real image"; + saveImage(capturedImage, "CapturedImage.png"); + saveImage(realImage, "RealImage.png"); + throw new RuntimeException(errorMessage); + } + } + + private static boolean compareImages(BufferedImage capturedImg, + BufferedImage realImg) { + int capturedPixel; + int realPixel; + int imgWidth = capturedImg.getWidth(); + int imgHeight = capturedImg.getHeight(); + + if (imgWidth != IMAGE_WIDTH || imgHeight != IMAGE_HEIGHT) { + System.out.println("Captured and real images are different in size"); + return false; + } + + for (int i = 0; i < imgWidth; i++) { + for (int j = 0; j < imgHeight; j++) { + capturedPixel = capturedImg.getRGB(i, j); + realPixel = realImg.getRGB(i, j); + if (capturedPixel != realPixel) { + System.out.println("Captured pixel (" + + Integer.toHexString(capturedPixel) + ") at " + + "(" + i + ", " + j + ") is not equal to real pixel (" + + Integer.toHexString(realPixel) + ")"); + return false; + } + } + } + return true; + } + + private static class ImageCanvas extends Canvas { + @Override + public void paint(Graphics g) { + g.drawImage(realImage, OFFSET, OFFSET, this); + } + } + + private static void saveImage(BufferedImage image, String fileName) { + try { + ImageIO.write(image, "png", new File(fileName)); + } catch (IOException ignored) { + System.err.println(ignored.getMessage()); + } + } + + private static void disposeFrame() { + if (frame != null) { + frame.dispose(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/CaretPositionTest/CaretPositionTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/CaretPositionTest/CaretPositionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/CaretPositionTest/CaretPositionTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/CaretPositionTest/CaretPositionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,104 @@ +/* + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.AWTException; +import java.awt.Button; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.TextField; +import java.awt.event.InputEvent; +import java.lang.reflect.InvocationTargetException; + +/* + * @test + * @bug 4038580 + * @key headful + * @requires os.family != "windows" + * @summary Caret position not accurate in presence of selected areas + * @run main CaretPositionTest + */ + +public class CaretPositionTest extends Frame { + private TextField text_field; + private Button caretpos_button; + private Point onScreen; + private Dimension size; + String text = "12 45 789"; + private static volatile int position = -1; + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException, AWTException { + CaretPositionTest test = new CaretPositionTest(); + EventQueue.invokeAndWait(test::setupGUI); + try { + test.test(); + if (position != 9) { + throw new RuntimeException("Caret position should be at the end of the string"); + } + } finally { + EventQueue.invokeAndWait(test::dispose); + } + } + + public void setupGUI() { + setLocationRelativeTo(null); + setTitle("CaretPositionTest"); + setLayout(new FlowLayout()); + text_field = new TextField(text, 9); + caretpos_button=new Button("CaretPosition"); + add(text_field); + add(caretpos_button); + pack(); + setVisible(true); + toFront(); + } + + public void test() throws AWTException, InterruptedException, + InvocationTargetException { + EventQueue.invokeAndWait(() -> { + onScreen = text_field.getLocationOnScreen(); + size = text_field.getSize(); + }); + Robot robot = new Robot(); + robot.setAutoDelay(50); + robot.delay(1000); + int y = onScreen.y + (size.height / 2); + robot.mouseMove(onScreen.x + (size.width / 2), y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseMove(onScreen.x + 3, y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + for (int x = onScreen.x + 5; x < onScreen.x + size.width; x += 2) { + robot.mouseMove(x, y); + } + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + EventQueue.invokeAndWait(() -> { + position = text_field.getCaretPosition(); + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetBoundsTest/SetBoundsTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetBoundsTest/SetBoundsTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetBoundsTest/SetBoundsTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetBoundsTest/SetBoundsTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.Color; +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Panel; +import java.awt.ScrollPane; +import java.awt.TextArea; +import java.awt.TextField; +import java.lang.reflect.InvocationTargetException; + +/* + * @test + * @bug 6198290 6277332 + * @summary TextField painting is broken when placed on a Scrollpane, XToolkit + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual SetBoundsTest + */ + +public class SetBoundsTest extends Frame { + + private static final String INSTRUCTIONS = """ + 1) Make active a frame with a scrollpane and a few components. + 2) Please, focus attention on the text components + placed on the upper half of the frame + 3) Make sure, that the scrollbar of the frame + have the same position during the test. + 4) Bring focus to TextField, try deleting the text. + If the text never gets erased, the test failed + 5) Bring focus to TextArea, try deleting the text. + If the text never gets erased, the test failed + 6) Please, focus attention on the text components + placed on the lower half of the frame + 7) Try input something into TextField. + If you can not input anything into TextField, the test failed + 8) Try input something into TextArea. + If you can not input anything into TextArea, the test failed + 9) The test passed + """; + + public SetBoundsTest() { + setTitle("SetBoundsTest Test Frame"); + setLayout(new GridLayout(2, 1)); + Panel hw = new Panel(); + ScrollPane sp = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); + Container lw = new Container(); + fill(hw); + fill(lw); + + sp.add(hw); + add(sp); + add(lw); + + setSize(600, 600); + sp.setScrollPosition(20, 0); + + } + + private void fill(Container c) { + Button button = new Button("button"); + c.add(button); + button.setBackground(new Color(0xd3ceac)); + button.setForeground(new Color(0x000000)); + button.move(60, 80); + button.resize(400, 60); + button.show(true); + + TextField textfield = new TextField("textfield"); + c.add(textfield); + textfield.setBackground(new Color(0xd3ceac)); + textfield.setForeground(new Color(0x000000)); + textfield.move(60, 20); + textfield.resize(400, 40); + textfield.show(true); + + TextArea textarea = new TextArea("textarea"); + c.add(textarea); + textarea.setBackground(new Color(0xd3ceac)); + textarea.setForeground(new Color(0x000000)); + textarea.move(60, 80); + textarea.resize(400, 60); + textarea.show(true); + + c.setLayout (new FlowLayout()); + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame.builder() + .title("Set Bounds Test Instructions") + .instructions(INSTRUCTIONS) + .testUI(SetBoundsTest::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(40) + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetEchoCharTest4/SetEchoCharTest4.java openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetEchoCharTest4/SetEchoCharTest4.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetEchoCharTest4/SetEchoCharTest4.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetEchoCharTest4/SetEchoCharTest4.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.InvocationTargetException; + +/* + * @test + * @bug 4226580 + * @summary TextField with echoChar add+remove+add seems to be broken + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual SetEchoCharTest4 + */ + +public class SetEchoCharTest4 extends Frame implements ActionListener { + TextField tf1 = new TextField(8); + TextField tf2 = new TextField(8); + TextField tf3 = new TextField(8); + Button b = new Button("Click Several Times"); + + static final String INSTRUCTIONS = """ + Type in the first text field and * characters will echo. + Type in the second text field and $ characters will echo. + Type in the third text field and # characters will echo. + + Hit the button several times. All characters should remain + the same and the test should not crash. + + Make sure the actual text matches what you typed in for each field. + Press Pass if everything's ok, otherwise Fail + """; + + public SetEchoCharTest4() { + setLayout(new FlowLayout()); + tf1.setEchoChar('*'); + tf2.setEchoChar('$'); + tf3.setEchoChar('#'); + addStuff(); + b.addActionListener(this); + setSize (200,200); + } + + private void addStuff() { + add(tf1); + add(tf2); + add(tf3); + add(b); + } + + public void actionPerformed(ActionEvent ae) { + PassFailJFrame.log("TextField1 = " + tf1.getText()); + PassFailJFrame.log("TextField2 = " + tf2.getText()); + PassFailJFrame.log("TextField3 = " + tf3.getText()); + PassFailJFrame.log("--------------"); + setVisible(false); + remove(tf1); + remove(tf2); + remove(tf3); + remove(b); + addStuff(); + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame.builder() + .title("Set Echo Character Test") + .testUI(SetEchoCharTest4::new) + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(40) + .logArea() + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetPasswordTest/SetPasswordTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetPasswordTest/SetPasswordTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/SetPasswordTest/SetPasswordTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/SetPasswordTest/SetPasswordTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.InvocationTargetException; + +/* + * @test + * @bug 4084454 + * @summary Make sure that you can set the text in a "password mode" + * text field and that it echoes as the current echo char. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual SetPasswordTest + */ + +public class SetPasswordTest extends Frame implements ActionListener { + private String setText = "Set text"; + private String getText = "Get text"; + private TextField tfPassword; + + static final String INSTRUCTIONS = """ + The purpose of this test is to ensure that when using a textField for + password entry that text set programmatically is not shown in the clear. + + We also test "pasting" text into the text field. + + 1. Press the "Set Text" button + Text should appear as '*' chars + - if the string "secret" appears then the test is failed. + 2. Use the mouse to select (highlight) all the text and press the DELETE key + 3. Use the system's copy/paste functionality to copy a text string from the + desktop or this window, and paste it into the text field. + 4. Text should appear in the text field as '*' chars + - if the string you pasted appears then the test is failed. + 5. press the "Get Text" button and the string you pasted + should be printed in the log area + - if it prints echo symbols instead the test is failed. + """; + + public SetPasswordTest() { + setLayout(new FlowLayout()); + tfPassword = new TextField("Initial text", 30); + tfPassword.setEchoChar('*'); + add(tfPassword); + + Button b1 = new Button(setText); + b1.addActionListener(this); + add(b1); + + Button b2 = new Button(getText); + b2.addActionListener(this); + add(b2); + pack(); + } + + public void actionPerformed(ActionEvent evt) { + String ac = evt.getActionCommand(); + if (setText.equals(ac)) { + tfPassword.setText("secret"); + } + + if (getText.equals(ac)) { + PassFailJFrame.log("Text: \"" + tfPassword.getText() + "\""); + } + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame.builder() + .title("Set Password Test") + .testUI(SetPasswordTest::new) + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(40) + .logArea() + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/ZeroEchoCharTest/ZeroEchoCharTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/ZeroEchoCharTest/ZeroEchoCharTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TextField/ZeroEchoCharTest/ZeroEchoCharTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TextField/ZeroEchoCharTest/ZeroEchoCharTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.lang.reflect.InvocationTargetException; + +/* + * @test + * @bug 4307281 + * @summary verify that after setting the echo char to 0 disguises are + * removed and user input is echoed to the screen unchanged. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual ZeroEchoCharTest + */ + +public class ZeroEchoCharTest extends Frame implements ActionListener { + private final TextField textfield = new TextField(); + private final Button button1 = new Button("Set echo char to *"); + private final Button button2 = new Button("Set echo char to 0"); + static final String INSTRUCTIONS = """ + 1.Type in the text field. The user input must be echoed unchanged. + 2.Set echo char to '*' by pressing the corresponding button. + If all characters in the text field aren't immediately replaced + with '*', the test fails. + 3.Set echo char to 0 by pressing the corresponding button. + If disguises in the text field don't immediately revert to + the original characters, the test fails. + 4.Type in the text field. If the input is echoed unchanged, + the test passes. Otherwise, the test fails. + """; + + public ZeroEchoCharTest() { + button1.addActionListener(this); + button2.addActionListener(this); + + setLayout(new GridLayout(3, 1)); + + add(textfield); + add(button1); + add(button2); + pack(); + } + + public void actionPerformed(ActionEvent event) { + if (event.getSource() == button1) { + textfield.setEchoChar('*'); + } else if (event.getSource() == button2) { + textfield.setEchoChar((char)0); + } + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame.builder() + .title("Zero Echo Char Test") + .testUI(ZeroEchoCharTest::new) + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(40) + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ActionCommand/ActionCommand.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionCommand/ActionCommand.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ActionCommand/ActionCommand.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionCommand/ActionCommand.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,7 +21,14 @@ * questions. */ -import java.awt.*; +import jdk.test.lib.Platform; +import jtreg.SkippedException; + +import java.awt.AWTException; +import java.awt.EventQueue; +import java.awt.Point; +import java.awt.SystemTray; +import java.awt.TrayIcon; import java.awt.image.BufferedImage; /* @@ -30,12 +37,18 @@ * @summary Check the return value of the getActionCommand method * of the ActionEvent triggered when TrayIcon is double clicked * (single clicked, on Mac) - * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) * @modules java.desktop/java.awt:open - * @library /lib/client ../ - * @library /java/awt/patchlib - * @build java.desktop/java.awt.Helper - * @build ExtendedRobot SystemTrayIconHelper + * @library + * /java/awt/patchlib + * /java/awt/TrayIcon + * /lib/client + * /test/lib + * @build + * java.desktop/java.awt.Helper + * jdk.test.lib.Platform + * jtreg.SkippedException + * ExtendedRobot + * SystemTrayIconHelper * @run main ActionCommand */ @@ -44,32 +57,38 @@ TrayIcon icon; ExtendedRobot robot; - boolean actionPerformed = false; - Object actionLock = new Object(); - String actionCommand = null; + volatile boolean actionPerformed = false; + volatile String actionCommand = null; + final Object actionLock = new Object(); + static boolean isMacOS = false; public static void main(String[] args) throws Exception { - if (! SystemTray.isSupported()) { - System.out.println("SystemTray not supported on the platform under test. " + - "Marking the test passed"); - } else { - if (System.getProperty("os.name").toLowerCase().startsWith("win")) { - System.err.println("Test can fail if the icon hides to a tray icons pool " + - "in Windows 7, which is behavior by default.\n" + - "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + - "\"Always show all icons and notifications on the taskbar\" true to " + - "avoid this problem. Or change behavior only for Java SE tray icon " + - "and rerun test."); - } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")){ - isMacOS = true; - } else if (SystemTrayIconHelper.isOel7()) { - System.out.println("OEL 7 doesn't support double click in " + - "systray. Skipped"); - return; - } - new ActionCommand().doTest(); + if (Platform.isOnWayland()) { + // The current robot implementation does not support + // clicking in the system tray area. + throw new SkippedException("Skipped on Wayland"); + } + + if (!SystemTray.isSupported()) { + throw new SkippedException("SystemTray is not supported on this platform."); + } + + if (Platform.isWindows()) { + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true to " + + "avoid this problem. Or change behavior only for Java SE tray icon " + + "and rerun test."); + } else if (Platform.isOSX()){ + isMacOS = true; + } else if (SystemTrayIconHelper.isOel7orLater()) { + System.out.println("OEL 7 doesn't support double click in " + + "systray. Skipped"); + throw new SkippedException("Skipped on OEL 7+"); } + new ActionCommand().doTest(); } void doTest() throws Exception { @@ -95,7 +114,7 @@ icon.setActionCommand("Sample Command"); - if (! "Sample Command".equals(icon.getActionCommand())) + if (!"Sample Command".equals(icon.getActionCommand())) throw new RuntimeException("FAIL: getActionCommand did not return the correct value. " + icon.getActionCommand() + " Expected: Sample Command"); @@ -117,7 +136,7 @@ actionPerformed = false; SystemTrayIconHelper.doubleClick(robot); - if (! actionPerformed) { + if (!actionPerformed) { synchronized (actionLock) { try { actionLock.wait(3000); @@ -125,7 +144,7 @@ } } } - if (! actionPerformed) { + if (!actionPerformed) { throw new RuntimeException("FAIL: ActionEvent not triggered when TrayIcon is "+(isMacOS? "" : "double ")+"clicked"); } else if (! "Sample Command".equals(actionCommand)) { throw new RuntimeException("FAIL: ActionEvent.getActionCommand did not return the correct " + @@ -140,7 +159,7 @@ } }); - robot.mouseMove(0, 0); + robot.mouseMove(100, 0); robot.waitForIdle(); robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); @@ -149,7 +168,7 @@ actionCommand = null; SystemTrayIconHelper.doubleClick(robot); - if (! actionPerformed) { + if (!actionPerformed) { synchronized (actionLock) { try { actionLock.wait(3000); @@ -157,7 +176,7 @@ } } } - if (! actionPerformed) { + if (!actionPerformed) { throw new RuntimeException("FAIL: ActionEvent not triggered when ActionCommand set to " + "null and then TrayIcon is "+(isMacOS? "" : "double ")+ "clicked"); } else if (actionCommand != null) { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ActionEventMask/ActionEventMask.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -70,7 +70,7 @@ } else { if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { isMacOS = true; - } else if (SystemTrayIconHelper.isOel7()) { + } else if (SystemTrayIconHelper.isOel7orLater()) { System.out.println("OEL 7 doesn't support double click in " + "systray. Skipped"); return; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ModalityTest/ModalityTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ModalityTest/ModalityTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/ModalityTest/ModalityTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/ModalityTest/ModalityTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,7 +39,7 @@ */ public class ModalityTest { - private static boolean isOEL7; + private static boolean isOel7orLater; TrayIcon icon; ExtendedRobot robot; Dialog d; @@ -85,7 +85,7 @@ "\"Always show all icons and notifications on the taskbar\" true " + "to avoid this problem. Or change behavior only for Java SE tray " + "icon and rerun test."); - isOEL7 = SystemTrayIconHelper.isOel7(); + isOel7orLater = SystemTrayIconHelper.isOel7orLater(); new ModalityTest().doTest(); } } @@ -230,7 +230,7 @@ Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); if (iconPosition == null) throw new RuntimeException("Unable to find the icon location!"); - if (isOEL7) { + if (isOel7orLater) { // close tray robot.mouseMove(100,100); robot.click(InputEvent.BUTTON1_MASK); @@ -243,7 +243,7 @@ robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(2000); - if(!isOEL7) { + if(!isOel7orLater) { SystemTrayIconHelper.doubleClick(robot); if (!actionPerformed) { @@ -260,7 +260,7 @@ for (int i = 0; i < buttonTypes.length; i++) { mousePressed = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -283,7 +283,7 @@ mouseReleased = false; mouseClicked = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -315,7 +315,7 @@ throw new RuntimeException("FAIL: mouseClicked not triggered when " + buttonNames[i] + " pressed & released"); } - if (!isOEL7) { + if (!isOel7orLater) { mouseMoved = false; robot.mouseMove(iconPosition.x, iconPosition.y); robot.glide(iconPosition.x + 100, iconPosition.y); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseEventMask/MouseEventMaskTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -75,7 +75,7 @@ "\"Always show all icons and notifications on the taskbar\" true " + "to avoid this problem. Or change behavior only for Java SE tray " + "icon and rerun test."); - } else if (SystemTrayIconHelper.isOel7()) { + } else if (SystemTrayIconHelper.isOel7orLater()) { return; } new MouseEventMaskTest().doTest(); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/MouseMovedTest/MouseMovedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,7 +44,7 @@ return; } - if (SystemTrayIconHelper.isOel7()) { + if (SystemTrayIconHelper.isOel7orLater()) { return; } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SecurityCheck/FunctionalityCheck/FunctionalityCheck.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -55,7 +55,7 @@ boolean mouseReleased = false; boolean mouseClicked = false; boolean mouseMoved = false; - static boolean isOEL7; + static boolean isOel7orLater; static final int[] buttonTypes = { InputEvent.BUTTON1_MASK, @@ -74,7 +74,7 @@ System.out.println("SystemTray not supported on the platform under test. " + "Marking the test passed"); } else { - isOEL7 = SystemTrayIconHelper.isOel7(); + isOel7orLater = SystemTrayIconHelper.isOel7orLater(); new FunctionalityCheck().doTest(); } } @@ -194,7 +194,7 @@ Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); if (iconPosition == null) throw new RuntimeException("Unable to find the icon location!"); - if (isOEL7) { + if (isOel7orLater) { // close tray robot.mouseMove(100,100); robot.click(InputEvent.BUTTON1_MASK); @@ -203,7 +203,7 @@ robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); - if(!isOEL7) { + if(!isOel7orLater) { SystemTrayIconHelper.doubleClick(robot); if (!actionPerformed) { @@ -220,7 +220,7 @@ for (int i = 0; i < buttonTypes.length; i++) { mousePressed = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -243,7 +243,7 @@ mouseReleased = false; mouseClicked = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -275,7 +275,7 @@ throw new RuntimeException("FAIL: mouseClicked not triggered when " + buttonNames[i] + " pressed & released"); } - if(!isOEL7) { + if(!isOel7orLater) { mouseMoved = false; robot.mouseMove(iconPosition.x + 100, iconPosition.y); robot.glide(iconPosition.x, iconPosition.y); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/SystemTrayIconHelper.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SystemTrayIconHelper.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/SystemTrayIconHelper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/SystemTrayIconHelper.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,8 @@ import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /* * @summary This is a helper class to find the location of a system tray icon, @@ -210,7 +212,7 @@ String sysv = System.getProperty("os.version"); System.out.println("System version is " + sysv); //Additional step to raise the system try in Gnome 3 in OEL 7 - if(isOel7()) { + if(isOel7orLater()) { System.out.println("OEL 7 detected"); GraphicsConfiguration gc = GraphicsEnvironment. getLocalGraphicsEnvironment().getDefaultScreenDevice(). @@ -234,9 +236,17 @@ return false; } - public static boolean isOel7() { - return System.getProperty("os.name").toLowerCase() - .contains("linux") && System.getProperty("os.version") - .toLowerCase().contains("el7"); + public static boolean isOel7orLater() { + if (System.getProperty("os.name").toLowerCase().contains("linux") && + System.getProperty("os.version").toLowerCase().contains("el")) { + Pattern p = Pattern.compile("el(\\d+)"); + Matcher m = p.matcher(System.getProperty("os.version")); + if (m.find()) { + try { + return Integer.parseInt(m.group(1)) >= 7; + } catch (NumberFormatException nfe) {} + } + } + return false; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEventModifiers/TrayIconEventModifiersTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -110,7 +110,7 @@ System.out.println(System.getProperty("os.arch")); - if (SystemTrayIconHelper.isOel7()) { + if (SystemTrayIconHelper.isOel7orLater()) { System.out.println("OEL 7 doesn't support click modifiers in " + "systray. Skipped"); return; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconEvents/TrayIconEventsTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,7 +41,7 @@ public class TrayIconEventsTest { - private static boolean isOEL7; + private static boolean isOel7orLater; TrayIcon icon; ExtendedRobot robot; @@ -82,7 +82,7 @@ "\"Always show all icons and notifications on the taskbar\" true " + "to avoid this problem. Or change behavior only for Java SE " + "tray icon."); - isOEL7 = SystemTrayIconHelper.isOel7(); + isOel7orLater = SystemTrayIconHelper.isOel7orLater(); new TrayIconEventsTest().doTest(); } } @@ -201,7 +201,7 @@ Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); if (iconPosition == null) throw new RuntimeException("Unable to find the icon location!"); - if (isOEL7) { + if (isOel7orLater) { // close tray robot.mouseMove(100,100); robot.click(InputEvent.BUTTON1_MASK); @@ -210,7 +210,7 @@ robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); - if(!isOEL7) { + if(!isOel7orLater) { SystemTrayIconHelper.doubleClick(robot); if (!actionPerformed) { @@ -227,7 +227,7 @@ for (int i = 0; i < buttonTypes.length; i++) { mousePressed = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -250,7 +250,7 @@ mouseReleased = false; mouseClicked = false; - if(isOEL7) { + if(isOel7orLater) { SystemTrayIconHelper.openTrayIfNeeded(robot); robot.mouseMove(iconPosition.x, iconPosition.y); robot.click(buttonTypes[i]); @@ -283,7 +283,7 @@ buttonNames[i] + " pressed & released"); } - if (!isOEL7) { + if (!isOel7orLater) { mouseMoved = false; robot.mouseMove(iconPosition.x + 100, iconPosition.y); robot.glide(iconPosition.x, iconPosition.y); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconMouseTest/TrayIconMouseTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,9 @@ * questions. */ +import jdk.test.lib.Platform; +import jtreg.SkippedException; + import java.awt.EventQueue; import java.awt.Point; import java.awt.SystemTray; @@ -37,10 +40,17 @@ * or single clicked with button 3 on Mac OS X * or single clicked with button 1 on rest. * @modules java.desktop/java.awt:open - * @library /java/awt/patchlib - * @library /lib/client ../ - * @build java.desktop/java.awt.Helper - * @build ExtendedRobot SystemTrayIconHelper + * @library + * /java/awt/patchlib + * /java/awt/TrayIcon + * /lib/client + * /test/lib + * @build + * java.desktop/java.awt.Helper + * jdk.test.lib.Platform + * jtreg.SkippedException + * ExtendedRobot + * SystemTrayIconHelper * @run main TrayIconMouseTest */ @@ -48,16 +58,18 @@ TrayIcon icon; ExtendedRobot robot; - boolean actionPerformed = false; - Object actionLock = new Object(); + + volatile boolean actionPerformed = false; + final Object actionLock = new Object(); + static boolean isMacOS = false; static boolean isWinOS = false; static boolean isOelOS = false; String caption = "Sample Icon"; int[] buttonTypes = { - InputEvent.BUTTON1_MASK, - InputEvent.BUTTON2_MASK, - InputEvent.BUTTON3_MASK + InputEvent.BUTTON1_DOWN_MASK, + InputEvent.BUTTON2_DOWN_MASK, + InputEvent.BUTTON3_DOWN_MASK }; String[] buttonNames = { "BUTTON1", @@ -66,20 +78,24 @@ }; public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + // The current robot implementation does not support + // clicking in the system tray area. + throw new SkippedException("Skipped on Wayland"); + } + if (!SystemTray.isSupported()) { - System.out.println("SystemTray not supported on the platform " - + "under test. Marking the test passed"); + throw new SkippedException("SystemTray is not supported on this platform."); + } + + if (Platform.isOSX()) { + isMacOS = true; + } else if (Platform.isWindows()) { + isWinOS = true; } else { - String osName = System.getProperty("os.name").toLowerCase(); - if (osName.startsWith("mac")) { - isMacOS = true; - } else if (osName.startsWith("win")) { - isWinOS = true; - } else { - isOelOS = SystemTrayIconHelper.isOel7(); - } - new TrayIconMouseTest().doTest(); + isOelOS = SystemTrayIconHelper.isOel7orLater(); } + new TrayIconMouseTest().doTest(); } TrayIconMouseTest() throws Exception { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupClickTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupClickTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupClickTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupClickTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,14 +20,15 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ +import jdk.test.lib.Platform; +import jtreg.SkippedException; + import java.awt.TrayIcon; import java.awt.SystemTray; import java.awt.EventQueue; import java.awt.Point; import java.awt.AWTException; import java.awt.event.MouseEvent; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.image.BufferedImage; @@ -37,12 +38,18 @@ * @key headful * @summary Check if a action performed event is received when TrayIcon display * message is clicked on. - * @author Shashidhara Veerabhadraiah (shashidhara.veerabhadraiah@oracle.com) * @modules java.desktop/java.awt:open - * @library /java/awt/patchlib - * @library /lib/client ../ - * @build java.desktop/java.awt.Helper - * @build ExtendedRobot SystemTrayIconHelper + * @library + * /java/awt/patchlib + * /java/awt/TrayIcon + * /lib/client + * /test/lib + * @build + * java.desktop/java.awt.Helper + * jdk.test.lib.Platform + * jtreg.SkippedException + * ExtendedRobot + * SystemTrayIconHelper * @run main TrayIconPopupClickTest */ @@ -50,22 +57,29 @@ TrayIcon icon; ExtendedRobot robot; - boolean actionPerformed = false; + volatile boolean actionPerformed = false; public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + // The current robot implementation does not support + // clicking in the system tray area. + throw new SkippedException("Skipped on Wayland"); + } + if (!SystemTray.isSupported()) { - System.out.println("SystemTray not supported on the platform under test. " + - "Marking the test passed"); - } else { - if (System.getProperty("os.name").toLowerCase().startsWith("win")) - System.err.println("Test can fail if the icon hides to a tray icons pool " + - "in Windows 7/10, which is behavior by default.\n" + - "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + - "\"Always show all icons and notifications on the taskbar\" true " + - "to avoid this problem. Or change behavior only for Java SE " + - "tray icon."); - new TrayIconPopupClickTest().doTest(); + throw new SkippedException("SystemTray is not supported on this platform."); + } + + if (Platform.isWindows()) { + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7/10, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE " + + "tray icon."); } + + new TrayIconPopupClickTest().doTest(); } TrayIconPopupClickTest() throws Exception { @@ -89,33 +103,26 @@ throw new RuntimeException(e); } - icon.getActionCommand(); - icon.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - actionPerformed = true; - } - }); + icon.addActionListener(e -> actionPerformed = true); } void doTest() throws Exception { - Point iconPosition = SystemTrayIconHelper.getTrayIconLocation(icon); if (iconPosition == null) throw new RuntimeException("Unable to find the icon location!"); robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.delay(50); robot.mouseMove(iconPosition.x, iconPosition.y + 10); robot.waitForIdle(); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.delay(50); if (!actionPerformed) diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/TrayIcon/TrayIconPopup/TrayIconPopupTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,8 +20,22 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import java.awt.*; -import java.awt.event.*; + +import jdk.test.lib.Platform; +import jtreg.SkippedException; + +import java.awt.AWTException; +import java.awt.Dialog; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.MenuItem; +import java.awt.Point; +import java.awt.PopupMenu; +import java.awt.SystemTray; +import java.awt.TrayIcon; +import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; /* @@ -29,12 +43,18 @@ * @key headful * @summary Check if a JPopupMenu can be displayed when TrayIcon is * right clicked. It uses a JWindow as the parent of the JPopupMenu - * @author Dmitriy Ermashov (dmitriy.ermashov@oracle.com) * @modules java.desktop/java.awt:open - * @library /java/awt/patchlib - * @library /lib/client ../ - * @build java.desktop/java.awt.Helper - * @build ExtendedRobot SystemTrayIconHelper + * @library + * /java/awt/patchlib + * /java/awt/TrayIcon + * /lib/client + * /test/lib + * @build + * java.desktop/java.awt.Helper + * jdk.test.lib.Platform + * jtreg.SkippedException + * ExtendedRobot + * SystemTrayIconHelper * @run main TrayIconPopupTest */ @@ -43,27 +63,34 @@ TrayIcon icon; ExtendedRobot robot; - boolean actionPerformed = false; - Object actionLock = new Object(); + volatile boolean actionPerformed = false; + final Object actionLock = new Object(); + static final int ATTEMPTS = 10; PopupMenu popup; Dialog window; public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + // The current robot implementation does not support + // clicking in the system tray area. + throw new SkippedException("Skipped on Wayland"); + } + if (!SystemTray.isSupported()) { - System.out.println("SystemTray not supported on the platform under test. " + - "Marking the test passed"); - } else { - if (System.getProperty("os.name").toLowerCase().startsWith("win")) - System.err.println("Test can fail if the icon hides to a tray icons pool " + - "in Windows 7, which is behavior by default.\n" + - "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + - "\"Always show all icons and notifications on the taskbar\" true " + - "to avoid this problem. Or change behavior only for Java SE " + - "tray icon."); - new TrayIconPopupTest().doTest(); + throw new SkippedException("SystemTray is not supported on this platform."); + } + + if (Platform.isWindows()) { + System.err.println("Test can fail if the icon hides to a tray icons pool " + + "in Windows 7, which is behavior by default.\n" + + "Set \"Right mouse click\" -> \"Customize notification icons\" -> " + + "\"Always show all icons and notifications on the taskbar\" true " + + "to avoid this problem. Or change behavior only for Java SE " + + "tray icon."); } + new TrayIconPopupTest().doTest(); } TrayIconPopupTest() throws Exception { @@ -128,15 +155,15 @@ robot.mouseMove(iconPosition.x, iconPosition.y); robot.waitForIdle(); - robot.mousePress(InputEvent.BUTTON3_MASK); + robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON3_MASK); + robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); robot.delay(6000); robot.mouseMove(window.getLocation().x + 10, window.getLocation().y + 10); - robot.mousePress(InputEvent.BUTTON3_MASK); + robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON3_MASK); + robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); int attempts = 0; while (!actionPerformed && attempts++ < ATTEMPTS) { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/a11y/AccessibleJTableTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/a11y/AccessibleJTableTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/a11y/AccessibleJTableTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/a11y/AccessibleJTableTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2021, JetBrains s.r.o.. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,22 +26,22 @@ * @test * @bug 8267388 * @summary Test implementation of NSAccessibilityTable protocol peer - * @author Artem.Semenov@jetbrains.com * @run main/manual AccessibleJTableTest * @requires (os.family == "windows" | os.family == "mac") */ -import javax.swing.*; -import javax.swing.event.TableModelEvent; -import javax.swing.event.TableModelListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableModel; - -import java.awt.*; +import java.awt.FlowLayout; +import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.table.AbstractTableModel; public class AccessibleJTableTest extends AccessibleComponentTest { private static final String[] columnNames = {"One", "Two", "Three"}; @@ -67,6 +67,7 @@ + "If you can hear table cells ctrl+tab further and press PASS, otherwise press FAIL.\n"; JTable table = new JTable(data, columnNames); + table.setPreferredScrollableViewportSize(table.getPreferredSize()); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(table); @@ -82,12 +83,13 @@ + "Turn screen reader on, and Tab to the table.\n" + "Using arrow keys navigate to the last cell in the first row in the table." + "Screen reader should announce it as \"Column 3 row 1\"\n\n" - + "Using mouse drag the header of the last culumn so the last column becomes the first one." + + "Using mouse drag the header of the last column so the last column becomes the first one." + "Wait for the screen reader to finish announcing new position in table.\n\n" + "If new position in table corresponds to the new table layout ctrl+tab further " + "and press PASS, otherwise press FAIL.\n"; JTable table = new JTable(data, columnNames); + table.setPreferredScrollableViewportSize(table.getPreferredSize()); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(table); @@ -105,7 +107,9 @@ + "If you can hear second table name: \"second table\" - ctrl+tab further and press PASS, otherwise press FAIL.\n"; JTable table = new JTable(data, columnNames); + table.setPreferredScrollableViewportSize(table.getPreferredSize()); JTable secondTable = new JTable(data, columnNames); + secondTable.setPreferredScrollableViewportSize(secondTable.getPreferredSize()); secondTable.getAccessibleContext().setAccessibleName("Second table"); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); @@ -126,8 +130,8 @@ + "If you hear changes in the table - ctrl+tab further and press PASS, otherwise press FAIL.\n"; JTable table = new JTable(new TestTableModel(3, 3)); - - JPanel panel = new JPanel(); + table.setPreferredScrollableViewportSize(table.getPreferredSize()); + JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(table); panel.add(scrollPane); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/dnd/DropActionChangeTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/DropActionChangeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/dnd/DropActionChangeTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/DropActionChangeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -21,17 +21,17 @@ * questions. */ -import javax.swing.JFrame; import java.awt.AWTEvent; import java.awt.Component; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Panel; import java.awt.Point; +import java.awt.Rectangle; import java.awt.Robot; +import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.dnd.DnDConstants; -import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceAdapter; @@ -43,9 +43,13 @@ import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.AWTEventListener; -import java.awt.event.MouseEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.io.File; +import java.util.concurrent.atomic.AtomicReference; +import javax.imageio.ImageIO; +import javax.swing.JFrame; /* @test @@ -56,28 +60,24 @@ */ public class DropActionChangeTest extends JFrame implements AWTEventListener { - Robot robot; - Frame frame; + private static Robot robot; + private static Frame frame; + private static volatile DropActionChangeTest test; Panel panel; private volatile boolean failed; private volatile boolean dropEnd; private volatile Component clickedComponent; private final Object LOCK = new Object(); - static final int FRAME_ACTIVATION_TIMEOUT = 3000; - static final int DROP_COMPLETION_TIMEOUT = 5000; + static final int DROP_COMPLETION_TIMEOUT = 8000; static final int MOUSE_RELEASE_TIMEOUT = 2000; public static void main(String[] args) throws Exception { - DropActionChangeTest test = new DropActionChangeTest(); + EventQueue.invokeAndWait(() -> test = new DropActionChangeTest()); EventQueue.invokeAndWait(test::init); try { test.start(); } finally { - EventQueue.invokeAndWait(() -> { - if (test.frame != null) { - test.frame.dispose(); - } - }); + EventQueue.invokeAndWait(DropActionChangeTest::disposeFrame); } } @@ -97,10 +97,12 @@ final DragSourceListener dsl = new DragSourceAdapter() { public void dragDropEnd(DragSourceDropEvent e) { - System.err.println("DragSourseListener.dragDropEnd(): " + + System.err.println("DragSourceListener.dragDropEnd(): " + "drop action=" + e.getDropAction()); if (e.getDropAction() != DnDConstants.ACTION_MOVE) { - System.err.println("FAILURE: wrong drop action:" + e.getDropAction()); + System.err.println("FAILURE: wrong drop action:" + + e.getDropAction() + ", It should be " + + DnDConstants.ACTION_MOVE); failed = true; } synchronized (LOCK) { @@ -110,11 +112,7 @@ } }; - DragGestureListener dgl = new DragGestureListener() { - public void dragGestureRecognized(DragGestureEvent dge) { - dge.startDrag(null, new StringSelection("test"), dsl); - } - }; + DragGestureListener dgl = dge -> dge.startDrag(null, new StringSelection("test"), dsl); new DragSource().createDefaultDragGestureRecognizer(panel, DnDConstants.ACTION_COPY_OR_MOVE, dgl); @@ -142,11 +140,25 @@ frame.setVisible(true); } + private static void disposeFrame() { + if (frame != null) { + frame.dispose(); + } + if (test != null) { + test.dispose(); + } + } + public void start() { try { robot = new Robot(); - - Point startPoint = panel.getLocationOnScreen(); + robot.setAutoDelay(100); + robot.waitForIdle(); + robot.delay(500); + + AtomicReference startPointRef = new AtomicReference<>(); + EventQueue.invokeAndWait(()-> startPointRef.set(panel.getLocationOnScreen())); + Point startPoint = startPointRef.get(); startPoint.translate(50, 50); if (!pointInComponent(robot, startPoint, panel)) { @@ -163,15 +175,18 @@ synchronized (LOCK) { robot.keyPress(KeyEvent.VK_CONTROL); robot.mouseMove(startPoint.x, startPoint.y); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); Util.doDrag(robot, startPoint, medPoint); + robot.delay(500); robot.keyRelease(KeyEvent.VK_CONTROL); Util.doDrag(robot, medPoint, endPoint); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.delay(500); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); LOCK.wait(DROP_COMPLETION_TIMEOUT); } if (!dropEnd) { - System.err.println("DragSourseListener.dragDropEnd() was not called, returning"); + captureScreen("No_Drop_End_"); + System.err.println("DragSourceListener.dragDropEnd() was not called, returning"); return; } } catch (Throwable e) { @@ -179,10 +194,22 @@ } if (failed) { - throw new RuntimeException("wrong drop action!"); + captureScreen("Wrong_Drop_Action_"); + throw new RuntimeException("Wrong drop action!"); } - System.err.println("test passed!"); + System.err.println("Test passed!"); + } + + private static void captureScreen(String str) { + try { + final Rectangle screenBounds = new Rectangle( + Toolkit.getDefaultToolkit().getScreenSize()); + ImageIO.write(robot.createScreenCapture(screenBounds), "png", + new File(str + "Failure_Screen.png")); + } catch (Exception e) { + e.printStackTrace(); + } } public void reset() { @@ -203,9 +230,9 @@ robot.waitForIdle(); reset(); robot.mouseMove(p.x, p.y); - robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); synchronized (LOCK) { - robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); LOCK.wait(MOUSE_RELEASE_TIMEOUT); } @@ -227,15 +254,11 @@ } public static void doDrag(Robot robot, Point startPoint, Point endPoint) { + robot.waitForIdle(); for (Point p = new Point(startPoint); !p.equals(endPoint); p.translate(Util.sign(endPoint.x - p.x), Util.sign(endPoint.y - p.y))) { robot.mouseMove(p.x, p.y); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } } } -} +} \ No newline at end of file diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/dnd/NextDropActionTest/NextDropActionTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/NextDropActionTest/NextDropActionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/dnd/NextDropActionTest/NextDropActionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/dnd/NextDropActionTest/NextDropActionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -88,7 +88,7 @@ final DragSourceListener dsl = new DragSourceAdapter() { boolean firstCall = true; public void dragDropEnd(DragSourceDropEvent e) { - System.err.println("DragSourseListener.dragDropEnd(): " + + System.err.println("DragSourceListener.dragDropEnd(): " + " firstCall=" + firstCall + " drop action=" + e.getDropAction()); if (firstCall) { @@ -140,18 +140,22 @@ robot.keyRelease(KeyEvent.VK_CONTROL); LOCK.wait(WAIT_TIMEOUT); } + if (!firstEnd) { - System.err.println("DragSourseListener.dragDropEnd() " + + System.err.println("DragSourceListener.dragDropEnd() " + "was not called, returning"); return; } + robot.delay(1000); + synchronized (LOCK) { Util.doDragDrop(robot, startPoint, endPoint); LOCK.wait(WAIT_TIMEOUT); } + if (!secondEnd) { - System.err.println("DragSourseListener.dragDropEnd() " + + System.err.println("DragSourceListener.dragDropEnd() " + "was not called, returning"); return; } @@ -171,7 +175,7 @@ class Util { public static int sign(int n) { - return n < 0 ? -1 : n == 0 ? 0 : 1; + return Integer.compare(n, 0); } public static void doDragDrop(Robot robot, Point startPoint, Point endPoint) { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/grab/CursorTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/grab/CursorTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/grab/CursorTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/grab/CursorTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6364746 6400007 + * @summary Cursor should be changed correctly while Swing menu is open (input is grabbed). + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual CursorTest +*/ + +import java.awt.FlowLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; + +public class CursorTest { + + static final String INSTRUCTIONS = """ + After the test starts you will see a frame titled "Cursor Test Window", + with two menus in the menubar (menu1 and menu2), and a textfield and + a button, labeled "JButton". + 1. Open menu1 (it should be small and fit within the border of the frame), + 2. Verify that the pointer image (cursor) is the default desktop cursor. + 3. Move the mouse over the text field - the cursor should change its shape to caret, + 4. Move the mouse over the button - the cursor should be default one, + 5. Move the mouse to the border of the frame - cursor should be a resize one + (exact shape is dependent on the border you move over), + 6. Move the mouse out of the frame - cursor should be default one, + 7. Perform steps 2-6 in reverse order (after this the mouse should be over the open menu1), + 8. Open menu2, it should be big enough to not fit within the frame, + 9. Repeat steps 2-7 (you should end up with mouse over opened menu2 :), + 10. Close the menu. + 11. If on every step the cursor was as described, press Pass, press Fail otherwise. + """; + + static JFrame createUI() { + + JButton but = new JButton("JButton"); + JPanel panel = new JPanel(); + JTextField jtf = new JTextField("JTextField", 20); + + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame frame = new JFrame("Cursor Test Window"); + frame.setLayout(new FlowLayout()); + panel.add(but); + + frame.getContentPane().add(jtf); + frame.getContentPane().add(panel); + + JMenu menu1 = new JMenu("menu1"); + menu1.add(new JMenuItem("menu1,item1")); + JMenuBar mb = new JMenuBar(); + mb.add(menu1); + JMenu menu2 = new JMenu("menu2"); + for (int i = 0; i < 10; i++) { + menu2.add(new JMenuItem("menu2,item"+i)); + } + mb.add(menu2); + frame.setJMenuBar(mb); + frame.pack(); + return frame; + } + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Cursor Test") + .instructions(INSTRUCTIONS) + .columns(60) + .testUI(CursorTest::createUI) + .build() + .awaitAndCheck(); + + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/grab/SystemMenuTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/grab/SystemMenuTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/grab/SystemMenuTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/grab/SystemMenuTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6364741 + * @key headful + * @requires (os.family == "windows") + * @summary REG: Using frame's menu actions does not make swing menu disappear on WinXP, + * since Mustang-b53 + */ + +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.Point; +import java.awt.Robot; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; +import javax.swing.event.MenuEvent; +import javax.swing.event.MenuListener; + +public class SystemMenuTest implements MenuListener { + + static volatile JMenu menu; + static volatile JMenu sub_menu; + static volatile JFrame frame; + + static volatile int selectCount = 0; + static volatile int deselectCount = 0; + static volatile boolean failed = false; + static volatile String reason = "none"; + + static void createUI() { + SystemMenuTest smt = new SystemMenuTest(); + sub_menu = new JMenu("SubMenu"); + sub_menu.addMenuListener(smt); + sub_menu.add(new JMenuItem("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")); + sub_menu.add(new JMenuItem("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB")); + menu = new JMenu("Menu"); + menu.addMenuListener(smt); + menu.add(sub_menu); + JMenuBar mb = new JMenuBar(); + mb.add(menu); + + frame = new JFrame("JFrame"); + frame.setJMenuBar(mb); + frame.pack(); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + + Robot robot = new Robot(); + + SwingUtilities.invokeAndWait(SystemMenuTest::createUI); + + try { + robot.waitForIdle(); + robot.delay(2000); + + Point p = menu.getLocationOnScreen(); + robot.mouseMove(p.x + menu.getWidth() / 2, p.y + menu.getHeight() / 2); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(2000); + + p = sub_menu.getLocationOnScreen(); + robot.mouseMove(p.x + sub_menu.getWidth() / 2, p.y + sub_menu.getHeight() /2 ); + robot.mousePress(InputEvent.BUTTON1_MASK); + robot.mouseRelease(InputEvent.BUTTON1_MASK); + robot.waitForIdle(); + robot.delay(2000); + + // Alt-Space to invoke System Menu, should close Swing menus. + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_SPACE); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_SPACE); + robot.keyRelease(KeyEvent.VK_ALT); + robot.waitForIdle(); + robot.delay(2000); + + if (selectCount != 2 || deselectCount != 2) { + throw new RuntimeException("unexpected selection count " + selectCount + ", " + deselectCount); + } + if (failed) { + throw new RuntimeException("Failed because " + reason); + } + } finally { + if (frame != null) { + SwingUtilities.invokeAndWait(frame::dispose); + } + } + } + + public void menuCanceled(MenuEvent e) { + System.out.println("cancelled"+e.getSource()); + } + + public void menuDeselected(MenuEvent e) { + deselectCount++; + if (selectCount != 2) { + failed = true; + reason = "deselect without two selects"; + } + System.out.println("deselected"+e.getSource()); + } + + public void menuSelected(MenuEvent e) { + if (deselectCount != 0) { + failed = true; + reason = "select without non-zero deselects"; + } + selectCount++; + System.out.println("selected"+e.getSource()); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/im/JTextFieldTest.html openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/im/JTextFieldTest.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ - - -

    -Please run this test case under Solaris cjk locale with inputmethod -support, if you could input Chinese/Japanese/Korean in the swing -JTextField, then the test has passed! - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/im/JTextFieldTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/im/JTextFieldTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/im/JTextFieldTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,43 +23,50 @@ /* * @test - * @bug 4226191 + * @bug 4226191 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Verify that Lightweight text components (like swing JTextField) * work correctly with IM when there is an uneditable peered * TextField/TextArea in the same parent Frame - * @author xueming.shen@eng - * @run applet/manual=yesno JTextFieldTest.html + * @run main/manual JTextFieldTest */ -import java.awt.*; -import java.awt.event.*; -import java.applet.*; -import javax.swing.*; +import java.awt.FlowLayout; +import java.awt.TextField; -public class JTextFieldTest extends Applet implements ActionListener { - - TextField tf1; - JTextField tf2; - - public JTextFieldTest() { - tf1 = new TextField("ABCDEFGH", 10); - tf1.setEditable(false); - tf2 = new JTextField("12345678", 10); - setLayout(new FlowLayout()); - add(tf1); - add(tf2); - } - - public void actionPerformed(ActionEvent ae) { +import javax.swing.JFrame; +import javax.swing.JTextField; +public class JTextFieldTest { + private static final String INSTRUCTIONS = + """ + Please run this test in a CJK (Chinese/Japanese/Korean) locale + with input method support. If you could add input in the swing + JTextField, then the test has passed! + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("JTextFieldTest") + .instructions(INSTRUCTIONS) + .rows(5) + .columns(40) + .testUI(JTextFieldTest::createAndShowGUI) + .build() + .awaitAndCheck(); } - public static void main(String args[]) { - JFrame win = new JFrame(); - JTextFieldTest jtf = new JTextFieldTest(); - win.getContentPane().setLayout(new FlowLayout()); - win.getContentPane().add(jtf); - win.pack(); - win.show(); + public static JFrame createAndShowGUI() { + JFrame frame = new JFrame("Test Frame"); + frame.setLayout(new FlowLayout()); + TextField tf1 = new TextField("ABCDEFGH", 10); + tf1.setEditable(false); + JTextField tf2 = new JTextField("12345678", 10); + frame.getContentPane().add(tf1); + frame.getContentPane().add(tf2); + frame.pack(); + return frame; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/image/MemoryLeakTest/MemoryLeakTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/image/MemoryLeakTest/MemoryLeakTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/image/MemoryLeakTest/MemoryLeakTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/image/MemoryLeakTest/MemoryLeakTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,154 +22,101 @@ */ /* @test - @bug 4078566 6658398 - @summary Test for a memory leak in Image. - @run main/manual MemoryLeakTest -*/ - -import java.applet.Applet; -import java.lang.*; -import java.awt.*; -import java.awt.event.*; - -class Globals { - static boolean testPassed=false; - static Thread mainThread=null; -} - -public class MemoryLeakTest extends Applet { - -public static void main(String args[]) throws Exception { - new TestDialog(new Frame(), "MemoryLeakTest").start(); - new MemoryLeak().start(); - Globals.mainThread = Thread.currentThread(); - try { - Thread.sleep(300000); - } catch (InterruptedException e) { - if (!Globals.testPassed) - throw new Exception("MemoryLeakTest failed."); - } -} - -} - -class TestDialog extends Dialog - implements ActionListener { + * @bug 4078566 6658398 + * @requires (os.family == "linux") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Test for a memory leak in Image. + * @run main/manual MemoryLeakTest + */ -TextArea output; -Button passButton; -Button failButton; -String name; - -public TestDialog(Frame frame, String name) -{ - super(frame, name + " Pass/Fail Dialog"); - this.name = name; - output = new TextArea(11, 50); - add("North", output); - output.append("Do the following steps on Solaris only.\n"); - output.append("Maximize and minimize the Memory Leak Test window.\n"); - output.append("Execute the following after minimize.\n"); - output.append(" ps -al | egrep -i 'java|PPID'\n"); - output.append("Examine the size of the process under SZ.\n"); - output.append("Maximize and minimize the Memory Leak Test window again.\n"); - output.append("Execute the following after minimize.\n"); - output.append(" ps -al | egrep -i 'java|PPID'\n"); - output.append("Examine the size of the process under SZ.\n"); - output.append("If the two SZ values are the same, plus or minus one,\n"); - output.append("then click Pass, else click Fail."); - Panel buttonPanel = new Panel(); - passButton = new Button("Pass"); - failButton = new Button("Fail"); - passButton.addActionListener(this); - failButton.addActionListener(this); - buttonPanel.add(passButton); - buttonPanel.add(failButton); - add("South", buttonPanel); - pack(); +import java.awt.Color; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; + +public class MemoryLeakTest { + private static final String INSTRUCTIONS = + """ + Do the following steps on Unix platforms. + Maximize and minimize the Memory Leak Test window. + Execute the following after minimize. + ps -al | egrep -i 'java|PPID' + Examine the size of the process under SZ. + Maximize and minimize the Memory Leak Test window again. + Execute the following after minimize. + ps -al | egrep -i 'java|PPID' + Examine the size of the process under SZ. + If the two SZ values are the same, plus or minus one, + then click Pass, else click Fail. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("MemoryLeakTest Instructions") + .instructions(INSTRUCTIONS) + .rows(15) + .columns(40) + .testUI(MemoryLeak::new) + .build() + .awaitAndCheck(); + } } -public void start() -{ - show(); -} +class MemoryLeak extends Frame implements ComponentListener { + private Image osImage; -public void actionPerformed(ActionEvent event) -{ - if ( event.getSource() == passButton ) { - Globals.testPassed = true; - System.err.println(name + " Passed."); - } - else if ( event.getSource() == failButton ) { - Globals.testPassed = false; - System.err.println(name + " Failed."); - } - this.dispose(); - if (Globals.mainThread != null) - Globals.mainThread.interrupt(); -} - -} + public MemoryLeak() { + super("Memory Leak Test"); + setSize(200, 200); + addComponentListener(this); + } + public static void main(String[] args) { + new MemoryLeak().start(); + } -class MemoryLeak extends Frame implements ComponentListener -{ -private Image osImage; - -public MemoryLeak() -{ - super("Memory Leak Test"); - setSize(200, 200); - addComponentListener(this); -} + public void start() { + setVisible(true); + } -public static void main(String args[]) -{ - new MemoryLeak().start(); -} + public void paint(Graphics g) { + if (osImage != null) { + g.drawImage(osImage, 0, 0, this); + } + } -public void start() -{ - show(); -} + public void update(Graphics g) { + paint(g); + } -public void paint(Graphics g) { - if (osImage != null) { - g.drawImage(osImage, 0, 0, this); + public void componentResized(ComponentEvent e) { + Image oldimage = osImage; + osImage = createImage(getSize().width, getSize().height); + Graphics g = osImage.getGraphics(); + if (oldimage != null) { + g.drawImage(oldimage, 0, 0, getSize().width, getSize().height, this); + oldimage.flush(); + } else { + g.setColor(Color.blue); + g.drawLine(0, 0, getSize().width, getSize().height); + } + g.dispose(); } -} -public void update(Graphics g) -{ - paint(g); -} + public void componentMoved(ComponentEvent e) {} -public void componentResized(ComponentEvent e) -{ - Image oldimage = osImage; - osImage = createImage(getSize().width, getSize().height); - Graphics g = osImage.getGraphics(); - if (oldimage != null) { - g.drawImage(oldimage, 0, 0, getSize().width, getSize().height, this); - oldimage.flush(); - } else { + public void componentShown(ComponentEvent e) { + osImage = createImage(getSize().width, getSize().height); + Graphics g = osImage.getGraphics(); g.setColor(Color.blue); g.drawLine(0, 0, getSize().width, getSize().height); + g.dispose(); } - g.dispose(); -} - -public void componentMoved(ComponentEvent e) {} - -public void componentShown(ComponentEvent e) -{ - osImage = createImage(getSize().width, getSize().height); - Graphics g = osImage.getGraphics(); - g.setColor(Color.blue); - g.drawLine(0, 0, getSize().width, getSize().height); - g.dispose(); -} -public void componentHidden(ComponentEvent e) {} + public void componentHidden(ComponentEvent e) {} } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.html openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ - - - - - MultiDisplayTest - - - - -This test is for OS X or Windows only. -For other OSes please simply push "Pass". - -The test requires two-display configuration, where - -- 1st display is operating in HiDPI mode; -- 2nd display is non-HiDPI. - -In other cases please simply push "Pass". - - -To run test please push "Start". - -Then drag parent / child to different displays and check -that the proper image is shown for every window -(must be "black 1x" for non-HiDPI and "blue 2x" for HiDPI). - -Please try to drag both parent and child, -do it fast several times and check if no artefacts occur. - -Try to switch display resolution (high to low and back). - -For Mac OS X please check also the behavior for -translucent windows appearing on the 2nd (non-active) display -and Mission Control behavior. - -Close the windows. - -In case if no issues occur please push "Pass", otherwise "Fail". - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest/MultiDisplayTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -/* - @test - @bug 8142861 8143062 8147016 - @summary Check if multiresolution image behaves properly - on HiDPI + non-HiDPI display pair. - @author a.stepanov - @library /test/lib - @build jdk.test.lib.Platform - @run applet/manual=yesno MultiDisplayTest.html -*/ - - -import java.applet.Applet; -import java.awt.*; -import java.awt.event.*; -import java.awt.image.*; - -import jdk.test.lib.Platform; - -public class MultiDisplayTest extends Applet { - - private static final int W = 200, H = 200; - - private static final BaseMultiResolutionImage IMG = - new BaseMultiResolutionImage(new BufferedImage[]{ - generateImage(1, Color.BLACK), generateImage(2, Color.BLUE)}); - - private static boolean checkOS() { - return Platform.isWindows() || Platform.isOSX(); - } - - public void init() { this.setLayout(new BorderLayout()); } - - public void start() { - - Button b = new Button("Start"); - b.setEnabled(checkOS()); - - b.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - - ParentFrame p = new ParentFrame(); - new ChildDialog(p); - } - }); - - add(b, BorderLayout.CENTER); - - validate(); - setVisible(true); - } - - - private static BufferedImage generateImage(int scale, Color c) { - - BufferedImage image = new BufferedImage( - scale * W, scale * H, BufferedImage.TYPE_INT_RGB); - Graphics g = image.getGraphics(); - g.setColor(c); - g.fillRect(0, 0, scale * W, scale * H); - - g.setColor(Color.WHITE); - Font f = g.getFont(); - g.setFont(new Font(f.getName(), Font.BOLD, scale * 48)); - g.drawChars((scale + "X").toCharArray(), 0, 2, scale * W / 2, scale * H / 2); - - return image; - } - - private static class ParentFrame extends Frame { - - public ParentFrame() { - EventQueue.invokeLater(this::CreateUI); - } - - private void CreateUI() { - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { dispose(); } - }); - setSize(W, H); - setLocation(50, 50); - setTitle("parent"); - setResizable(false); - setVisible(true); - } - - @Override - public void paint(Graphics gr) { - gr.drawImage(IMG, 0, 0, this); - } - } - - private static class ChildDialog extends Dialog { - - public ChildDialog(Frame f) { - super(f); - EventQueue.invokeLater(this::CreateUI); - } - - private void CreateUI() { - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { dispose(); } - }); - setSize(W, H); - setTitle("child"); - setResizable(false); - setModal(true); - setVisible(true); - } - - @Override - public void paint(Graphics gr) { - gr.drawImage(IMG, 0, 0, this); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/image/multiresolution/MultiDisplayTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/image/multiresolution/MultiDisplayTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Dialog; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BaseMultiResolutionImage; +import java.awt.image.BufferedImage; + +import javax.swing.JButton; + +import jdk.test.lib.Platform; +import jtreg.SkippedException; + +/* + * @test + * @bug 8142861 8143062 8147016 + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame jdk.test.lib.Platform + * @requires (os.family == "windows" | os.family == "mac") + * @summary Check if multiresolution image behaves properly + * on HiDPI + non-HiDPI display pair. + * @run main/manual MultiDisplayTest + */ + +public class MultiDisplayTest { + private static final String INSTRUCTIONS = + """ + The test requires two-display configuration, where + + - 1st display is operating in HiDPI mode; + - 2nd display is non-HiDPI. + + In other cases please simply push "Pass". + + To run test please push "Start". + + Then drag parent / child to different displays and check + that the proper image is shown for every window + (must be "black 1x" for non-HiDPI and "blue 2x" for HiDPI). + + Please try to drag both parent and child, + do it fast several times and check if no artefacts occur. + + Try to switch display resolution (high to low and back). + + For Mac OS X please check also the behavior for + translucent windows appearing on the 2nd (non-active) display + and Mission Control behavior. + + Close the Child & Parent windows. + + In case if no issues occur please push "Pass", otherwise "Fail". + """; + + private static final int W = 200; + private static final int H = 200; + + private static final BaseMultiResolutionImage IMG = + new BaseMultiResolutionImage(new BufferedImage[]{ + generateImage(1, Color.BLACK), generateImage(2, Color.BLUE)}); + + public static void main(String[] args) throws Exception { + if (!checkOS()) { + throw new SkippedException("Invalid OS." + + "Please run test on either Windows or MacOS"); + } + PassFailJFrame + .builder() + .title("MultiDisplayTest Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .splitUIBottom(MultiDisplayTest::createAndShowGUI) + .build() + .awaitAndCheck(); + } + + public static JButton createAndShowGUI() { + JButton b = new JButton("Start"); + b.addActionListener(e -> { + ParentFrame p = new ParentFrame(); + new ChildDialog(p); + }); + return b; + } + + private static boolean checkOS() { + return Platform.isWindows() || Platform.isOSX(); + } + + private static BufferedImage generateImage(int scale, Color c) { + BufferedImage image = new BufferedImage( + scale * W, scale * H, BufferedImage.TYPE_INT_RGB); + Graphics g = image.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, scale * W, scale * H); + + g.setColor(Color.WHITE); + Font f = g.getFont(); + g.setFont(new Font(f.getName(), Font.BOLD, scale * 48)); + g.drawChars((scale + "X").toCharArray(), 0, 2, + scale * W / 2, scale * H / 2); + return image; + } + + private static class ParentFrame extends Frame { + public ParentFrame() { + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { dispose(); } + }); + setSize(W, H); + setLocation(50, 50); + setTitle("parent"); + setResizable(false); + setVisible(true); + } + + @Override + public void paint(Graphics gr) { + gr.drawImage(IMG, 0, 0, this); + } + } + + private static class ChildDialog extends Dialog { + public ChildDialog(Frame f) { + super(f); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { dispose(); } + }); + setSize(W, H); + setTitle("child"); + setResizable(false); + setModal(true); + setVisible(true); + } + + @Override + public void paint(Graphics gr) { + gr.drawImage(IMG, 0, 0, this); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/Dialog/PrintApplet.html openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/Dialog/PrintApplet.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -!-- - Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - - This code is free software; you can redistribute it and/or modify it - under the terms of the GNU General Public License version 2 only, as - published by the Free Software Foundation. - - This code is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - version 2 for more details (a copy is included in the LICENSE file that - accompanied this code). - - You should have received a copy of the GNU General Public License version - 2 along with this work; if not, write to the Free Software Foundation, - Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - - Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - or visit www.oracle.com if you need additional information or have any - questions. ---> - -PrintApplet -

    PrintApplet

    - - - -

    diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/Dialog/PrintApplet.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/Dialog/PrintApplet.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/Dialog/PrintApplet.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - @test - @bug 5024549 - @key printer - @summary Pass if dialogs are modal. - @run applet/manual PrintApplet.html -*/ -import java.awt.*; -import java.awt.event.*; -import java.applet.*; -import java.awt.print.*; -import javax.swing.*; - -public class PrintApplet extends JApplet implements Printable { - private JButton jButton1 = new JButton(); - - - public PrintApplet() { - } - - public void init() { - try { - jbInit(); - } - catch(Exception e) { - e.printStackTrace(); - } - } - - private void jbInit() throws Exception { - jButton1.setText("PRINT"); - jButton1.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(ActionEvent e) { - jButton1_actionPerformed(e); - } - }); - jButton1.setBounds(new Rectangle(165, 248, 80, 30)); - this.setSize(new Dimension(400,300)); - this.getContentPane().setLayout(null); - this.getContentPane().setBackground(Color.pink); - this.getContentPane().add(jButton1, BorderLayout.SOUTH); - } - - public void start() { - } - - public void stop() { - } - - public void destroy() { - } - - public String getAppletInfo() { - return "Applet inf"; - } - - public String[][] getParameterInfo() { - return null; - } - - - public int print(Graphics g, PageFormat pf, int page) throws PrinterException { - System.out.println("Calling print"); - if (page == 0) { - Graphics2D g2 = (Graphics2D)g; - g2.translate(pf.getImageableX(), pf.getImageableY()); - g2.setColor(Color.black); - g2.drawString("Hello World", 20, 100); - - return Printable.PAGE_EXISTS; - } - return Printable.NO_SUCH_PAGE; - } - - - - void jButton1_actionPerformed(ActionEvent e) { - PrinterJob printJob = null; - PageFormat pageFormat = null; - Paper prtPaper = null; - boolean bPrintFlg = true; - - - try{ - printJob = PrinterJob.getPrinterJob(); - - } - catch(SecurityException se){ - - bPrintFlg = false; - } - - if (bPrintFlg) { - - pageFormat = printJob.pageDialog(printJob.defaultPage()); - System.out.println("PrintApplet: pageFormat = "+pageFormat.getWidth()/72.0+" x "+pageFormat.getHeight()/72.0); - if (pageFormat != null) { - - prtPaper = pageFormat.getPaper(); - pageFormat.setPaper(prtPaper); - - - printJob.setPrintable(this, pageFormat); - } - - if (printJob.printDialog()) { - - try { - printJob.print(); - } - catch (java.awt.print.PrinterException ex) { - ex.printStackTrace(); - } - - } - - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/NullPaper.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/NullPaper.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/NullPaper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/NullPaper.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,176 +21,27 @@ * questions. */ -/* - @test - @bug 4199506 - @summary java.awt.print.PageFormat.setpaper(Paper paper) - assertion test fails by not throwing - NullPointerException when a null paper instance is - passed as argument and this is specified in the doc. - @run main NullPaper -*/ - - -//*** global search and replace NullPaper with name of the test *** - -/** - * NullPaper.java - * - * summary: java.awt.print.PageFormat.setpaper(Paper paper) - assertion test fails by not throwing - NullPointerException when a null paper instance is - passed as argument and this is specified in the doc. +import java.awt.print.PageFormat; +/* + * @test + * @bug 4199506 + * @summary Verify PageFormat.setPaper(null) throws NullPointerException + * as specified + * @run main NullPaper */ - -import java.awt.print.*; - -// This test is a "main" test as applets would need Runtime permission -// "queuePrintJob". - -public class NullPaper { - - private static void init() - { - boolean settingNullWorked = false; - - try { - /* Setting the paper to null should throw an exception. - * The bug was the exception was not being thrown. - */ - new PageFormat().setPaper(null); - settingNullWorked = true; - - /* If the test succeeds we'll end up here, so write - * to standard out. - */ - } catch (NullPointerException e) { - pass(); - - /* The test failed if we end up here because an exception - * other than the one we were expecting was thrown. - */ - } catch (Exception e) { - fail("Instead of the expected NullPointerException, '" + e + "' was thrown."); - } - - if (settingNullWorked) { - fail("The expected NullPointerException was not thrown"); - } - - }//End init() - - - /***************************************************** - Standard Test Machinery Section - DO NOT modify anything in this section -- it's a - standard chunk of code which has all of the - synchronisation necessary for the test harness. - By keeping it the same in all tests, it is easier - to read and understand someone else's test, as - well as insuring that all tests behave correctly - with the test harness. - There is a section following this for test-defined - classes - ******************************************************/ - private static boolean theTestPassed = false; - private static boolean testGeneratedInterrupt = false; - private static String failureMessage = ""; - - private static Thread mainThread = null; - - private static int sleepTime = 300000; - - public static void main( String args[] ) throws InterruptedException - { - mainThread = Thread.currentThread(); - try - { - init(); - } - catch( TestPassedException e ) - { - //The test passed, so just return from main and harness will - // interepret this return as a pass - return; - } - //At this point, neither test passed nor test failed has been - // called -- either would have thrown an exception and ended the - // test, so we know we have multiple threads. - - //Test involves other threads, so sleep and wait for them to - // called pass() or fail() - try - { - Thread.sleep( sleepTime ); - //Timed out, so fail the test - throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); - } - catch (InterruptedException e) - { - if( ! testGeneratedInterrupt ) throw e; - - //reset flag in case hit this code more than once for some reason (just safety) - testGeneratedInterrupt = false; - if ( theTestPassed == false ) - { - throw new RuntimeException( failureMessage ); - } - } - - }//main - - public static synchronized void setTimeoutTo( int seconds ) - { - sleepTime = seconds * 1000; - } - - public static synchronized void pass() - { - System.out.println( "The test passed." ); - //first check if this is executing in main thread - if ( mainThread == Thread.currentThread() ) - { - //Still in the main thread, so set the flag just for kicks, - // and throw a test passed exception which will be caught - // and end the test. - theTestPassed = true; - throw new TestPassedException(); - } - //pass was called from a different thread, so set the flag and interrupt - // the main thead. - theTestPassed = true; - testGeneratedInterrupt = true; - mainThread.interrupt(); - }//pass() - - public static synchronized void fail() - { - //test writer didn't specify why test failed, so give generic - fail( "it just plain failed! :-)" ); +public final class NullPaper { + public static void main(String[] args) { + try { + /* Setting the paper to null should throw an exception. + * The bug was the exception was not being thrown. + */ + new PageFormat().setPaper(null); + + throw new RuntimeException("NullPointerException is expected " + + "but not thrown"); + } catch (NullPointerException e) { + System.out.println("NullPointerException caught - test passes"); + } } - - public static synchronized void fail( String whyFailed ) - { - System.out.println( "The test failed: " + whyFailed ); - //check if this called from main thread - if ( mainThread == Thread.currentThread() ) - { - //If main thread, fail now 'cause not sleeping - throw new RuntimeException( whyFailed ); - } - theTestPassed = false; - testGeneratedInterrupt = true; - failureMessage = whyFailed; - mainThread.interrupt(); - }//fail() - - }// class NullPaper - -//This exception is used to exit from any level of call nesting -// when it's determined that the test has passed, and immediately -// end the test. -class TestPassedException extends RuntimeException - { - } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/Orient.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/Orient.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/Orient.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/Orient.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,64 +21,47 @@ * questions. */ -/* - @test - @bug 4236095 - @summary Confirm that the you get three pages of output, one - each in portrait, landscape, and reverse landscape - orientations. - @key printer - @run main/manual Orient -*/ - - -//*** global search and replace Orient with name of the test *** +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Ellipse2D; +import java.awt.print.Book; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; -/** - * Orient.java - * - * summary: +/* + * @test + * @bug 4236095 + * @summary Confirm that you get three pages of output, one + * each in portrait, landscape and reverse landscape + * orientations. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @key printer + * @run main/manual Orient */ - -import java.awt.*; -import java.awt.event.*; -import java.awt.geom.*; -import java.awt.print.*; - -// This test is a "main" test as applets would need Runtime permission -// "queuePrintJob". - public class Orient implements Printable { + private static final String INSTRUCTIONS = + """ + This test will automatically initiate a print. + + A passing test will print three pages each containing a large oval + with the text describing the orientation: PORTRAIT, LANDSCAPE + or REVERSE_LANDSCAPE, inside of it. The first page will + be emitted in portrait orientation, the second page in landscape + orientation and the third page in reverse-landscape orientation. - private static void init() - { - //*** Create instructions for the user here *** - - String[] instructions = - { - "On-screen inspection is not possible for this printing-specific", - "test therefore its only output is three printed pages.", - "To be able to run this test it is required to have a default", - "printer configured in your user environment.", - "", - "Visual inspection of the printed page is needed. A passing", - "test will print three pages each containing a large oval ", - "with the text describing the orientation: PORTRAIT, LANDSCAPE", - "or REVERSE_LANDSCAPE, inside of it. The first page will ", - "be emitted in portait orientation, the second page in landscape ", - "orientation and the third page in reverse-landscape orientation. ", - "On each page the oval will be wholly within the imageable area ", - "of the page. In a failing test the oval on the third page ", - "will be clipped against the imageable area.", - "Axes will indicate the direction of increasing X and Y" - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); + On each page the oval will be wholly within the imageable area of the page. + Axes will indicate the direction of increasing X and Y. - PrinterJob pjob = PrinterJob.getPrinterJob(); + Test failed if the oval on the page clipped against the imageable area. + """; + private static void printOrientationJob() throws PrinterException { + PrinterJob pjob = PrinterJob.getPrinterJob(); Book book = new Book(); - // Page 1 PageFormat portrait = pjob.defaultPage(); portrait.setOrientation(PageFormat.PORTRAIT); @@ -95,366 +78,47 @@ book.append(new Orient(), reverseLandscape); pjob.setPageable(book); - try { - pjob.print(); - } catch (PrinterException e) { - e.printStackTrace(); - } - }//End init() + pjob.print(); + } + @Override public int print(Graphics g, PageFormat pf, int pageIndex) { - - Graphics2D g2d = (Graphics2D)g; + Graphics2D g2d = (Graphics2D) g; g2d.translate(pf.getImageableX(), pf.getImageableY()); drawGraphics(g2d, pf); return Printable.PAGE_EXISTS; } void drawGraphics(Graphics2D g, PageFormat pf) { - double iw = pf.getImageableWidth(); - double ih = pf.getImageableHeight(); - + String orientation = switch (pf.getOrientation()) { + case PageFormat.PORTRAIT -> "PORTRAIT"; + case PageFormat.LANDSCAPE -> "LANDSCAPE"; + case PageFormat.REVERSE_LANDSCAPE -> "REVERSE_LANDSCAPE"; + default -> "INVALID"; + }; g.setColor(Color.black); - String orientation; - switch (pf.getOrientation()) { - case PageFormat.PORTRAIT : orientation = "PORTRAIT"; - break; - case PageFormat.LANDSCAPE : orientation = "LANDSCAPE"; - break; - case PageFormat.REVERSE_LANDSCAPE : - orientation = "REVERSE_LANDSCAPE"; - break; - default : orientation = "INVALID"; - } g.drawString(orientation, 100, 300); - g.draw(new Ellipse2D.Double(0, 0, iw, ih)); - g.drawString("(0,0)", 5,15); - g.drawLine(0,0,300,0); - g.drawString("X", 300,15); - g.drawLine(0,0,0,300); - g.drawString("Y",5,300); - } - - - /***************************************************** - Standard Test Machinery Section - DO NOT modify anything in this section -- it's a - standard chunk of code which has all of the - synchronisation necessary for the test harness. - By keeping it the same in all tests, it is easier - to read and understand someone else's test, as - well as insuring that all tests behave correctly - with the test harness. - There is a section following this for test-defined - classes - ******************************************************/ - private static boolean theTestPassed = false; - private static boolean testGeneratedInterrupt = false; - private static String failureMessage = ""; - - private static Thread mainThread = null; - - private static int sleepTime = 300000; - - public static void main( String args[] ) throws InterruptedException - { - mainThread = Thread.currentThread(); - try - { - init(); - } - catch( TestPassedException e ) - { - //The test passed, so just return from main and harness will - // interepret this return as a pass - return; - } - //At this point, neither test passed nor test failed has been - // called -- either would have thrown an exception and ended the - // test, so we know we have multiple threads. - - //Test involves other threads, so sleep and wait for them to - // called pass() or fail() - try - { - Thread.sleep( sleepTime ); - //Timed out, so fail the test - throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); - } - catch (InterruptedException e) - { - if( ! testGeneratedInterrupt ) throw e; - - //reset flag in case hit this code more than once for some reason (just safety) - testGeneratedInterrupt = false; - if ( theTestPassed == false ) - { - throw new RuntimeException( failureMessage ); - } - } - - }//main - - public static synchronized void setTimeoutTo( int seconds ) - { - sleepTime = seconds * 1000; + g.draw(new Ellipse2D.Double(0, 0, + pf.getImageableWidth(), pf.getImageableHeight())); + g.drawString("(0,0)", 5, 15); + g.drawLine(0, 0, 300, 0); + g.drawString("X", 300, 15); + g.drawLine(0, 0, 0, 300); + g.drawString("Y", 5, 300); } - public static synchronized void pass() - { - Sysout.println( "The test passed." ); - Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); - //first check if this is executing in main thread - if ( mainThread == Thread.currentThread() ) - { - //Still in the main thread, so set the flag just for kicks, - // and throw a test passed exception which will be caught - // and end the test. - theTestPassed = true; - throw new TestPassedException(); - } - //pass was called from a different thread, so set the flag and interrupt - // the main thead. - theTestPassed = true; - testGeneratedInterrupt = true; - mainThread.interrupt(); - }//pass() - - public static synchronized void fail() - { - //test writer didn't specify why test failed, so give generic - fail( "it just plain failed! :-)" ); - } - - public static synchronized void fail( String whyFailed ) - { - Sysout.println( "The test failed: " + whyFailed ); - Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); - //check if this called from main thread - if ( mainThread == Thread.currentThread() ) - { - //If main thread, fail now 'cause not sleeping - throw new RuntimeException( whyFailed ); - } - theTestPassed = false; - testGeneratedInterrupt = true; - failureMessage = whyFailed; - mainThread.interrupt(); - }//fail() - - }// class Orient - -//This exception is used to exit from any level of call nesting -// when it's determined that the test has passed, and immediately -// end the test. -class TestPassedException extends RuntimeException - { - } - -//*********** End Standard Test Machinery Section ********** - - -//************ Begin classes defined for the test **************** - -// make listeners in a class defined here, and instantiate them in init() - -/* Example of a class which may be written as part of a test -class NewClass implements anInterface - { - static int newVar = 0; - - public void eventDispatched(AWTEvent e) - { - //Counting events to see if we get enough - eventCount++; - - if( eventCount == 20 ) - { - //got enough events, so pass - - Orient.pass(); - } - else if( tries == 20 ) - { - //tried too many times without getting enough events so fail - - Orient.fail(); - } - - }// eventDispatched() - - }// NewClass class - -*/ - - -//************** End classes defined for the test ******************* - - - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog implements ActionListener - { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - Panel buttonP = new Panel(); - Button passB = new Button( "pass" ); - Button failB = new Button( "fail" ); - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - passB = new Button( "pass" ); - passB.setActionCommand( "pass" ); - passB.addActionListener( this ); - buttonP.add( "East", passB ); - - failB = new Button( "fail" ); - failB.setActionCommand( "fail" ); - failB.addActionListener( this ); - buttonP.add( "West", failB ); - - add( "South", buttonP ); - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } + public static void main(String args[]) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } - //catch presses of the passed and failed buttons. - //simply call the standard pass() or fail() static methods of - //Orient - public void actionPerformed( ActionEvent e ) - { - if( e.getActionCommand() == "pass" ) - { - Orient.pass(); - } - else - { - Orient.fail(); - } + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); + printOrientationJob(); + passFailJFrame.awaitAndCheck(); } - - }// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/PageSetupDialog.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/PageSetupDialog.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/PageSetupDialog.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/PageSetupDialog.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,333 +21,224 @@ * questions. */ -/** +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.Color; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.awt.print.PageFormat; +import java.awt.print.Paper; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* * @test - * @bug 4197377 - * @bug 4299145 - * @bug 6358747 - * @bug 6574633 - * @summary Page setup dialog settings + * @bug 4197377 4299145 6358747 6574633 * @key printer + * @summary Page setup dialog settings + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PageSetupDialog */ - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; - public class PageSetupDialog extends Frame implements Printable { - - PrinterJob myPrinterJob; - PageFormat myPageFormat; - Label pw, ph, pglm, pgiw, pgrm, pgtm, pgih, pgbm; - Label myWidthLabel; - Label myHeightLabel; - Label myImageableXLabel; - Label myImageableYLabel; - Label myImageableRightLabel; - Label myImageableBottomLabel; - Label myImageableWidthLabel; - Label myImageableHeightLabel; - Label myOrientationLabel; - Checkbox reverseCB; - boolean alpha = false; - boolean reverse = false; - - protected void displayPageFormatAttributes() { - - myWidthLabel.setText("Format Width = " + (float)myPageFormat.getWidth()); - myHeightLabel.setText("Format Height = " + (float)myPageFormat.getHeight()); - myImageableXLabel.setText - ("Format Left Margin = " + (float)myPageFormat.getImageableX()); - myImageableRightLabel.setText - ("Format Right Margin = " + (float)(myPageFormat.getWidth() - - (myPageFormat.getImageableX() + myPageFormat.getImageableWidth()))); - myImageableWidthLabel.setText - ("Format ImageableWidth = " + (float)myPageFormat.getImageableWidth()); - myImageableYLabel.setText - ("Format Top Margin = " + (float)myPageFormat.getImageableY()); - myImageableBottomLabel.setText - ("Format Bottom Margin = " + (float)(myPageFormat.getHeight() - - (myPageFormat.getImageableY() + myPageFormat.getImageableHeight()))); - myImageableHeightLabel.setText - ("Format ImageableHeight = " + (float)myPageFormat.getImageableHeight()); - int o = myPageFormat.getOrientation(); - if (o == PageFormat.LANDSCAPE && reverse) { - o = PageFormat.REVERSE_LANDSCAPE; - myPageFormat.setOrientation(PageFormat.REVERSE_LANDSCAPE); - } else if (o == PageFormat.REVERSE_LANDSCAPE && !reverse) { - o = PageFormat.LANDSCAPE; - myPageFormat.setOrientation(PageFormat.LANDSCAPE); - } - myOrientationLabel.setText - ("Format Orientation = " + - (o == PageFormat.PORTRAIT ? "PORTRAIT" : - o == PageFormat.LANDSCAPE ? "LANDSCAPE" : - o == PageFormat.REVERSE_LANDSCAPE ? "REVERSE_LANDSCAPE" : - "")); - Paper p = myPageFormat.getPaper(); - pw.setText("Paper Width = " + (float)p.getWidth()); - ph.setText("Paper Height = " + (float)p.getHeight()); - pglm.setText("Paper Left Margin = " + (float)p.getImageableX()); - pgiw.setText("Paper Imageable Width = " + (float)p.getImageableWidth()); - pgrm.setText("Paper Right Margin = " + - (float)(p.getWidth() - (p.getImageableX()+p.getImageableWidth()))); - pgtm.setText("Paper Top Margin = " + (float)p.getImageableY()); - pgih.setText("Paper Imageable Height = " + (float)p.getImageableHeight()); - pgbm.setText("Paper Bottom Margin = " + - (float)(p.getHeight() - (p.getImageableY()+p.getImageableHeight()))); - } - - public PageSetupDialog() { - super ("Page Dialog Test"); - myPrinterJob = PrinterJob.getPrinterJob(); - myPageFormat = new PageFormat(); - Paper p = new Paper(); - double margin = 1.5*72; - p.setImageableArea(margin, margin, - p.getWidth()-2*margin, p.getHeight()-2*margin); - myPageFormat.setPaper(p); - Panel c = new Panel(); - c.setLayout (new GridLayout (9, 2, 0, 0)); - c.add (reverseCB = new Checkbox("reverse if landscape")); - c.add (myOrientationLabel = new Label()); - c.add (myWidthLabel = new Label()); - c.add (pw = new Label()); - c.add (myImageableXLabel = new Label()); - c.add (pglm = new Label()); - c.add (myImageableRightLabel = new Label()); - c.add (pgrm = new Label()); - c.add (myImageableWidthLabel = new Label()); - c.add (pgiw = new Label()); - c.add (myHeightLabel = new Label()); - c.add (ph = new Label()); - c.add (myImageableYLabel = new Label()); - c.add (pgtm = new Label()); - c.add (myImageableHeightLabel = new Label()); - c.add (pgih = new Label()); - c.add (myImageableBottomLabel = new Label()); - c.add (pgbm = new Label()); - - reverseCB.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - reverse = e.getStateChange() == ItemEvent.SELECTED; - int o = myPageFormat.getOrientation(); - if (o == PageFormat.LANDSCAPE || - o == PageFormat.REVERSE_LANDSCAPE) { - displayPageFormatAttributes(); - } + PrinterJob myPrinterJob; + PageFormat myPageFormat; + Label pw, ph, pglm, pgiw, pgrm, pgtm, pgih, pgbm; + Label myWidthLabel; + Label myHeightLabel; + Label myImageableXLabel; + Label myImageableYLabel; + Label myImageableRightLabel; + Label myImageableBottomLabel; + Label myImageableWidthLabel; + Label myImageableHeightLabel; + Label myOrientationLabel; + Checkbox reverseCB; + boolean alpha = false; + boolean reverse = false; + + private static final String INSTRUCTIONS = + " This test is very flexible and requires much interaction.\n" + + " If the platform print dialog supports it, adjust orientation\n" + + " and margins and print pages and compare the results with the request."; + + protected void displayPageFormatAttributes() { + myWidthLabel.setText("Format Width = " + myPageFormat.getWidth()); + myHeightLabel.setText("Format Height = " + myPageFormat.getHeight()); + myImageableXLabel.setText("Format Left Margin = " + + myPageFormat.getImageableX()); + myImageableRightLabel.setText("Format Right Margin = " + + (myPageFormat.getWidth() + - (myPageFormat.getImageableX() + myPageFormat.getImageableWidth()))); + myImageableWidthLabel.setText("Format ImageableWidth = " + + myPageFormat.getImageableWidth()); + myImageableYLabel.setText("Format Top Margin = " + + myPageFormat.getImageableY()); + myImageableBottomLabel.setText("Format Bottom Margin = " + + (myPageFormat.getHeight() + - (myPageFormat.getImageableY() + myPageFormat.getImageableHeight()))); + myImageableHeightLabel.setText("Format ImageableHeight = " + + myPageFormat.getImageableHeight()); + int o = myPageFormat.getOrientation(); + if (o == PageFormat.LANDSCAPE && reverse) { + o = PageFormat.REVERSE_LANDSCAPE; + myPageFormat.setOrientation(PageFormat.REVERSE_LANDSCAPE); + } else if (o == PageFormat.REVERSE_LANDSCAPE && !reverse) { + o = PageFormat.LANDSCAPE; + myPageFormat.setOrientation(PageFormat.LANDSCAPE); + } + myOrientationLabel.setText + ("Format Orientation = " + + (switch (o) { + case PageFormat.PORTRAIT -> "PORTRAIT"; + case PageFormat.LANDSCAPE -> "LANDSCAPE"; + case PageFormat.REVERSE_LANDSCAPE -> "REVERSE_LANDSCAPE"; + default -> ""; + })); + Paper p = myPageFormat.getPaper(); + pw.setText("Paper Width = " + p.getWidth()); + ph.setText("Paper Height = " + p.getHeight()); + pglm.setText("Paper Left Margin = " + p.getImageableX()); + pgiw.setText("Paper Imageable Width = " + p.getImageableWidth()); + pgrm.setText("Paper Right Margin = " + + (p.getWidth() + - (p.getImageableX() + p.getImageableWidth()))); + pgtm.setText("Paper Top Margin = " + p.getImageableY()); + pgih.setText("Paper Imageable Height = " + p.getImageableHeight()); + pgbm.setText("Paper Bottom Margin = " + + (p.getHeight() + - (p.getImageableY() + p.getImageableHeight()))); + } + + public PageSetupDialog() { + super("Page Dialog Test"); + myPrinterJob = PrinterJob.getPrinterJob(); + myPageFormat = new PageFormat(); + Paper p = new Paper(); + double margin = 1.5 * 72; + p.setImageableArea(margin, margin, + p.getWidth() - 2 * margin, p.getHeight() - 2 * margin); + myPageFormat.setPaper(p); + Panel c = new Panel(); + c.setLayout(new GridLayout(9, 2, 0, 0)); + c.add(reverseCB = new Checkbox("reverse if landscape")); + c.add(myOrientationLabel = new Label()); + c.add(myWidthLabel = new Label()); + c.add(pw = new Label()); + c.add(myImageableXLabel = new Label()); + c.add(pglm = new Label()); + c.add(myImageableRightLabel = new Label()); + c.add(pgrm = new Label()); + c.add(myImageableWidthLabel = new Label()); + c.add(pgiw = new Label()); + c.add(myHeightLabel = new Label()); + c.add(ph = new Label()); + c.add(myImageableYLabel = new Label()); + c.add(pgtm = new Label()); + c.add(myImageableHeightLabel = new Label()); + c.add(pgih = new Label()); + c.add(myImageableBottomLabel = new Label()); + c.add(pgbm = new Label()); + + reverseCB.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent e) { + reverse = e.getStateChange() == ItemEvent.SELECTED; + int o = myPageFormat.getOrientation(); + if (o == PageFormat.LANDSCAPE || + o == PageFormat.REVERSE_LANDSCAPE) { + displayPageFormatAttributes(); } - }); + } + }); - add("Center", c); - displayPageFormatAttributes(); - Panel panel = new Panel(); - Button pageButton = new Button ("Page Setup..."); - pageButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - myPageFormat = myPrinterJob.pageDialog (myPageFormat); - displayPageFormatAttributes(); + add("Center", c); + displayPageFormatAttributes(); + Panel panel = new Panel(); + Button pageButton = new Button("Page Setup..."); + pageButton.addActionListener(e -> { + myPageFormat = myPrinterJob.pageDialog(myPageFormat); + displayPageFormatAttributes(); + }); + Button printButton = new Button("Print ..."); + printButton.addActionListener(e -> { + if (myPrinterJob.printDialog()) { + myPrinterJob.setPrintable(PageSetupDialog.this, myPageFormat); + alpha = false; + try { + myPrinterJob.print(); + } catch (PrinterException pe) { + pe.printStackTrace(); + PassFailJFrame.forceFail("Test failed because of PrinterException"); } - }); - Button printButton = new Button ("Print ..."); - printButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - try { - if (myPrinterJob.printDialog()) { - myPrinterJob.setPrintable(PageSetupDialog.this, - myPageFormat); - alpha = false; - myPrinterJob.print(); - } - } catch (PrinterException pe ) { - } + } + }); + Button printAlphaButton = new Button("Print w/Alpha..."); + printAlphaButton.addActionListener(e -> { + if (myPrinterJob.printDialog()) { + myPrinterJob.setPrintable(PageSetupDialog.this, myPageFormat); + alpha = true; + try { + myPrinterJob.print(); + } catch (PrinterException pe) { + pe.printStackTrace(); + PassFailJFrame.forceFail("Test failed because of PrinterException"); } - }); - Button printAlphaButton = new Button ("Print w/Alpha..."); - printAlphaButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - try { - if (myPrinterJob.printDialog()) { - myPrinterJob.setPrintable(PageSetupDialog.this, - myPageFormat); - alpha = true; - myPrinterJob.print(); - } - } catch (PrinterException pe ) { - } - } - }); - panel.add (pageButton); - panel.add (printButton); - panel.add (printAlphaButton); - add("South", panel); - addWindowListener (new WindowAdapter() { - public void windowClosing (WindowEvent e) { - dispose(); - System.exit (0); - } - - }); - //setSize (280, 550); - pack(); - setVisible (true); - } - - public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { - - if (pageIndex > 0) { - return Printable.NO_SUCH_PAGE; - } - - Graphics2D g2d = (Graphics2D)graphics; - g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); - g2d.drawString("ORIGIN("+pageFormat.getImageableX()+","+ - pageFormat.getImageableY()+")", 20, 20); - g2d.drawString("X THIS WAY", 200, 50); - g2d.drawString("Y THIS WAY", 60 , 200); - g2d.drawString("Graphics is " + g2d.getClass().getName(), 100, 100); - g2d.drawRect(0,0,(int)pageFormat.getImageableWidth(), - (int)pageFormat.getImageableHeight()); - if (alpha) { - g2d.setColor(new Color(0,0,255,192)); - } else { - g2d.setColor(Color.blue); - } - g2d.drawRect(1,1,(int)pageFormat.getImageableWidth()-2, - (int)pageFormat.getImageableHeight()-2); - - return Printable.PAGE_EXISTS; - } - - public static void main( String[] args) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test is very flexible and requires much interaction.", - "If the platform print dialog supports it, adjust orientation", - "and margins and print pages and compare the results with the", - "request." - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - new PageSetupDialog(); - } - -} - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); + } + }); + panel.add(pageButton); + panel.add(printButton); + panel.add(printAlphaButton); + add("South", panel); + pack(); + } + + @Override + public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { + if (pageIndex > 0) { + return Printable.NO_SUCH_PAGE; + } + + Graphics2D g2d = (Graphics2D) graphics; + g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); + g2d.drawString("ORIGIN(" + pageFormat.getImageableX() + "," + + pageFormat.getImageableY() + ")", 20, 20); + g2d.drawString("X THIS WAY", 200, 50); + g2d.drawString("Y THIS WAY", 60, 200); + g2d.drawString("Graphics is " + g2d.getClass().getName(), 100, 100); + g2d.drawRect(0, 0, + (int) pageFormat.getImageableWidth(), + (int) pageFormat.getImageableHeight()); + if (alpha) { + g2d.setColor(new Color(0, 0, 255, 192)); + } else { + g2d.setColor(Color.blue); + } + g2d.drawRect(1, 1, + (int) pageFormat.getImageableWidth() - 2, + (int) pageFormat.getImageableHeight() - 2); + + return Printable.PAGE_EXISTS; + } + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .testUI(PageSetupDialog::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/SetOrient.html openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/SetOrient.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ - - - - - - - SetOrient - - - -This test prints two pages and sends them to the printer. -One page is in PORTRAIT orientation and the other is in LANDSCAPE -orientation. On each page it draws an ellipse inscribed in the clip -boundary established by the PrinterJob. The ellipse should fill the -page within the bounds established by the default margins and not -extend off any end or side of the page. Also, the string "Portrait" -or "Landscape" should be oriented correctly. - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/SetOrient.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PageFormat/SetOrient.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PageFormat/SetOrient.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,56 +21,96 @@ * questions. */ -/** - * @bug 4186119: setting orientation does not affect printer +/* + * @test + * @key printer + * @bug 4186119 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Confirm that the clip and transform of the Graphics2D is * affected by the landscape orientation of the PageFormat. - * @run applet/manual=yesno SetOrient.html + * @run main/manual SetOrient */ -import java.awt.*; -import java.awt.geom.*; -import java.awt.print.*; -import java.applet.Applet; - -public class SetOrient extends Applet implements Printable { - PrinterJob pjob; - - public void init() { - pjob = PrinterJob.getPrinterJob(); - - Book book = new Book(); - PageFormat pf = pjob.defaultPage(); - pf.setOrientation(PageFormat.PORTRAIT); - book.append(this, pf); - pf = pjob.defaultPage(); - pf.setOrientation(PageFormat.LANDSCAPE); - book.append(this, pf); - pjob.setPageable(book); - - try { - pjob.print(); - } catch (PrinterException e) { - throw new RuntimeException(e.getMessage()); - } - } - - public int print(Graphics g, PageFormat pf, int pageIndex) { - Graphics2D g2d = (Graphics2D)g; - drawGraphics(g2d, pf); - return Printable.PAGE_EXISTS; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Ellipse2D; +import java.awt.print.Book; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import javax.swing.JButton; + +public class SetOrient { + private static final String INSTRUCTIONS = + """ + This test prints two pages and sends them to the printer. + One page is in PORTRAIT orientation and the other is in LANDSCAPE + orientation. On each page it draws an ellipse inscribed in the clip + boundary established by the PrinterJob. The ellipse should fill the + page within the bounds established by the default margins and not + extend off any end or side of the page. Also, the string "Portrait" + or "Landscape" should be oriented correctly. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("SetOrient Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .splitUIBottom(SetOrient::createAndShowGUI) + .build() + .awaitAndCheck(); } - void drawGraphics(Graphics2D g, PageFormat pf) { - double ix = pf.getImageableX(); - double iy = pf.getImageableY(); - double iw = pf.getImageableWidth(); - double ih = pf.getImageableHeight(); - - g.setColor(Color.black); - g.drawString(((pf.getOrientation() == PageFormat.PORTRAIT) - ? "Portrait" : "Landscape"), - (int) (ix+iw/2), (int) (iy+ih/2)); - g.draw(new Ellipse2D.Double(ix, iy, iw, ih)); + public static JButton createAndShowGUI() { + JButton btn = new JButton("PRINT"); + btn.addActionListener(e -> { + PrinterJob pjob = PrinterJob.getPrinterJob(); + + Printable p = new Printable() { + public int print(Graphics g, PageFormat pf, int pageIndex) { + Graphics2D g2d = (Graphics2D)g; + drawGraphics(g2d, pf); + return Printable.PAGE_EXISTS; + } + + void drawGraphics(Graphics2D g, PageFormat pf) { + double ix = pf.getImageableX(); + double iy = pf.getImageableY(); + double iw = pf.getImageableWidth(); + double ih = pf.getImageableHeight(); + + g.setColor(Color.black); + g.drawString(((pf.getOrientation() == PageFormat.PORTRAIT) + ? "Portrait" : "Landscape"), + (int) (ix + iw / 2), (int) (iy + ih / 2)); + g.draw(new Ellipse2D.Double(ix, iy, iw, ih)); + } + }; + + Book book = new Book(); + PageFormat pf = pjob.defaultPage(); + pf.setOrientation(PageFormat.PORTRAIT); + book.append(p, pf); + pf = pjob.defaultPage(); + pf.setOrientation(PageFormat.LANDSCAPE); + book.append(p, pf); + pjob.setPageable(book); + + try { + pjob.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + PassFailJFrame.forceFail(msg); + } + }); + return btn; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/Cancel/PrinterJobCancel.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Cancel/PrinterJobCancel.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/Cancel/PrinterJobCancel.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Cancel/PrinterJobCancel.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,218 +21,98 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterAbortException; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* * @test * @bug 4245280 - * @summary PrinterJob not cancelled when PrinterJob.cancel() is used * @key printer + * @summary PrinterJob not cancelled when PrinterJob.cancel() is used + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrinterJobCancel */ - -import java.awt.* ; -import java.awt.print.* ; - public class PrinterJobCancel extends Thread implements Printable { + private final PrinterJob pj; + private final boolean okayed; + private static final String INSTRUCTIONS = + "Test that print job cancellation works.\n\n" + + "This test starts after clicking OK / Print button.\n" + + "While the print job is in progress, the test automatically cancels it.\n" + + "The test will complete automatically."; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); + + PrinterJobCancel pjc = new PrinterJobCancel(); + if (pjc.okayed) { + pjc.start(); + Thread.sleep(5000); + pjc.pj.cancel(); + } else { + PassFailJFrame.forceFail("User cancelled printing"); + } + passFailJFrame.awaitAndCheck(); + } + + public PrinterJobCancel() { + pj = PrinterJob.getPrinterJob(); + pj.setPrintable(this); + okayed = pj.printDialog(); + } + + public void run() { + boolean cancelWorked = false; + try { + pj.print(); + } catch (PrinterAbortException paex) { + cancelWorked = true; + System.out.println("Job was properly cancelled and we"); + System.out.println("got the expected PrintAbortException"); + PassFailJFrame.forcePass(); + } catch (PrinterException prex) { + prex.printStackTrace(); + PassFailJFrame.forceFail("Unexpected PrinterException caught:" + prex.getMessage()); + } finally { + System.out.println("DONE PRINTING"); + if (!cancelWorked) { + PassFailJFrame.forceFail("Didn't get the expected PrintAbortException"); + } + } + } + + @Override + public int print(Graphics g, PageFormat pagef, int pidx) { + if (pidx > 5) { + return (Printable.NO_SUCH_PAGE); + } + + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pagef.getImageableX(), pagef.getImageableY()); + g2d.setColor(Color.black); + g2d.drawString(("This is page" + (pidx + 1)), 60, 80); + // Need to slow things down a bit .. important not to try this + // on the event dispatching thread of course. + try { + Thread.sleep(2000); + } catch (InterruptedException ignored) { + } - PrinterJob pj ; - boolean okayed; - - public static void main ( String args[] ) { - - String[] instructions = - { - "Test that print job cancellation works.", - "You must have a printer available to perform this test.", - "This test silently starts a print job and while the job is", - "still being printed, cancels the print job", - "You should see a message on System.out that the job", - "was properly cancelled.", - "You will need to kill the application manually since regression", - "tests apparently aren't supposed to call System.exit()" - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrinterJobCancel pjc = new PrinterJobCancel() ; - - if (pjc.okayed) { - pjc.start(); - try { - Thread.sleep(5000); - pjc.pj.cancel(); - } catch ( InterruptedException e ) { - } - } - } - - public PrinterJobCancel() { - - pj = PrinterJob.getPrinterJob() ; - pj.setPrintable(this); - okayed = pj.printDialog(); - } - - public void run() { - boolean cancelWorked = false; - try { - pj.print() ; + return Printable.PAGE_EXISTS; } - catch ( PrinterAbortException paex ) { - cancelWorked = true; - System.out.println("Job was properly cancelled and we"); - System.out.println("got the expected PrintAbortException"); - } - catch ( PrinterException prex ) { - System.out.println("This is wrong .. we shouldn't be here"); - System.out.println("Looks like a test failure"); - prex.printStackTrace() ; - //throw prex; - } - finally { - System.out.println("DONE PRINTING"); - if (!cancelWorked) { - System.out.println("Looks like the test failed - we didn't get"); - System.out.println("the expected PrintAbortException "); - } - } - //System.exit(0); - } - - public int print(Graphics g, PageFormat pagef, int pidx) { - - if (pidx > 5) { - return( Printable.NO_SUCH_PAGE ) ; - } - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pagef.getImageableX(), pagef.getImageableY()); - g2d.setColor(Color.black); - - g2d.drawString(("This is page"+(pidx+1)), 60 , 80); - // Need to slow things down a bit .. important not to try this - // on the event dispathching thread of course. - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - } - - return ( Printable.PAGE_EXISTS ); - } - } - - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/Collate2DPrintingTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Collate2DPrintingTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/Collate2DPrintingTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/Collate2DPrintingTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,63 +21,90 @@ * questions. */ -/** +import java.awt.Graphics; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.io.InputStream; +import java.io.Reader; + +import javax.print.Doc; +import javax.print.DocFlavor; +import javax.print.DocPrintJob; +import javax.print.PrintException; +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import javax.print.attribute.DocAttributeSet; +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.print.attribute.standard.Copies; +import javax.print.attribute.standard.SheetCollate; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; + +/* * @test * @bug 6362683 8012381 * @summary Collation should work. * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual Collate2DPrintingTest */ -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; -import javax.print.attribute.standard.*; -import javax.print.attribute.*; -import javax.print.*; -import java.io.*; - -public class Collate2DPrintingTest - extends Frame implements Doc, Printable, ActionListener { - - Button print2D = new Button("2D Print"); - Button printMerlin = new Button("PrintService"); - PrinterJob pj = PrinterJob.getPrinterJob(); - PrintService defService = null; +public class Collate2DPrintingTest implements Doc, Printable { + private static JComponent createTestUI() { HashPrintRequestAttributeSet prSet = new HashPrintRequestAttributeSet(); + PrintService defService = PrintServiceLookup.lookupDefaultPrintService(); + prSet.add(SheetCollate.COLLATED); + prSet.add(new Copies(2)); - public Collate2DPrintingTest() { - - Panel butPanel = new Panel(); - butPanel.add(print2D); - butPanel.add(printMerlin); - print2D.addActionListener(this); - printMerlin.addActionListener(this); - addWindowListener (new WindowAdapter() { - public void windowClosing (WindowEvent e) { - dispose(); + JButton print2D = new JButton("2D Print"); + print2D.addActionListener((ae) -> { + try { + PrinterJob pj = PrinterJob.getPrinterJob(); + pj.setPrintable(new Collate2DPrintingTest()); + if (pj.printDialog(prSet)) { + pj.print(prSet); + } + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(print2D, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); } }); - add("South", butPanel); - defService = PrintServiceLookup.lookupDefaultPrintService(); - PrintService[] pservice; - if (defService == null) { - pservice = PrintServiceLookup.lookupPrintServices(null, null); - if (pservice.length == 0) { - throw new RuntimeException("No printer found. TEST ABORTED"); + JButton printMerlin = new JButton("PrintService"); + printMerlin.addActionListener((ae) -> { + try { + DocPrintJob pj = defService.createPrintJob(); + pj.print(new Collate2DPrintingTest(), prSet); + } catch (PrintException ex) { + ex.printStackTrace(); + String msg = "PrintException: " + ex.getMessage(); + JOptionPane.showMessageDialog(printMerlin, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); } - defService = pservice[0]; - } - prSet.add(SheetCollate.COLLATED); - prSet.add(new Copies(2)); - pj.setPrintable(Collate2DPrintingTest.this); - setSize(300, 200); - setVisible(true); - } + }); + Box main = Box.createVerticalBox(); + main.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + main.add(Box.createVerticalGlue()); + main.add(print2D); + main.add(Box.createVerticalStrut(4)); + main.add(printMerlin); + main.add(Box.createVerticalGlue()); + return main; + } + @Override public int print(Graphics g, PageFormat pf, int pageIndex) - throws PrinterException { + throws PrinterException { g.drawString("Page: " + pageIndex, 100, 100); if (pageIndex == 2) { return Printable.NO_SUCH_PAGE; @@ -86,168 +113,51 @@ } } - public void actionPerformed (ActionEvent ae) { - try { - if (ae.getSource() == print2D) { - if (pj.printDialog(prSet)) { - pj.print(prSet); - } - } else { - DocPrintJob pj = defService.createPrintJob(); - pj.print(this, prSet); - } - System.out.println ("DONE"); - } catch (Exception e) { - e.printStackTrace(); - } - } - + @Override public DocAttributeSet getAttributes() { return null; } + @Override public DocFlavor getDocFlavor() { - DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; - return flavor; + return DocFlavor.SERVICE_FORMATTED.PRINTABLE; } + @Override public Object getPrintData() { return this; } + @Override public Reader getReaderForText() { return null; } + @Override public InputStream getStreamForBytes() { return null; } - public static void main( String[] args) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "The print result should be collated." - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - new Collate2DPrintingTest(); - } -} - - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() + private static final String INSTRUCTIONS = + "Click on the '2D Print' button.\n" + + "Choose copies as '2' with 'Collated' checkbox and Print\n" + + "\n" + + "Click on the 'PrintService', should get a print from default printer\n" + + "\n" + + "If you get only one copy or non 'Collated' prints from any of the above cases, " + + "test failed"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .splitUI(Collate2DPrintingTest::createTestUI) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); } - - }// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/DrawImage.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawImage.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/DrawImage.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawImage.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,262 +21,119 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.geom.AffineTransform; +import java.awt.image.BufferedImage; +import java.awt.image.BufferedImageOp; +import java.awt.image.RescaleOp; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* * @test * @bug 4329866 * @key printer * @summary Confirm that no printing exception is generated. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual DrawImage */ +public class DrawImage { + private static final int OBJECT_BORDER = 15; -import java.util.*; -import java.text.*; -import java.io.*; -import java.net.*; -import java.awt.*; -import java.awt.font.*; -import java.awt.geom.*; -import java.awt.print.*; -import java.awt.event.*; -import java.awt.image.*; -import java.awt.image.renderable.*; -import javax.swing.*; -import javax.swing.text.*; -import javax.swing.border.*; -import javax.swing.event.*; - -public class DrawImage -{ - protected static final double _hwBorder = 72 / 4; // 1/4 inch - protected static final double _border = 72 / 4; // 1/4 inch - protected static final int _objectBorder = 15; - protected static final int _verticalGap = 20; - protected static final int _textIndent = 150; - - protected BufferedImage _image; + private static final String INSTRUCTIONS = + "This test will automatically initiate a print\n\n" + + "Test passes if you get a printout of a gray rectangle\n" + + "with white text without any exception."; - protected PageFormat _pageFormat; + private final BufferedImage image; + private final PageFormat pageFormat; - public DrawImage(BufferedImage image) { - _image = image; + private DrawImage(BufferedImage image) { + this.image = image; PrinterJob pj = PrinterJob.getPrinterJob(); - _pageFormat = pj.defaultPage(); - - } + pageFormat = pj.defaultPage(); + } + private int printImage(Graphics g, PageFormat pf, int pageIndex) { + if (pageIndex > 0) { + return Printable.NO_SUCH_PAGE; + } - protected int printImage(Graphics g, PageFormat pf, BufferedImage image) { - Graphics2D g2D = (Graphics2D)g; - g2D.transform(new AffineTransform(_pageFormat.getMatrix())); + int paperW = (int) pageFormat.getImageableWidth(); + int paperH = (int) pageFormat.getImageableHeight(); + int x = (int) pageFormat.getImageableX(); + int y = (int) pageFormat.getImageableY(); + + // Make the image slightly smaller (25) than max possible width + float scaleFactor = ((float) ((paperW - 25) - OBJECT_BORDER - OBJECT_BORDER) + / (float) (image.getWidth())); - int paperW = (int)pf.getImageableWidth(), paperH = - (int)pf.getImageableHeight(); + BufferedImageOp scaleOp = new RescaleOp(scaleFactor, 0, null); - int x = (int)pf.getImageableX(), y = (int)pf.getImageableY(); + Graphics2D g2D = (Graphics2D) g; + g2D.transform(new AffineTransform(pageFormat.getMatrix())); g2D.setClip(x, y, paperW, paperH); + g2D.drawImage(image, scaleOp, x + OBJECT_BORDER, y + OBJECT_BORDER); - // print images - if (image != null ) { - int imageH = image.getHeight(), imageW = image.getWidth(); - // make slightly smaller (25) than max possible width - float scaleFactor = ((float)((paperW - 25) - _objectBorder - - _objectBorder) / (float)(imageW)); - int scaledW = (int)(imageW * scaleFactor), - scaledH = (int)(imageH *scaleFactor); - BufferedImageOp scaleOp = new RescaleOp(scaleFactor, 0, null); - g2D.drawImage(image, scaleOp, x + _objectBorder, y + _objectBorder); - y += _objectBorder + scaledH + _objectBorder; - return Printable.PAGE_EXISTS; - } - else { - return Printable.NO_SUCH_PAGE; - } + return Printable.PAGE_EXISTS; } - public void print() { - try { - final PrinterJob pj = PrinterJob.getPrinterJob(); - pj.setJobName("Print Image"); - pj.setPrintable(new Printable() { - public int print(Graphics g, PageFormat pf, int pageIndex) { - int result = NO_SUCH_PAGE; - if (pageIndex == 0) { - result = printImage(g, _pageFormat, _image); - } - return result; - } - }); - if (pj.printDialog()) { - try { pj.print(); } - catch (PrinterException e) { - System.out.println(e); - } - } - - } - catch (Exception e) { - e.printStackTrace(System.out); + private void print() throws PrinterException { + final PrinterJob pj = PrinterJob.getPrinterJob(); + pj.setJobName("Print Image"); + pj.setPrintable(this::printImage); + if (pj.printDialog()) { + pj.print(); + } else { + PassFailJFrame.forceFail("User cancelled printing"); } } - public static void main(String[] args) { - String[] instructions = - { - "You must have a printer available to perform this test.", - "The test passes if you get a printout of a gray rectangle", - "with white text without any exception." - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } BufferedImage image = prepareFrontImage(); + + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); + DrawImage pt = new DrawImage(image); pt.print(); - // System.exit(0); + passFailJFrame.awaitAndCheck(); } - - - public static BufferedImage prepareFrontImage() { + private static BufferedImage prepareFrontImage() { // build my own test images BufferedImage result = new BufferedImage(400, 200, - BufferedImage.TYPE_BYTE_GRAY); + BufferedImage.TYPE_BYTE_GRAY); + int w = result.getWidth(); + int h = result.getHeight(); - Graphics2D g2D = (Graphics2D)result.getGraphics(); + Graphics2D g2D = (Graphics2D) result.getGraphics(); g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); - int w = result.getWidth(), h = result.getHeight(); - g2D.setColor(Color.gray); g2D.fill(new Rectangle(0, 0, w, h)); - g2D.setColor(Color.white); - AffineTransform original = g2D.getTransform(); - AffineTransform originXform = AffineTransform.getTranslateInstance(w / -5, h / 5); + AffineTransform originXform = AffineTransform.getTranslateInstance( + w / 5.0, h / 5.0); g2D.transform(originXform); - - g2D.drawString("Front Side", 20, h / 2); + g2D.dispose(); return result; } - - } - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/DrawStringMethods.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawStringMethods.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/DrawStringMethods.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/DrawStringMethods.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,31 +21,46 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.font.FontRenderContext; +import java.awt.print.Book; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterJob; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +/* * @test * @bug 4185019 * @key printer * @summary Confirm that all of the drawString methods on Graphics2D * work for printer graphics objects. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual DrawStringMethods */ - -import java.awt.*; -import java.text.*; -import java.awt.font.*; -import java.awt.print.*; - public class DrawStringMethods implements Printable { + private static final String INSTRUCTIONS = + " This test will automatically initiate a print.\n" + + "\n" + + " Confirm that the following methods are printed:\n" + + " For Graphics: drawString, drawString, drawChars, drawBytes\n" + + " For Graphics2D: drawString, drawString, drawGlyphVector"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } - public static void main(String args[]) { - String[] instructions = - { - "Confirm that the methods are printed.", - " For Graphics: drawString, drawString, drawChars, drawBytes", - " For Graphics2D: drawString, drawString, drawGlyphVector" - }; - Sysout.createDialogWithInstructions( instructions ); - + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); PrinterJob pjob = PrinterJob.getPrinterJob(); PageFormat pf = pjob.defaultPage(); @@ -53,18 +68,16 @@ book.append(new DrawStringMethods(), pf); pjob.setPageable(book); + pjob.print(); - try { - pjob.print(); - } catch (PrinterException e) { - throw new RuntimeException(e.getMessage()); - } + passFailJFrame.awaitAndCheck(); } - public static AttributedCharacterIterator getIterator(String s) { + private static AttributedCharacterIterator getIterator(String s) { return new AttributedString(s).getIterator(); } + @Override public int print(Graphics g, PageFormat pf, int pageIndex) { int ix = (int) pf.getImageableX(); int iy = (int) pf.getImageableY(); @@ -93,7 +106,7 @@ iy += 30; s = "drawBytes(byte data[], int offset, int length, int x, int y)"; - byte data[] = new byte[s.length()]; + byte[] data = new byte[s.length()]; for (int i = 0; i < data.length; i++) { data[i] = (byte) s.charAt(i); } @@ -116,7 +129,7 @@ iy += 30; s = "drawString(AttributedCharacterIterator iterator, "+ - "float x, float y)"; + "float x, float y)"; g.drawLine(ix, iy, ix+10, iy); g2d.drawString(getIterator(s), (float) ix+20, (float) iy); @@ -133,119 +146,3 @@ return PAGE_EXISTS; } } - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog - { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("South", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/InvalidPage.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/InvalidPage.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/InvalidPage.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/InvalidPage.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,223 +21,118 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PageFormat; +import java.awt.print.Paper; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JOptionPane; + +/* * @test InvalidPage.java * @bug 4671634 6506286 * @summary Invalid page format can crash win32 JRE * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual InvalidPage */ - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; - -public class InvalidPage extends Frame implements Printable { - - PrinterJob pJob; - PageFormat pf; - - public InvalidPage() { - super ("Validate Page Test"); - pJob = PrinterJob.getPrinterJob(); - pf = pJob.defaultPage(); - Paper p = pf.getPaper(); - p.setImageableArea(0,0,p.getWidth(), p.getHeight()); - pf.setPaper(p); - setLayout(new FlowLayout()); - Panel panel = new Panel(); - Button printButton = new Button ("Print"); - printButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - try { - if (pJob.printDialog()) { - pJob.setPrintable(InvalidPage.this, pf); - pJob.print(); - } - } catch (PrinterException pe ) { - } +public class InvalidPage implements Printable { + private static JComponent createTestUI() { + JButton b = new JButton("Print"); + b.addActionListener((ae) -> { + try { + PrinterJob job = PrinterJob.getPrinterJob(); + PageFormat pf = job.defaultPage(); + Paper p = pf.getPaper(); + p.setImageableArea(0, 0, p.getWidth(), p.getHeight()); + pf.setPaper(p); + job.setPrintable(new InvalidPage(), pf); + if (job.printDialog()) { + job.print(); } - }); - panel.add (printButton); - add(panel); - - addWindowListener (new WindowAdapter() { - public void windowClosing (WindowEvent e) { - dispose(); - System.exit (0); - } - - }); - setSize (200, 200); - setVisible (true); - } - - public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { - - if (pageIndex > 1) { - return Printable.NO_SUCH_PAGE; - } - - Graphics2D g2d = (Graphics2D)graphics; - - g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); - g2d.drawString("ORIGIN", 30, 30); - g2d.drawString("X THIS WAY", 200, 50); - g2d.drawString("Y THIS WAY", 60 , 200); - g2d.drawRect(0,0,(int)pageFormat.getImageableWidth(), - (int)pageFormat.getImageableHeight()); - if (pageIndex == 0) { - g2d.setColor(Color.black); - } else { - g2d.setColor(new Color(0,0,0,128)); - } - g2d.drawRect(1,1,(int)pageFormat.getImageableWidth()-2, - (int)pageFormat.getImageableHeight()-2); - - g2d.drawLine(0,0, - (int)pageFormat.getImageableWidth(), - (int)pageFormat.getImageableHeight()); - g2d.drawLine((int)pageFormat.getImageableWidth(),0, - 0,(int)pageFormat.getImageableHeight()); - return Printable.PAGE_EXISTS; - } - - public static void main( String[] args) { - String[] instructions = - { - "You must have a printer available to perform this test", - "Press the print button, which brings up a print dialog and", - "in the dialog select a printer and press the print button", - "in the dialog. Repeat for as many printers as you have installed", - "On solaris and linux just one printer is sufficient", - "Collect the output and examine it, each print job has two pages", - "of very similar output, except that the 2nd page of the job may", - "appear in a different colour, and the output near the edge of", - "the page may be clipped. This is OK. Hold up both pieces of paper", - "to the light and confirm that the lines and text (where present)", - "are positioned identically on both pages", - "The test fails if the JRE crashes, or if the output from the two", - "pages of a job is aligned differently" - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - new InvalidPage(); - } - -} - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + JOptionPane.showMessageDialog(b, msg, "Error occurred", + JOptionPane.ERROR_MESSAGE); + PassFailJFrame.forceFail(msg); + } + }); + + Box main = Box.createHorizontalBox(); + main.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); + main.add(Box.createHorizontalGlue()); + main.add(b); + main.add(Box.createHorizontalGlue()); + return main; } - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } + @Override + public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { + if (pageIndex > 1) { + return Printable.NO_SUCH_PAGE; + } + + Graphics2D g2d = (Graphics2D) graphics; + g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); + g2d.drawString("ORIGIN", 30, 30); + g2d.drawString("X THIS WAY", 200, 50); + g2d.drawString("Y THIS WAY", 60, 200); + g2d.drawRect(0, 0, + (int) pageFormat.getImageableWidth(), + (int) pageFormat.getImageableHeight()); + if (pageIndex == 0) { + g2d.setColor(Color.black); + } else { + g2d.setColor(new Color(0, 0, 0, 128)); + } + g2d.drawRect(1, 1, + (int) pageFormat.getImageableWidth() - 2, + (int) pageFormat.getImageableHeight() - 2); + g2d.drawLine(0, 0, + (int) pageFormat.getImageableWidth(), + (int) pageFormat.getImageableHeight()); + g2d.drawLine((int) pageFormat.getImageableWidth(), 0, + 0, (int) pageFormat.getImageableHeight()); - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); + return Printable.PAGE_EXISTS; } -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + private static final String INSTRUCTIONS = + " Press the print button, which brings up a print dialog.\n" + + " In the dialog select a printer and press the print button.\n\n" + + " Repeat for all the printers as you have installed\n" + + " On Solaris and Linux just one printer is sufficient.\n\n" + + " Collect the output and examine it, each print job has two pages\n" + + " of very similar output, except that the 2nd page of the job may\n" + + " appear in a different colour, and the output near the edge of\n" + + " the page may be clipped. This is OK. Hold up both pieces of paper\n" + + " to the light and confirm that the lines and text (where present)\n" + + " are positioned identically on both pages\n\n" + + " The test fails if the output from the two\n" + + " pages of a job is aligned differently"; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .splitUI(InvalidPage::createTestUI) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); } - - }// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/JobName/PrinterJobName.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/JobName/PrinterJobName.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/JobName/PrinterJobName.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/JobName/PrinterJobName.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,173 +21,55 @@ * questions. */ -/** +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterJob; + +/* * @test * @bug 4205601 * @summary setJobName should be used by PrinterJob * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual PrinterJobName */ - -import java.awt.*; -import java.awt.print.*; - public class PrinterJobName implements Printable { + private static final String THE_NAME = "Testing the Job name setting"; + private static final String INSTRUCTIONS = + "This test prints a page with a banner/job name of\n\n" + + THE_NAME; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); + + PrinterJob job = PrinterJob.getPrinterJob(); + job.setJobName(THE_NAME); + job.setPrintable(new PrinterJobName()); + job.print(); + passFailJFrame.awaitAndCheck(); + } - static String theName = "Testing the Jobname setting"; - - public static void main(String[] args) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test prints a page with a banner/job name of", - theName - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrinterJob job = PrinterJob.getPrinterJob(); - job.setJobName(theName); - job.setPrintable(new PrinterJobName()); - try { - job.print(); - System.out.println("PRINTING DONE."); - } - catch (Exception exc) { - System.out.println("Printer Exception"); - } - } - - + @Override public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - if (pgIndex > 0 ) { - return Printable.NO_SUCH_PAGE; - } - - double iw = pgFmt.getImageableWidth(); - double ih = pgFmt.getImageableHeight(); - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - g2d.drawString("Name is: "+theName,20,20 ); - return Printable.PAGE_EXISTS; + if (pgIndex > 0) { + return Printable.NO_SUCH_PAGE; + } + + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + g2d.drawString("Name is: " + THE_NAME, 20, 20); + return Printable.PAGE_EXISTS; } - } - - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/NumCopies.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/NumCopies.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/NumCopies.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/NumCopies.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,169 +21,56 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.Graphics; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* * @test * @bug 4258003 * @summary Checks the right number of copies are printed * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual NumCopies */ - -import java.awt.*; -import java.awt.print.*; - public class NumCopies implements Printable { - - - public static void main(String[] args) { - - String[] instructions = - { - "You must have a printer available to perform this test", - "This test should print a total of four pages which are two", - " copies of each of two pages which consist of the text :-", - "'This is page number N', where N is 0 and 1.", - "The pages should be uncollated." - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - PrinterJob job = PrinterJob.getPrinterJob(); - job.setCopies(2); - job.setPrintable(new NumCopies()); - try { + private static final String INSTRUCTIONS = + "This test should print four pages, which are \n" + + "two copies of each page with the text :-\n" + + "'This is page number N', where N is 0 and 1.\n" + + "The pages should be uncollated."; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); + + PrinterJob job = PrinterJob.getPrinterJob(); + job.setCopies(2); + job.setPrintable(new NumCopies()); job.print(); + passFailJFrame.awaitAndCheck(); } - catch (Exception exc) { - System.out.println("Printer Exception"); - } - } - - public int print(Graphics g, PageFormat pf, int pageIndex) - throws PrinterException { - if (pageIndex > 1) { - return NO_SUCH_PAGE; + @Override + public int print(Graphics g, PageFormat pf, int pageIndex) + throws PrinterException { + if (pageIndex > 1) { + return NO_SUCH_PAGE; + } + g.translate((int) pf.getImageableX(), (int) pf.getImageableY()); + g.setColor(Color.black); + g.drawString("This is page number " + pageIndex, 50, 50); + return PAGE_EXISTS; } - g.translate((int)pf.getImageableX(), (int)pf.getImageableY()); - g.setColor(Color.black); - g.drawString("This is page number " + Integer.toString(pageIndex), 50, 50); - return PAGE_EXISTS ; - } - } - -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - - }// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintAllFonts.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintAllFonts.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintAllFonts.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintAllFonts.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,55 +21,63 @@ * questions. */ -/** - * - * test +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GraphicsEnvironment; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterJob; + +/* + * @test * @bug 4884389 7183516 * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Font specified with face name loses style on printing * @run main/manual PrintAllFonts */ - -import java.awt.*; -import java.awt.print.*; -import java.awt.GraphicsEnvironment; - public class PrintAllFonts implements Printable { + private static final int LINE_HEIGHT = 18; + private static final int FONT_SIZE = 14; - static Font[] allFonts; - int fontNum = 0; - int startNum = 0; - int lineHeight = 18; - boolean done = false; - int thisPage = 0; - + private final Font[] allFonts = + GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); + private int fontNum = 0; + private int startNum = 0; + private int thisPage = 0; + + private static final String INSTRUCTIONS = + "This bug is system dependent and is not always reproducible.\n" + + "Font names will be printed in two columns.\n" + + "First column non synthesised and second column with synthesised italic.\n" + + "A passing test will have all text printed with correct font style."; public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } - String[] instructions = - { - "You must have a printer available to perform this test and should use Win 98.", - "This bug is system dependent and is not always reproducible.", - " ", - "A passing test will have all text printed with correct font style.", - }; - - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - GraphicsEnvironment ge = - GraphicsEnvironment.getLocalGraphicsEnvironment(); - allFonts = ge.getAllFonts(); + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build(); PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new PrintAllFonts()); if (pj.printDialog()) { - pj.print(); + pj.print(); + } else { + PassFailJFrame.forceFail("User cancelled printing"); } + passFailJFrame.awaitAndCheck(); } + @Override public int print(Graphics g, PageFormat pf, int pageIndex) { - if (fontNum >= allFonts.length && pageIndex > thisPage) { return NO_SUCH_PAGE; } @@ -79,18 +87,20 @@ } else { fontNum = startNum; } - g.setColor(Color.black); - int hgt = (int)pf.getImageableHeight(); - int fontsPerPage = hgt/lineHeight; - int x = (int)pf.getImageableX()+10; - int y = (int)pf.getImageableY()+lineHeight; + int fontsPerPage = (int) pf.getImageableHeight() / LINE_HEIGHT - 1; + int x = (int) pf.getImageableX() + 10; + int y = (int) pf.getImageableY() + LINE_HEIGHT; + g.setColor(Color.black); for (int n = 0; n < fontsPerPage; n++) { - Font f = allFonts[fontNum].deriveFont(Font.PLAIN, 16); + Font f = allFonts[fontNum].deriveFont(Font.PLAIN, FONT_SIZE); + Font fi = allFonts[fontNum].deriveFont(Font.ITALIC, FONT_SIZE); g.setFont(f); g.drawString(f.getFontName(), x, y); - y+= lineHeight; + g.setFont(fi); + g.drawString(f.getFontName(), (int) (x + pf.getImageableWidth() / 2), y); + y += LINE_HEIGHT; fontNum++; if (fontNum >= allFonts.length) { break; @@ -99,117 +109,3 @@ return PAGE_EXISTS; } } - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintNullString.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintNullString.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintNullString.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintNullString.java 2025-04-09 19:45:33.000000000 +0000 @@ -148,7 +148,7 @@ // API 3: null & empty drawString(Iterator, int, int); try { g2d.drawString(nullIterator, 20, 120); - g2d.drawString("FAILURE: No NPE for null iterator, float", 20, 120); + g2d.drawString("FAILURE: No NPE for null iterator, int", 20, 120); } catch (NullPointerException e) { g2d.drawString("caught expected NPE for null iterator, int", 20, 120); } @@ -169,7 +169,7 @@ } try { - g2d.drawString(emptyIterator, 20, 180); + g2d.drawString(emptyIterator, 20.0f, 180.0f); g2d.drawString("FAILURE: No IAE for empty iterator, float", 20, 180); } catch (IllegalArgumentException e) { g2d.drawString("caught expected IAE for empty iterator, float", 20, 180); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrintTextTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,193 +21,207 @@ * questions. */ -/** +/* * @test * @bug 6425068 7157659 8132890 * @key printer * @summary Confirm that text prints where we expect to the length we expect. - * @run main/manual=yesno PrintTextTest + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual PrintTextTest */ -import java.awt.*; -import java.awt.event.*; -import java.text.*; -import java.util.*; -import java.awt.font.*; -import java.awt.geom.*; -import java.awt.print.*; -import javax.swing.*; - -public class PrintTextTest extends Component implements Printable { - - static int preferredSize; - Font textFont; - AffineTransform gxTx; - String page; - boolean useFM; - - public static void main(String args[]) { - String[] instructions = - { - "This tests that printed text renders similarly to on-screen", - "under a variety of APIs and graphics and font transforms", - "Print to your preferred printer. Collect the output.", - "Refer to the onscreen buttons to cycle through the on-screen", - "content", - "For each page, confirm that the printed content corresponds to", - "the on-screen rendering for that *same* page.", - "Some cases may look odd but its intentional. Verify", - "it looks the same on screen and on the printer.", - "Note that text does not scale linearly from screen to printer", - "so some differences are normal and not a bug.", - "The easiest way to spot real problems is to check that", - "any underlines are the same length as the underlined text", - "and that any rotations are the same in each case.", - "Note that each on-screen page is printed in both portrait", - "and landscape mode", - "So for example, Page 1/Portrait, and Page 1/Landscape when", - "rotated to view properly, should both match Page 1 on screen.", - }; - Sysout.createDialogWithInstructions(instructions); +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.RenderingHints; +import java.awt.font.FontRenderContext; +import java.awt.font.GlyphVector; +import java.awt.font.TextLayout; +import java.awt.geom.AffineTransform; +import java.awt.geom.Point2D; +import java.awt.print.Book; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; +import java.util.HashMap; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JTabbedPane; + +public class PrintTextTest { + + static final String INSTRUCTIONS = """ + This tests that printed text renders similarly to on-screen under a variety + of APIs and graphics and font transforms. + 1. Print to your preferred printer. + 2. Collect the output. + 3. Refer to the onscreen buttons to cycle through the on-screen content. + 4. For each page, confirm that the printed content corresponds to the + on-screen rendering for that *same* page. Some cases may look odd but + its intentional. Verify it looks the same on screen and on the printer. + Note that text does not scale linearly from screen to printer so some + differences are normal and not a bug. + The easiest way to spot real problems is to check that any underlines are + the same length as the underlined text and that any rotations are the same + in each case. + Note that each on-screen page is printed in both portrait and landscape mode. + So for example, Page 1/Portrait, and Page 1/Landscape when rotated to view + properly, should both match Page 1 on screen. + """; + public static void main(String[] args) throws Exception { PrinterJob pjob = PrinterJob.getPrinterJob(); PageFormat portrait = pjob.defaultPage(); portrait.setOrientation(PageFormat.PORTRAIT); - preferredSize = (int)portrait.getImageableWidth(); + int preferredSize = (int) portrait.getImageableWidth(); PageFormat landscape = pjob.defaultPage(); landscape.setOrientation(PageFormat.LANDSCAPE); Book book = new Book(); - JTabbedPane p = new JTabbedPane(); + JTabbedPane pane = new JTabbedPane(); int page = 1; - Font font = new Font("Dialog", Font.PLAIN, 18); - String name = "Page " + new Integer(page++); - PrintTextTest ptt = new PrintTextTest(name, font, null, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); - - font = new Font("Dialog", Font.PLAIN, 18); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, null, true); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + Font font = new Font(Font.DIALOG, Font.PLAIN, 18); + String name = "Page " + page++; + PrintText pt = new PrintText(name, font, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); + + font = new Font(Font.DIALOG, Font.PLAIN, 18); + name = "Page " + page++; + pt = new PrintText(name, font, null, true, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); font = getPhysicalFont(); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, null, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintText(name, font, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); font = getPhysicalFont(); AffineTransform rotTx = AffineTransform.getRotateInstance(0.15); - rotTx.translate(60,0); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, rotTx, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + rotTx.translate(60, 0); + name = "Page " + page++; + pt = new PrintText(name, font, rotTx, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); - font = new Font("Dialog", Font.PLAIN, 18); + font = new Font(Font.DIALOG, Font.PLAIN, 18); AffineTransform scaleTx = AffineTransform.getScaleInstance(1.25, 1.25); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, scaleTx, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintText(name, font, scaleTx, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); - font = new Font("Dialog", Font.PLAIN, 18); + font = new Font(Font.DIALOG, Font.PLAIN, 18); scaleTx = AffineTransform.getScaleInstance(-1.25, 1.25); - scaleTx.translate(-preferredSize/1.25, 0); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, scaleTx, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + scaleTx.translate(-preferredSize / 1.25, 0); + name = "Page " + page++; + pt = new PrintText(name, font, scaleTx, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); - font = new Font("Dialog", Font.PLAIN, 18); + font = new Font(Font.DIALOG, Font.PLAIN, 18); scaleTx = AffineTransform.getScaleInstance(1.25, -1.25); - scaleTx.translate(0, -preferredSize/1.25); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, scaleTx, false); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + scaleTx.translate(0, -preferredSize / 1.25); + name = "Page " + page++; + pt = new PrintText(name, font, scaleTx, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); font = font.deriveFont(rotTx); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, null, false); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); - - font = new Font("Monospaced", Font.PLAIN, 12); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, font, null, false); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintText(name, font, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); + + font = new Font(Font.MONOSPACED, Font.PLAIN, 12); + name = "Page " + page++; + pt = new PrintText(name, font, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); Font xfont = font.deriveFont(AffineTransform.getScaleInstance(1.5, 1)); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, xfont, null, false); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintText(name, xfont, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); Font yfont = font.deriveFont(AffineTransform.getScaleInstance(1, 1.5)); - name = "Page " + new Integer(page++); - ptt = new PrintTextTest(name, yfont, null, false); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintText(name, yfont, null, false, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); if (System.getProperty("os.name").startsWith("Windows")) { font = new Font("MS Gothic", Font.PLAIN, 12); - name = "Page " + new Integer(page++); - ptt = new PrintJAText(name, font, null, true); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + name = "Page " + page++; + pt = new PrintJapaneseText(name, font, null, true, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); font = new Font("MS Gothic", Font.PLAIN, 12); - name = "Page " + new Integer(page++); + name = "Page " + page++; rotTx = AffineTransform.getRotateInstance(0.15); - ptt = new PrintJAText(name, font, rotTx, true); - p.add(ptt, BorderLayout.CENTER); - p.add(name, ptt); - book.append(ptt, portrait); - book.append(ptt, landscape); + pt = new PrintJapaneseText(name, font, rotTx, true, preferredSize); + pane.addTab(name, pt); + book.append(pt, portrait); + book.append(pt, landscape); } pjob.setPageable(book); - JFrame f = new JFrame(); - f.add(BorderLayout.CENTER, p); - f.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) {System.exit(0);} + JButton printButton = new JButton("Print"); + printButton.addActionListener(event -> { + try { + if (pjob.printDialog()) { + pjob.print(); + } + } catch (PrinterException e) { + throw new RuntimeException(e.getMessage(), e); + } }); + + JFrame f = new JFrame("PrintTextTest"); + f.add(BorderLayout.CENTER, pane); + f.add(BorderLayout.SOUTH, printButton); f.pack(); - f.show(); - try { - if (pjob.printDialog()) { - pjob.print(); - } - } catch (PrinterException e) { - throw new RuntimeException(e.getMessage()); - } + PassFailJFrame.builder() + .title("PrintTextTest") + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .columns(60) + .testUI(f) + .build() + .awaitAndCheck(); } // The test needs a physical font that supports Latin. @@ -221,338 +235,228 @@ String[] names = ge.getAvailableFontFamilyNames(); for (String n : names) { - switch (n.toLowerCase()) { - case "dialog": - case "dialoginput": - case "serif": - case "sansserif": - case "monospaced": - break; + switch (n) { + case Font.DIALOG: + case Font.DIALOG_INPUT: + case Font.SERIF: + case Font.SANS_SERIF: + case Font.MONOSPACED: + continue; default: Font f = new Font(n, Font.PLAIN, 18); if (f.canDisplayUpTo("AZaz09") == -1) { physicalFont = f; return f; } - } + } } physicalFont = new Font(Font.DIALOG, Font.PLAIN, 18); return physicalFont; } - public PrintTextTest(String page, Font font, AffineTransform gxTx, - boolean fm) { - this.page = page; - textFont = font; - this.gxTx = gxTx; - this.useFM = fm; - setBackground(Color.white); - } + private static class PrintText extends Component implements Printable { - public static AttributedCharacterIterator getIterator(String s) { - return new AttributedString(s).getIterator(); - } - - static String orient(PageFormat pf) { - if (pf.getOrientation() == PageFormat.PORTRAIT) { - return "Portrait"; - } else { - return "Landscape"; + protected final Font textFont; + protected final AffineTransform gxTx; + protected final String page; + protected final boolean useFM; + protected final int preferredSize; + + public PrintText(String page, Font font, AffineTransform gxTx, boolean fm, int size) { + this.page = page; + this.textFont = font; + this.gxTx = gxTx; + this.useFM = fm; + this.preferredSize = size; + setBackground(Color.WHITE); + } + + private static AttributedCharacterIterator getIterator(String s) { + return new AttributedString(s).getIterator(); + } + + private static String orient(PageFormat pf) { + if (pf.getOrientation() == PageFormat.PORTRAIT) { + return "Portrait"; + } else { + return "Landscape"; + } } - } - - public int print(Graphics g, PageFormat pf, int pageIndex) { - - Graphics2D g2d = (Graphics2D)g; - g2d.translate(pf.getImageableX(), pf.getImageableY()); - g.drawString(page+" "+orient(pf),50,20); - g.translate(0, 25); - paint(g); - return PAGE_EXISTS; - } - public Dimension getMinimumSize() { - return getPreferredSize(); - } - - public Dimension getPreferredSize() { - return new Dimension(preferredSize, preferredSize); - } - - public void paint(Graphics g) { - - /* fill with white before any transformation is applied */ - g.setColor(Color.white); - g.fillRect(0, 0, getSize().width, getSize().height); - - - Graphics2D g2d = (Graphics2D) g; - if (gxTx != null) { - g2d.transform(gxTx); - } - if (useFM) { - g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, - RenderingHints.VALUE_FRACTIONALMETRICS_ON); + @Override + public int print(Graphics g, PageFormat pf, int pageIndex) { + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pf.getImageableX(), pf.getImageableY()); + g.drawString(page + " " + orient(pf), 50, 20); + g.translate(0, 25); + paint(g); + return PAGE_EXISTS; } - g.setFont(textFont); - FontMetrics fm = g.getFontMetrics(); - - String s; - int LS = 30; - int ix=10, iy=LS+10; - g.setColor(Color.black); - - s = "drawString(String str, int x, int y)"; - g.drawString(s, ix, iy); - if (!textFont.isTransformed()) { - g.drawLine(ix, iy+1, ix+fm.stringWidth(s), iy+1); + @Override + public Dimension getMinimumSize() { + return getPreferredSize(); } - iy += LS; - s = "drawString(AttributedCharacterIterator iterator, int x, int y)"; - g.drawString(getIterator(s), ix, iy); - - iy += LS; - s = "\tdrawChars(\t\r\nchar[], int off, int len, int x, int y\t)"; - g.drawChars(s.toCharArray(), 0, s.length(), ix, iy); - if (!textFont.isTransformed()) { - g.drawLine(ix, iy+1, ix+fm.stringWidth(s), iy+1); + @Override + public Dimension getPreferredSize() { + return new Dimension(preferredSize, preferredSize); } - iy += LS; - s = "drawBytes(byte[], int off, int len, int x, int y)"; - byte data[] = new byte[s.length()]; - for (int i = 0; i < data.length; i++) { - data[i] = (byte) s.charAt(i); - } - g.drawBytes(data, 0, data.length, ix, iy); + @Override + public void paint(Graphics g) { - Font f = g2d.getFont(); - FontRenderContext frc = g2d.getFontRenderContext(); + g.setColor(Color.WHITE); + g.fillRect(0, 0, getSize().width, getSize().height); - iy += LS; - s = "drawString(String s, float x, float y)"; - g2d.drawString(s, (float) ix, (float) iy); - if (!textFont.isTransformed()) { - g.drawLine(ix, iy+1, ix+fm.stringWidth(s), iy+1); - } + Graphics2D g2d = (Graphics2D) g; + if (gxTx != null) { + g2d.transform(gxTx); + } + if (useFM) { + g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + } - iy += LS; - s = "drawString(AttributedCharacterIterator iterator, "+ - "float x, float y)"; - g2d.drawString(getIterator(s), (float) ix, (float) iy); + g.setFont(textFont); + FontMetrics fm = g.getFontMetrics(); - iy += LS; - s = "drawGlyphVector(GlyphVector g, float x, float y)"; - GlyphVector gv = f.createGlyphVector(frc, s); - g2d.drawGlyphVector(gv, ix, iy); - Point2D adv = gv.getGlyphPosition(gv.getNumGlyphs()); - if (!textFont.isTransformed()) { - g.drawLine(ix, iy+1, ix+(int)adv.getX(), iy+1); - } + String s; + int LS = 30; + int ix = 10, iy = LS + 10; + g.setColor(Color.BLACK); + + s = "drawString(String str, int x, int y)"; + g.drawString(s, ix, iy); + if (!textFont.isTransformed()) { + g.drawLine(ix, iy + 1, ix + fm.stringWidth(s), iy + 1); + } - iy += LS; - s = "GlyphVector with position adjustments"; + iy += LS; + s = "drawString(AttributedCharacterIterator iterator, int x, int y)"; + g.drawString(getIterator(s), ix, iy); + + iy += LS; + s = "\tdrawChars(\t\r\nchar[], int off, int len, int x, int y\t)"; + g.drawChars(s.toCharArray(), 0, s.length(), ix, iy); + if (!textFont.isTransformed()) { + g.drawLine(ix, iy + 1, ix + fm.stringWidth(s), iy + 1); + } - gv = f.createGlyphVector(frc, s); - int ng = gv.getNumGlyphs(); - adv = gv.getGlyphPosition(ng); - for (int i=0; i(), frc); + tl.draw(g2d, ix, iy); + + iy += LS; + s = "TextLayout 2: \u0924\u094d\u0930 \u0915\u0948\u0930\u0947 End."; + tl = new TextLayout(s, f, frc); + tl.draw(g2d, ix, iy); } } -} -class Sysout - { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } + private static class PrintJapaneseText extends PrintText { + public PrintJapaneseText(String page, Font font, AffineTransform gxTx, boolean fm, int size) { + super(page, font, gxTx, fm, size); + } - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } + private static final String TEXT = + "\u3042\u3044\u3046\u3048\u304a\u30a4\u30ed\u30cf" + + "\u30cb\u30db\u30d8\u30c8\u4e00\u4e01\u4e02\u4e05\uff08"; + @Override + public void paint(Graphics g) { - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } + g.setColor(Color.WHITE); + g.fillRect(0, 0, getSize().width, getSize().height); - }// Sysout class + Graphics2D g2d = (Graphics2D) g; + if (gxTx != null) { + g2d.transform(gxTx); + } + if (useFM) { + g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_ON); + } -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog - { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 20, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("South", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + String text = TEXT + TEXT + TEXT; + g.setColor(Color.BLACK); + int y = 20; + float origSize = 7f; + for (int i = 0; i < 11; i++) { + float size = origSize + (i * 0.1f); + g2d.translate(0, size + 6); + Font f = textFont.deriveFont(size); + g2d.setFont(f); + FontMetrics fontMetrics = g2d.getFontMetrics(); + int stringWidth = fontMetrics.stringWidth(text); + g.drawLine(0, y + 1, stringWidth, y + 1); + g.drawString(text, 0, y); + y += 10; + } + } } - -}// TestDialog class +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.html openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ - - - - - - PrinterDialogsModalityTest - - - -

    PrinterDialogsModalityTest
    Bug ID: 4784285 4785920

    - -

    See the dialog box (usually in upper left corner) for instructions

    - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest/PrinterDialogsModalityTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - test - @bug 4784285 4785920 - @key printer - @summary check whether Print- and Page- dialogs are modal and correct window activated after their closing - @run applet/manual=yesno PrinterDialogsModalityTest.html -*/ - -/** - * PrinterDialogsModalityTest.java - * - * summary: check whether Print- and Page- dialogs are modal and correct window activated after their closing - */ - -import java.applet.Applet; - -import java.awt.BorderLayout; -import java.awt.Button; -import java.awt.Dialog; -import java.awt.FlowLayout; -import java.awt.Frame; -import java.awt.TextArea; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import java.awt.print.PageFormat; -import java.awt.print.PrinterJob; - -public class PrinterDialogsModalityTest extends Applet -{ - //Declare things used in the test, like buttons and labels here - - public void init() - { - //Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - - String[] instructions = - { - "This is a Windows only test, for other platforms consider it passed", - "After test start you will see frame titled \"test Frame\"", - "with two buttons - \"Page Dialog\" and \"Print Dialog\"", - "1. make the frame active by clicking on title", - "2. press \"Page Dialog\" button, page dailog should popup", - "3. make sure page dialog is modal (if not test is failed)", - "4. close the dialog (either cancel it or press ok)", - "5. make sure the frame is still active (if not test is failed)", - "6. press \"Print Dialog\" button, print dialog should popup", - "7. repeat steps 3.-5.", - "", - "If you are able to execute all steps successfully then test is passed, else failed." - }; - Sysout.createDialogWithInstructions( instructions ); - - }//End init() - - public void start () - { - //Get things going. Request focus, set size, et cetera - setSize (200,200); - setVisible(true); - validate(); - - Button page = new Button("Page Dialog"); - page.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - PrinterJob prnJob = PrinterJob.getPrinterJob(); - prnJob.pageDialog(new PageFormat()); - } - }); - Button print = new Button("Print Dialog"); - print.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent e) { - PrinterJob prnJob = PrinterJob.getPrinterJob(); - prnJob.printDialog(); - } - }); - Frame frame = new Frame("Test Frame"); - frame.setLayout(new FlowLayout()); - frame.add(page); - frame.add(print); - frame.setLocation(200, 200); - frame.pack(); - frame.setVisible(true); - - }// start() - - //The rest of this class is the actions which perform the test... - - //Use Sysout.println to communicate with the user NOT System.out!! - //Sysout.println ("Something Happened!"); - -}// class PrinterDialogsModalityTest - -/* Place other classes related to the test after this line */ - - - - - -/**************************************************** - Standard Test Machinery - DO NOT modify anything below -- it's a standard - chunk of code whose purpose is to make user - interaction uniform, and thereby make it simpler - to read and understand someone else's test. - ****************************************************/ - -/** - This is part of the standard test machinery. - It creates a dialog (with the instructions), and is the interface - for sending text messages to the user. - To print the instructions, send an array of strings to Sysout.createDialog - WithInstructions method. Put one line of instructions per array entry. - To display a message for the tester to see, simply call Sysout.println - with the string to be displayed. - This mimics System.out.println but works within the test harness as well - as standalone. - */ - -class Sysout -{ - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/PrinterDialogsModalityTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Button; +import java.awt.FlowLayout; +import java.awt.print.PageFormat; +import java.awt.print.PrinterJob; + +import javax.swing.JFrame; + +/* + * @test + * @bug 4784285 4785920 5024549 + * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary check whether Print- and Page- dialogs are modal and correct window + * activated after their closing + * @run main/manual PrinterDialogsModalityTest + */ + +public class PrinterDialogsModalityTest { + private static final String INSTRUCTIONS = + """ + After the test starts, you will see a frame titled "Test Frame" + with two buttons: "Page Dialog" and "Print Dialog". + 1. Make the "Test Frame" active by clicking on title. + 2. Press "Page Dialog" button and a page dialog should popup. + 3. Make sure page dialog is modal. (Modal in this case means that + it blocks the user from interacting with other windows in the + same application, like this instruction window. You may still be + able to interact with unrelated applications on the desktop.). + 4. Close the dialog (either cancel it or press ok). + 5. Make sure the frame is still active. + 6. Press "Print Dialog" button, print dialog should popup. + 7. Repeat steps 3-5. + + If you are able to execute all steps successfully then the test + passes, otherwise it fails. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("PrinterDialogsModalityTest Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(PrinterDialogsModalityTest::createAndShowGUI) + .build() + .awaitAndCheck(); + } + + public static JFrame createAndShowGUI() { + JFrame frame = new JFrame("Test Frame"); + frame.setLayout(new FlowLayout()); + + Button page = new Button("Page Dialog"); + page.addActionListener(e -> { + PrinterJob prnJob = PrinterJob.getPrinterJob(); + prnJob.pageDialog(new PageFormat()); + }); + Button print = new Button("Print Dialog"); + print.addActionListener(e -> { + PrinterJob prnJob = PrinterJob.getPrinterJob(); + prnJob.printDialog(); + }); + frame.add(page); + frame.add(print); + frame.pack(); + return frame; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/ValidatePage/ValidatePage.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/ValidatePage/ValidatePage.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/ValidatePage/ValidatePage.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/ValidatePage/ValidatePage.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,407 +21,283 @@ * questions. */ -/** +import java.awt.Button; +import java.awt.Color; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.print.PageFormat; +import java.awt.print.Paper; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import javax.swing.JOptionPane; + +/* * @test * @bug 4252108 6229507 * @key printer * @summary PrinterJob.validatePage() is unimplemented. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual ValidatePage */ - -import java.awt.*; -import java.awt.event.*; -import java.awt.print.*; - public class ValidatePage extends Frame implements Printable { - -PrinterJob myPrinterJob; -PageFormat myPageFormat; -Label pw, ph, pglm, pgrm, pgiw, pgih, pgtm, pgbm; -TextField tpw, tph, tpglm, tpgtm, tpgiw, tpgih; -Label myWidthLabel; -Label myHeightLabel; -Label myImageableXLabel; -Label myImageableYLabel; -Label myImageableRightLabel; -Label myImageableBottomLabel; -Label myImageableWidthLabel; -Label myImageableHeightLabel; -Label myOrientationLabel; - - protected void displayPageFormatAttributes() { - myWidthLabel.setText ("Format Width = " + drnd(myPageFormat.getWidth())); - myHeightLabel.setText ("Format Height = " + drnd(myPageFormat.getHeight())); - myImageableXLabel.setText - ("Format Left Margin = " + drnd(myPageFormat.getImageableX())); - myImageableRightLabel.setText - ("Format Right Margin = " + drnd(myPageFormat.getWidth() - - (myPageFormat.getImageableX() + myPageFormat.getImageableWidth()))); - myImageableWidthLabel.setText - ("Format ImageableWidth = " + drnd(myPageFormat.getImageableWidth())); - myImageableYLabel.setText - ("Format Top Margin = " + drnd(myPageFormat.getImageableY())); - myImageableBottomLabel.setText - ("Format Bottom Margin = " + drnd(myPageFormat.getHeight() - - (myPageFormat.getImageableY() + myPageFormat.getImageableHeight()))); - myImageableHeightLabel.setText - ("Format ImageableHeight = " + drnd(myPageFormat.getImageableHeight())); - int o = myPageFormat.getOrientation(); - myOrientationLabel.setText - ("Format Orientation = " + - (o == PageFormat.PORTRAIT ? "PORTRAIT" : - o == PageFormat.LANDSCAPE ? "LANDSCAPE" : - o == PageFormat.REVERSE_LANDSCAPE ? "REVERSE_LANDSCAPE" : - "")); - Paper p = myPageFormat.getPaper(); - pw.setText("Paper Width = " + drnd(p.getWidth())); - ph.setText("Paper Height = " + drnd(p.getHeight())); - pglm.setText("Paper Left Margin = " + drnd(p.getImageableX())); - pgiw.setText("Paper Imageable Width = " + drnd(p.getImageableWidth())); - pgih.setText("Paper Imageable Height = " + drnd(p.getImageableHeight())); - - pgrm.setText("Paper Right Margin = " + - drnd(p.getWidth() - (p.getImageableX()+p.getImageableWidth()))); - pgtm.setText("Paper Top Margin = " + drnd(p.getImageableY())); - pgbm.setText("Paper Bottom Margin = " + - drnd(p.getHeight() - (p.getImageableY()+p.getImageableHeight()))); - } - - static String drnd(double d) { - d = d * 10.0 + 0.5; - d = Math.floor(d) /10.0; - String ds = Double.toString(d); - int decimal_pos = ds.indexOf("."); - int len = ds.length(); - if (len > decimal_pos+2) { - return ds.substring(0, decimal_pos+2); - } else { - return ds; - } - } - - public ValidatePage() { - super ("Validate Page Test"); - myPrinterJob = PrinterJob.getPrinterJob(); - myPageFormat = new PageFormat(); - Paper p = new Paper(); - p.setSize(28*72, 21.5 * 72); - myPageFormat.setPaper(p); - setLayout(new FlowLayout()); - Panel pfp = new Panel(); - pfp.setLayout (new GridLayout (9, 1, 0, 0)); - pfp.add (myOrientationLabel = new Label()); - pfp.add (myWidthLabel = new Label()); - pfp.add (myImageableXLabel = new Label()); - pfp.add (myImageableRightLabel = new Label()); - pfp.add (myImageableWidthLabel = new Label()); - pfp.add (myHeightLabel = new Label()); - pfp.add (myImageableYLabel = new Label()); - pfp.add (myImageableBottomLabel = new Label()); - pfp.add (myImageableHeightLabel = new Label()); - - add(pfp); - - Panel pp = new Panel(); - pp.setLayout (new GridLayout (8, 1, 0, 0)); - pp.add (pw = new Label()); - pp.add (pglm = new Label()); - pp.add (pgtm = new Label()); - pp.add (ph = new Label()); - pp.add (pgiw = new Label()); - pp.add (pgih = new Label()); - pp.add (pgrm = new Label()); - pp.add (pgbm = new Label()); - - add(pp); - - Panel epp = new Panel(); - epp.setLayout (new GridLayout (6, 2, 0, 0)); - - epp.add(new Label("Page width:")); - epp.add (tpw = new TextField()); - epp.add(new Label("Page height:")); - epp.add (tph = new TextField()); - epp.add(new Label("Left Margin:")); - epp.add (tpglm = new TextField()); - epp.add(new Label("Top margin:")); - epp.add (tpgtm = new TextField()); - epp.add(new Label("Imageable Wid:")); - epp.add (tpgiw = new TextField()); - epp.add(new Label("Imageable Hgt:")); - epp.add (tpgih = new TextField()); - - add(epp); - displayPageFormatAttributes(); - - Panel panel = new Panel(); - Button defButton = new Button ("Default Page"); - defButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - myPageFormat = myPrinterJob.defaultPage(); - displayPageFormatAttributes(); - } - }); - - Button pageButton = new Button ("Page Setup.."); - pageButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - myPageFormat = myPrinterJob.pageDialog (myPageFormat); - displayPageFormatAttributes(); - } - }); - Button printButton = new Button ("Print"); - printButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - try { - //if (myPrinterJob.printDialog()) { - myPrinterJob.setPrintable(ValidatePage.this, - myPageFormat); - myPrinterJob.print(); - // } - } catch (PrinterException pe ) { - } - } - }); - - Button chooseButton = new Button ("Printer.."); - chooseButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - myPrinterJob.printDialog(); - } - }); - - Button validateButton = new Button ("Validate Page"); - validateButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - myPageFormat = myPrinterJob.validatePage(myPageFormat); - displayPageFormatAttributes(); - } - }); - Button setButton = new Button ("Set Paper"); - setButton.addActionListener(new ActionListener() { - public void actionPerformed (ActionEvent e) { - try { - Paper p = new Paper(); - double pwid = Double.parseDouble(tpw.getText()); - double phgt = Double.parseDouble(tph.getText()); - double pimx = Double.parseDouble(tpglm.getText()); - double pimy = Double.parseDouble(tpgtm.getText()); - double pimwid = Double.parseDouble(tpgiw.getText()); - double pimhgt = Double.parseDouble(tpgih.getText()); - p.setSize(pwid, phgt); - p.setImageableArea(pimx, pimy, pimwid, pimhgt); - myPageFormat.setPaper(p); - displayPageFormatAttributes(); - } catch (NumberFormatException nfe) { - } - } - }); - panel.add (setButton); - panel.add (defButton); - panel.add (pageButton); - panel.add (chooseButton); - panel.add (validateButton); - panel.add (printButton); - add(panel); - TextArea ta = new TextArea(7, 60); - String ls = System.getProperty("line.Separator", "\n"); - ta.setText( - "When validating a page, the process is 1st to find the closest matching " + ls + - "paper size, next to make sure the requested imageable area fits within " + ls + - "the printer's imageable area for that paper size. Finally the top and " + ls + - "left margins will be shrunk if they are too great for the adjusted " + ls + - "imageable area to fit at that position. They will shrink by the minimum" + ls + - "needed to accomodate the imageable area."+ls+ls+ - "To test 6229507, put the minimum margins (all 0s) in Page Setup dialog."+ls+ - "Compare Imageable width, height, and margins of portrait against landscape."); - ta.setEditable(false); - add(ta); - - addWindowListener (new WindowAdapter() { - public void windowClosing (WindowEvent e) { - dispose(); - System.exit (0); - } - - }); - setSize (500, 630); - setVisible (true); - } - - public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { - - if (pageIndex > 0) { - return Printable.NO_SUCH_PAGE; - } - - Graphics2D g2d = (Graphics2D)graphics; - - int o = pageFormat.getOrientation(); - - System.out.println("Format Orientation = " + - (o == PageFormat.PORTRAIT ? "PORTRAIT" : - o == PageFormat.LANDSCAPE ? "LANDSCAPE" : - o == PageFormat.REVERSE_LANDSCAPE ? "REVERSE_LANDSCAPE" : - "")); - System.out.println(g2d.getTransform()); - System.out.println("ix="+pageFormat.getImageableX()+ - " iy="+pageFormat.getImageableY()); - g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); - g2d.drawString("ORIGIN", 20, 20); - g2d.drawString("X THIS WAY", 200, 50); - g2d.drawString("Y THIS WAY", 60 , 200); - g2d.drawRect(0,0,(int)pageFormat.getImageableWidth(), - (int)pageFormat.getImageableHeight()); - g2d.setColor(Color.blue); - g2d.drawRect(1,1,(int)pageFormat.getImageableWidth()-2, - (int)pageFormat.getImageableHeight()-2); - - return Printable.PAGE_EXISTS; - } - - public static void main( String[] args) { - String[] instructions = - { - "You must have a printer available to perform this test", - "This test is very flexible and requires much interaction.", - "There are several buttons.", - "Set Paper: if all fields are valid numbers it sets the Paper object.", - "This is used to create arbitrary nonsensical paper sizes to help", - "test validatePage.", - "Default Page: sets a default page. This should always be valid.", - "Page Setup: brings up the page dialog. You must OK this dialog", - "for it to have any effect. You can use this to set different size,", - "orientation and margins - which of course affect imageable area.", - "Printer: Used to set the current printer. Useful because current", - "printer affects the choice of paper sizes available.", - "You must OK this dialog for it to have any effect.", - "Validate Page:", - "The most important button in the test. By setting nonsensical", - "or valid papers with varying margins etc, this should always find", - "the closest", - "match within the limits of what is possible on the current printer.", - "Print: to the current printer. Not vital for this test.", - "request." - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - new ValidatePage(); - } - -} - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); + PrinterJob myPrinterJob; + PageFormat myPageFormat; + Label pw, ph, pglm, pgrm, pgiw, pgih, pgtm, pgbm; + TextField tpw, tph, tpglm, tpgtm, tpgiw, tpgih; + Label myWidthLabel; + Label myHeightLabel; + Label myImageableXLabel; + Label myImageableYLabel; + Label myImageableRightLabel; + Label myImageableBottomLabel; + Label myImageableWidthLabel; + Label myImageableHeightLabel; + Label myOrientationLabel; + + private static String getOrientation(int o) { + return switch (o) { + case PageFormat.PORTRAIT -> "PORTRAIT"; + case PageFormat.LANDSCAPE -> "LANDSCAPE"; + case PageFormat.REVERSE_LANDSCAPE -> "REVERSE_LANDSCAPE"; + default -> ""; + }; } - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); + private void displayPageFormatAttributes() { + myWidthLabel.setText("Format Width = " + drnd(myPageFormat.getWidth())); + myHeightLabel.setText("Format Height = " + drnd(myPageFormat.getHeight())); + myImageableXLabel.setText("Format Left Margin = " + drnd(myPageFormat.getImageableX())); + myImageableRightLabel.setText("Format Right Margin = " + + drnd(myPageFormat.getWidth() + - (myPageFormat.getImageableX() + myPageFormat.getImageableWidth()))); + myImageableWidthLabel.setText("Format ImageableWidth = " + + drnd(myPageFormat.getImageableWidth())); + myImageableYLabel.setText("Format Top Margin = " + + drnd(myPageFormat.getImageableY())); + myImageableBottomLabel.setText("Format Bottom Margin = " + + drnd(myPageFormat.getHeight() + - (myPageFormat.getImageableY() + myPageFormat.getImageableHeight()))); + myImageableHeightLabel.setText("Format ImageableHeight = " + + drnd(myPageFormat.getImageableHeight())); + myOrientationLabel.setText("Format Orientation = " + + getOrientation(myPageFormat.getOrientation())); + Paper p = myPageFormat.getPaper(); + pw.setText("Paper Width = " + drnd(p.getWidth())); + ph.setText("Paper Height = " + drnd(p.getHeight())); + pglm.setText("Paper Left Margin = " + drnd(p.getImageableX())); + pgiw.setText("Paper Imageable Width = " + drnd(p.getImageableWidth())); + pgih.setText("Paper Imageable Height = " + drnd(p.getImageableHeight())); + + pgrm.setText("Paper Right Margin = " + + drnd(p.getWidth() + - (p.getImageableX() + p.getImageableWidth()))); + pgtm.setText("Paper Top Margin = " + drnd(p.getImageableY())); + pgbm.setText("Paper Bottom Margin = " + + drnd(p.getHeight() + - (p.getImageableY() + p.getImageableHeight()))); } - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); + static String drnd(double d) { + return String.format("%.2f", d); } - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); + public ValidatePage() { + super("Validate Page Test"); + myPrinterJob = PrinterJob.getPrinterJob(); + myPageFormat = new PageFormat(); + Paper p = new Paper(); + p.setSize(28 * 72, 21.5 * 72); + myPageFormat.setPaper(p); + setLayout(new FlowLayout()); + Panel pfp = new Panel(); + pfp.setLayout(new GridLayout(9, 1, 0, 0)); + pfp.add(myOrientationLabel = new Label()); + pfp.add(myWidthLabel = new Label()); + pfp.add(myImageableXLabel = new Label()); + pfp.add(myImageableRightLabel = new Label()); + pfp.add(myImageableWidthLabel = new Label()); + pfp.add(myHeightLabel = new Label()); + pfp.add(myImageableYLabel = new Label()); + pfp.add(myImageableBottomLabel = new Label()); + pfp.add(myImageableHeightLabel = new Label()); + + add(pfp); + + Panel pp = new Panel(); + pp.setLayout(new GridLayout(8, 1, 0, 0)); + pp.add(pw = new Label()); + pp.add(pglm = new Label()); + pp.add(pgtm = new Label()); + pp.add(ph = new Label()); + pp.add(pgiw = new Label()); + pp.add(pgih = new Label()); + pp.add(pgrm = new Label()); + pp.add(pgbm = new Label()); + + add(pp); + + Panel epp = new Panel(); + epp.setLayout(new GridLayout(6, 2, 0, 0)); + + epp.add(new Label("Page width:")); + epp.add(tpw = new TextField()); + epp.add(new Label("Page height:")); + epp.add(tph = new TextField()); + epp.add(new Label("Left Margin:")); + epp.add(tpglm = new TextField()); + epp.add(new Label("Top margin:")); + epp.add(tpgtm = new TextField()); + epp.add(new Label("Imageable Wid:")); + epp.add(tpgiw = new TextField()); + epp.add(new Label("Imageable Hgt:")); + epp.add(tpgih = new TextField()); + + add(epp); + displayPageFormatAttributes(); + + Panel panel = new Panel(); + Button defButton = new Button("Default Page"); + defButton.addActionListener(e -> { + myPageFormat = myPrinterJob.defaultPage(); + displayPageFormatAttributes(); + }); + + Button pageButton = new Button("Page Setup..."); + pageButton.addActionListener(e -> { + myPageFormat = myPrinterJob.pageDialog(myPageFormat); + displayPageFormatAttributes(); + }); + Button printButton = new Button("Print"); + printButton.addActionListener(e -> { + try { + myPrinterJob.setPrintable(ValidatePage.this, myPageFormat); + myPrinterJob.print(); + } catch (PrinterException pe) { + pe.printStackTrace(); + PassFailJFrame.forceFail("Test failed because of PrinterException"); + } + }); + + Button chooseButton = new Button("Printer..."); + chooseButton.addActionListener(e -> myPrinterJob.printDialog()); + + Button validateButton = new Button("Validate Page"); + validateButton.addActionListener(e -> { + myPageFormat = myPrinterJob.validatePage(myPageFormat); + displayPageFormatAttributes(); + }); + Button setButton = new Button("Set Paper"); + setButton.addActionListener(e -> { + try { + Paper p1 = new Paper(); + double pwid = Double.parseDouble(tpw.getText()); + double phgt = Double.parseDouble(tph.getText()); + double pimx = Double.parseDouble(tpglm.getText()); + double pimy = Double.parseDouble(tpgtm.getText()); + double pimwid = Double.parseDouble(tpgiw.getText()); + double pimhgt = Double.parseDouble(tpgih.getText()); + p1.setSize(pwid, phgt); + p1.setImageableArea(pimx, pimy, pimwid, pimhgt); + myPageFormat.setPaper(p1); + displayPageFormatAttributes(); + } catch (NumberFormatException nfe) { + JOptionPane.showMessageDialog(ValidatePage.this, + "NumberFormatException occurred", "Error", + JOptionPane.ERROR_MESSAGE); + } + }); + panel.add(setButton); + panel.add(defButton); + panel.add(pageButton); + panel.add(chooseButton); + panel.add(validateButton); + panel.add(printButton); + add(panel); + TextArea ta = new TextArea(10, 45); + ta.setText( + "When validating a page, the process is 1st to find the closest matching \n" + + "paper size, next to make sure the requested imageable area fits within \n" + + "the printer's imageable area for that paper size. Finally the top and \n" + + "left margins will be shrunk if they are too great for the adjusted \n" + + "imageable area to fit at that position. They will shrink by the minimum\n" + + "needed to accommodate the imageable area.\n \n \n" + + "To test 6229507, put the minimum margins (all 0s) in Page Setup dialog.\n" + + "Compare Imageable width, height, and margins of portrait against landscape."); + + ta.setEditable(false); + add(ta); + setSize(700, 500); } -}// Sysout class + @Override + public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) { + if (pageIndex > 0) { + return Printable.NO_SUCH_PAGE; + } + + System.out.println("Format Orientation = " + + getOrientation(pageFormat.getOrientation())); + + Graphics2D g2d = (Graphics2D) graphics; + + System.out.println(g2d.getTransform()); + System.out.println("ix=" + pageFormat.getImageableX() + + " iy=" + pageFormat.getImageableY()); + g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); + g2d.drawString("ORIGIN", 20, 20); + g2d.drawString("X THIS WAY", 200, 50); + g2d.drawString("Y THIS WAY", 60, 200); + g2d.drawRect(0, 0, + (int) pageFormat.getImageableWidth(), + (int) pageFormat.getImageableHeight()); + g2d.setColor(Color.blue); + g2d.drawRect(1, 1, + (int) pageFormat.getImageableWidth() - 2, + (int) pageFormat.getImageableHeight() - 2); -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); + return Printable.PAGE_EXISTS; } - }// TestDialog class + private static final String INSTRUCTIONS = + "This test is very flexible and requires much interaction.\n" + + "There are several buttons.\n\n" + + "Set Paper: if all fields are valid numbers it sets the Paper object.\n" + + "This is used to create arbitrary nonsensical paper sizes to help\n" + + "test validatePage.\n\n" + + "Default Page: sets a default page. This should always be valid.\n\n" + + "Page Setup: brings up the page dialog. You must OK this dialog\n" + + "for it to have any effect. You can use this to set different size,\n" + + "orientation and margins - which of course affect imageable area.\n\n" + + "Printer: Used to set the current printer. Useful because current\n" + + "printer affects the choice of paper sizes available.\n" + + "You must OK this dialog for it to have any effect.\n\n" + + "Validate Page:The most important button in the test.\n" + + "By setting nonsensical or valid papers with varying margins etc,\n" + + "this should always find the closest match within the limits of\n" + + "what is possible on the current printer.\n\n" + + "Print: to the current printer. Not vital for this test request."; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testTimeOut(10) + .testUI(ValidatePage::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/XparColor.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/XparColor.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/XparColor.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/XparColor.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,7 @@ /** * @test * @bug 4179262 - @ @key printer + * @key printer * @summary Confirm that transparent colors are printed correctly. The * printout should show transparent rings with increasing darkness toward * the center. diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/raster/RasterTest.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/raster/RasterTest.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/PrinterJob/raster/RasterTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/PrinterJob/raster/RasterTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,248 +21,129 @@ * questions. */ -/** +import java.awt.Button; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; + +/* * @test * @bug 4242639 * @summary Printing quality problem on Canon and NEC * @key printer + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @run main/manual RasterTest */ -import java.awt.*; -import java.awt.geom.*; -import java.awt.event.*; -import java.awt.print.*; -import java.awt.Toolkit; -import java.awt.image.BufferedImage; - - public class RasterTest extends Frame implements ActionListener { + private final RasterCanvas c; + private static final String INSTRUCTIONS = + "This test uses rendering operations which force the implementation\n" + + "to print the page as a raster\n" + + "You should see two square images, the 1st containing overlapping\n" + + "composited squares, the lower image shows a gradient paint.\n" + + "The printed output should match the on-screen display, although\n" + + "only colour printers will be able to accurately reproduce the\n" + + "subtle color changes."; + + public static void main(String[] args) throws Exception { + if (PrinterJob.lookupPrintServices().length == 0) { + throw new RuntimeException("Printer not configured or available."); + } + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testUI(RasterTest::new) + .rows((int) INSTRUCTIONS.lines().count() + 1) + .columns(45) + .build() + .awaitAndCheck(); + } - private RasterCanvas c; - - public static void main(String args[]) { - String[] instructions = - { - "You must have a printer available to perform this test", - "This test uses rendering operations which force the implementation", - "to print the page as a raster", - "You should see two square images, the 1st containing overlapping", - "composited squares, the lower image shows a gradient paint.", - "The printed output should match the on-screen display, although", - "only colour printers will be able to accurately reproduce the", - "subtle color changes." - }; - Sysout.createDialog( ); - Sysout.printInstructions( instructions ); - - RasterTest f = new RasterTest(); - f.show(); - } - - public RasterTest() { + public RasterTest() { super("Java 2D Raster Printing"); - c = new RasterCanvas(); - add("Center", c); - - Button printButton = new Button("Print"); - printButton.addActionListener(this); - add("South", printButton); - - addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - System.exit(0); - } - }); - - pack(); + c = new RasterCanvas(); + add("Center", c); + Button printButton = new Button("Print"); + printButton.addActionListener(this); + add("South", printButton); + pack(); setBackground(Color.white); - - } - - public void actionPerformed(ActionEvent e) { - - PrinterJob pj = PrinterJob.getPrinterJob(); - - if (pj != null && pj.printDialog()) { - pj.setPrintable(c); - try { - pj.print(); - } catch (PrinterException pe) { - } finally { - System.err.println("PRINT RETURNED"); - } - } -} - - - class RasterCanvas extends Canvas implements Printable { - - - public int print(Graphics g, PageFormat pgFmt, int pgIndex) { - if (pgIndex > 0) - return Printable.NO_SUCH_PAGE; - - Graphics2D g2d= (Graphics2D)g; - g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); - doPaint(g2d); - return Printable.PAGE_EXISTS; } - public void paint(Graphics g) { - doPaint(g); - } + public void actionPerformed(ActionEvent e) { + PrinterJob pj = PrinterJob.getPrinterJob(); - public void paintComponent(Graphics g) { - doPaint(g); + if (pj.printDialog()) { + pj.setPrintable(c); + try { + pj.print(); + } catch (PrinterException pe) { + pe.printStackTrace(); + PassFailJFrame.forceFail("Test failed because of PrinterException"); + } + } } - public void doPaint(Graphics g) { - Graphics2D g2 = (Graphics2D)g; - - g2.setColor(Color.black); - - BufferedImage bimg = new BufferedImage(200, 200, - BufferedImage.TYPE_INT_ARGB); - Graphics ig = bimg.getGraphics(); - Color alphared = new Color(255, 0, 0, 128); - Color alphagreen = new Color(0, 255, 0, 128); - Color alphablue = new Color(0, 0, 255, 128); - ig.setColor(alphared); - ig.fillRect(0,0,200,200); - ig.setColor(alphagreen); - ig.fillRect(25,25,150,150); - ig.setColor(alphablue); - ig.fillRect(75,75,125,125); - g.drawImage(bimg, 10, 25, this); - - GradientPaint gp = - new GradientPaint(10.0f, 10.0f, alphablue, 210.0f, 210.0f, alphared, true); - g2.setPaint(gp); - g2.fillRect(10, 240, 200, 200); - - } + private static class RasterCanvas extends Canvas implements Printable { + @Override + public int print(Graphics g, PageFormat pgFmt, int pgIndex) { + if (pgIndex > 0) { + return Printable.NO_SUCH_PAGE; + } - public Dimension getPreferredSize() { - return new Dimension(500, 500); + Graphics2D g2d = (Graphics2D) g; + g2d.translate(pgFmt.getImageableX(), pgFmt.getImageableY()); + doPaint(g2d); + + return Printable.PAGE_EXISTS; + } + + @Override + public void paint(Graphics g) { + doPaint(g); + } + + private void doPaint(Graphics g) { + BufferedImage bimg = new BufferedImage(200, 200, + BufferedImage.TYPE_INT_ARGB); + Graphics ig = bimg.getGraphics(); + Color alphared = new Color(255, 0, 0, 128); + Color alphagreen = new Color(0, 255, 0, 128); + Color alphablue = new Color(0, 0, 255, 128); + ig.setColor(alphared); + ig.fillRect(0, 0, 200, 200); + ig.setColor(alphagreen); + ig.fillRect(25, 25, 150, 150); + ig.setColor(alphablue); + ig.fillRect(75, 75, 125, 125); + g.drawImage(bimg, 10, 25, this); + ig.dispose(); + + GradientPaint gp = + new GradientPaint(10.0f, 10.0f, alphablue, 210.0f, 210.0f, alphared, true); + + Graphics2D g2 = (Graphics2D) g; + g2.setPaint(gp); + g2.fillRect(10, 240, 200, 200); + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(500, 500); + } } - - } - } - - -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.show(); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - } - - }// TestDialog class diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392/bug8023392.html openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.html --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392/bug8023392.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ - - - - - - Bug 8023392 - - - -

    Bug ID: 8023392

    - -

    See the dialog box (usually in upper left corner) for instructions

    - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392/bug8023392.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392/bug8023392.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392/bug8023392.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,287 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - test - @bug 8023392 8259232 - @summary Swing text components printed with spaces between chars - @key printer - @run applet/manual=yesno bug8023392.html -*/ - -import javax.swing.*; -import javax.swing.border.LineBorder; -import java.applet.Applet; -import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.font.TextAttribute; -import java.awt.print.PageFormat; -import java.awt.print.Printable; -import java.awt.print.PrinterException; -import java.awt.print.PrinterJob; -import java.text.AttributedCharacterIterator; -import java.text.AttributedString; - - -public class bug8023392 extends Applet { - static final String[] instructions = { - "Please select the RadioButton for applet size labeled \"variable\" radiobutton in test harness window.", - "A Frame containing several pairs of labels ((a) and (b)) is displayed.", - "Labels of each pair look the same and are left-aligned (with spaces ", - "between chars).", - "1. Hit the print button.", - "2. Select any available printer (printing to file is also fine).", - "3. Look at the printing result (paper, PDF, PS, etc.):", - " The (a) and (b) labels should look almost the same and the (a) labels", - " shouldn't appear as if they are stretched along X axis."}; - - public void init() { - this.setLayout(new BorderLayout()); - add(new SimplePrint2(), BorderLayout.CENTER); - - Sysout.createDialogWithInstructions(instructions); - - } - - public static class SimplePrint2 extends JPanel - implements ActionListener, Printable { - JLabel label1; - JLabel label2; - JButton printButton; - - - public SimplePrint2() { - setLayout(new BorderLayout()); - label1 = new JLabel("2a) a b c d e" + - " "); - label2 = new JLabel("2b) a b c d e"); - - Box p1 = new Box(BoxLayout.Y_AXIS); - p1.add(label1); - p1.add(label2); - p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { - String s = "3a) a b c d e "; - @Override - protected void paintComponent(Graphics g) { - sun.swing.SwingUtilities2.drawChars(this, g, s.toCharArray(), - 0, s.length(), 0, 15); - } - }); - p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { - String s = "3b) a b c d e"; - @Override - protected void paintComponent(Graphics g) { - sun.swing.SwingUtilities2.drawChars(this, g, s.toCharArray(), - 0, s.length(), 0, 15); - } - }); - p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { - String s = "4a) a b c d e "; - AttributedCharacterIterator it; - { - AttributedString as = new AttributedString(s); - as.addAttribute(TextAttribute.FONT, getFont()); - as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 3, 8); - it = as.getIterator(); - } - @Override - protected void paintComponent(Graphics g) { - sun.swing.SwingUtilities2.drawString(this, g, it, 0, 15); - } - }); - - p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { - String s = "4b) a b c d e"; - AttributedCharacterIterator it; - { - AttributedString as = new AttributedString(s); - as.addAttribute(TextAttribute.FONT, getFont()); - as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 3, 8); - it = as.getIterator(); - } - @Override - protected void paintComponent(Graphics g) { - sun.swing.SwingUtilities2.drawString(this, g, it, 0, 15); - } - }); - - JPanel p2 = new JPanel(); - printButton = new JButton("Print"); - printButton.addActionListener(this); - p2.add(printButton); - - Container c = this; - c.add(p1, BorderLayout.CENTER); - c.add(p2, BorderLayout.SOUTH); - - String[] data = { - "1a) \u30aa\u30f3\u30e9\u30a4\u30f3\u6d88\u8fbc" + - " ", - "1b) \u30aa\u30f3\u30e9\u30a4\u30f3\u6d88\u8fbc" - }; - JList l0 = new JList(data); - l0.setVisibleRowCount(l0.getModel().getSize()); - JScrollPane jsp = new JScrollPane(l0); - l0.setBorder(new LineBorder(Color.GRAY)); - c.add(jsp, BorderLayout.NORTH); - - for (Component comp : new Component[]{label1, label2, printButton}) { - comp.setFont(new Font("Monospaced", 0, 16)); - } - } - - public void actionPerformed(ActionEvent e) { - PrinterJob job = PrinterJob.getPrinterJob(); - job.setPrintable(this); - if (job.printDialog()) { - try { - job.print(); - } catch (PrinterException ex) { - ex.printStackTrace(); - } - } - } - - public int print(Graphics graphics, - PageFormat pageFormat, - int pageIndex) - throws PrinterException { - if (pageIndex >= 1) { - return Printable.NO_SUCH_PAGE; - } - double imgX = pageFormat.getImageableX(); - double imgY = pageFormat.getImageableY(); - ((Graphics2D)graphics).translate(imgX, imgY); - this.paint(graphics); - return Printable.PAGE_EXISTS; - } - } -} - - -/** - * ************************************************* - * Standard Test Machinery - * DO NOT modify anything below -- it's a standard - * chunk of code whose purpose is to make user - * interaction uniform, and thereby make it simpler - * to read and understand someone else's test. - * ************************************************** - */ -class Sysout { - private static TestDialog dialog; - - public static void createDialogWithInstructions(String[] instructions) { - dialog = new TestDialog(new Frame(), "Instructions"); - dialog.printInstructions(instructions); - dialog.show(); - println("Any messages for the tester will display here."); - } - - public static void createDialog() { - dialog = new TestDialog(new Frame(), "Instructions"); - String[] defInstr = {"Instructions will appear here. ", ""}; - dialog.printInstructions(defInstr); - dialog.show(); - println("Any messages for the tester will display here."); - } - - - public static void printInstructions(String[] instructions) { - dialog.printInstructions(instructions); - } - - - public static void println(String messageIn) { - dialog.displayMessage(messageIn); - } - -}// Sysout class - - -class TestDialog extends Dialog { - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog(Frame frame, String name) { - super(frame, name); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); - add("North", instructionsText); - - messageText = new TextArea("", 5, maxStringLength, scrollBoth); - add("South", messageText); - - pack(); - - show(); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions(String[] instructions) { - //Clear out any current instructions - instructionsText.setText(""); - - //Go down array of instruction strings - - String printStr, remainingStr; - for (int i = 0; i < instructions.length; i++) { - //chop up each into pieces maxSringLength long - remainingStr = instructions[i]; - while (remainingStr.length() > 0) { - //if longer than max then chop off first max chars to print - if (remainingStr.length() >= maxStringLength) { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf(' ', maxStringLength - 1); - - if (posOfSpace <= 0) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring(0, posOfSpace + 1); - remainingStr = remainingStr.substring(posOfSpace + 1); - } - //else just print - else { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append(printStr + "\n"); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage(String messageIn) { - messageText.append(messageIn + "\n"); - } - -}// TestDialog class - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392.java openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/print/bug8023392.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/print/bug8023392.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8023392 8259232 + * @key printer + * @modules java.desktop/sun.swing + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Swing text components printed with spaces between chars + * @run main/manual bug8023392 + */ + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.font.TextAttribute; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.border.LineBorder; + +import sun.swing.SwingUtilities2; + +public class bug8023392 { + private static final String INSTRUCTIONS = + """ + A Frame containing several pairs of labels (a) and (b) is displayed. + Labels of each pair look the same and are left-aligned (with spaces + between chars). + 1. Hit the print button. + 2. Select any available printer (printing to file is also fine). + 3. Look at the printing result (paper, PDF, PS, etc.): + The (a) and (b) labels should look almost the same and the (a) + labels shouldn't appear as if they are stretched along X axis. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame + .builder() + .title("bug8023392 Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(bug8023392::init) + .build() + .awaitAndCheck(); + } + + public static JFrame init() { + JFrame frame = new JFrame("Test Window"); + frame.setLayout(new BorderLayout()); + frame.add(new SimplePrint2(), BorderLayout.CENTER); + frame.pack(); + return frame; + } + + public static class SimplePrint2 extends JPanel + implements ActionListener, Printable { + JLabel label1; + JLabel label2; + JButton printButton; + + public SimplePrint2() { + setLayout(new BorderLayout()); + label1 = new JLabel("2a) a b c d e" + + " "); + label2 = new JLabel("2b) a b c d e"); + + Box p1 = new Box(BoxLayout.Y_AXIS); + p1.add(label1); + p1.add(label2); + p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { + String s = "3a) a b c d e "; + @Override + protected void paintComponent(Graphics g) { + SwingUtilities2.drawChars(this, g, s.toCharArray(), + 0, s.length(), 0, 15); + } + }); + p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { + String s = "3b) a b c d e"; + @Override + protected void paintComponent(Graphics g) { + SwingUtilities2.drawChars(this, g, s.toCharArray(), + 0, s.length(), 0, 15); + } + }); + p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { + String s = "4a) a b c d e "; + AttributedCharacterIterator it; + { + AttributedString as = new AttributedString(s); + as.addAttribute(TextAttribute.FONT, getFont()); + as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 3, 8); + it = as.getIterator(); + } + @Override + protected void paintComponent(Graphics g) { + SwingUtilities2.drawString(this, g, it, 0, 15); + } + }); + + p1.add(new JLabel("wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww") { + String s = "4b) a b c d e"; + AttributedCharacterIterator it; + { + AttributedString as = new AttributedString(s); + as.addAttribute(TextAttribute.FONT, getFont()); + as.addAttribute(TextAttribute.FOREGROUND, Color.RED, 3, 8); + it = as.getIterator(); + } + @Override + protected void paintComponent(Graphics g) { + SwingUtilities2.drawString(this, g, it, 0, 15); + } + }); + + JPanel p2 = new JPanel(); + printButton = new JButton("Print"); + printButton.addActionListener(this); + p2.add(printButton); + + Container c = this; + c.add(p1, BorderLayout.CENTER); + c.add(p2, BorderLayout.SOUTH); + + String[] data = { + "1a) \u30aa\u30f3\u30e9\u30a4\u30f3\u6d88\u8fbc" + + " ", + "1b) \u30aa\u30f3\u30e9\u30a4\u30f3\u6d88\u8fbc" + }; + JList l0 = new JList(data); + l0.setVisibleRowCount(l0.getModel().getSize()); + JScrollPane jsp = new JScrollPane(l0); + l0.setBorder(new LineBorder(Color.GRAY)); + c.add(jsp, BorderLayout.NORTH); + + for (Component comp : new Component[]{label1, label2, printButton}) { + comp.setFont(new Font("Monospaced", 0, 16)); + } + } + + public void actionPerformed(ActionEvent e) { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(this); + if (job.printDialog()) { + try { + job.print(); + } catch (PrinterException ex) { + ex.printStackTrace(); + String msg = "PrinterException: " + ex.getMessage(); + PassFailJFrame.forceFail(msg); + } + } + } + + public int print(Graphics graphics, + PageFormat pageFormat, + int pageIndex) + throws PrinterException { + if (pageIndex >= 1) { + return Printable.NO_SUCH_PAGE; + } + double imgX = pageFormat.getImageableX(); + double imgY = pageFormat.getImageableY(); + ((Graphics2D)graphics).translate(imgX, imgY); + this.paint(graphics); + return Printable.PAGE_EXISTS; + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/PassFailJFrame.java 2025-04-09 19:45:33.000000000 +0000 @@ -184,21 +184,23 @@ * *

    * Add the following jtreg tags before the test class declaration - * {@snippet : + *

    
      * /*
    - *  * @test
    + *  * @test
      *  * @summary Sample manual test
      *  * @library /java/awt/regtesthelpers
      *  * @build PassFailJFrame
      *  * @run main/manual SampleManualTest
    - * }
    - * and the closing comment tag */.
    + *  */
    + * 
    *

    * The {@code @library} tag points to the location of the * {@code PassFailJFrame} class in the source code; * the {@code @build} tag makes jtreg compile the {@code PassFailJFrame} class, * and finally the {@code @run} tag specifies it is a manual * test and the class to run. + *

    + * Don't forget to update the name of the class to run in the {@code @run} tag. * *

    Using {@code Builder}

    * Use methods of the {@link Builder Builder} class to set or change diff -Nru openjdk-17-17.0.14+7/test/jdk/java/awt/regtesthelpers/Util.java openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/Util.java --- openjdk-17-17.0.14+7/test/jdk/java/awt/regtesthelpers/Util.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/awt/regtesthelpers/Util.java 2025-04-09 19:45:33.000000000 +0000 @@ -174,6 +174,8 @@ if (screen.equals(color)) { return true; } + System.out.println("Robot.getPixelColor Expected: " + color); + System.out.println("Robot.getPixelColor Actual: " + screen); } return false; } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/io/File/createTempFile/SpecialTempFile.java openjdk-17-17.0.15+6/test/jdk/java/io/File/createTempFile/SpecialTempFile.java --- openjdk-17-17.0.14+7/test/jdk/java/io/File/createTempFile/SpecialTempFile.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/io/File/createTempFile/SpecialTempFile.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,10 +39,15 @@ import jdk.test.lib.Platform; import jdk.test.lib.OSVersion; +import jdk.internal.util.StaticProperty; public class SpecialTempFile { + // + // If exceptionExpected == null, then any IOException thrown by + // File.createTempFile is ignored. + // private static void test(String name, String[] prefix, String[] suffix, - boolean exceptionExpected) throws IOException + Boolean exceptionExpected) throws IOException { if (prefix == null || suffix == null || prefix.length != suffix.length) @@ -69,19 +74,21 @@ f = File.createTempFile(prefix[i], suffix[i], tempDir.toFile()); } catch (IOException e) { - if (exceptionExpected) { - if (e.getMessage().startsWith(exceptionMsg)) - exceptionThrown = true; - else - System.out.println("Wrong error message:" + - e.getMessage()); - } else { - throw e; + if (exceptionExpected != null) { + if (exceptionExpected) { + if (e.getMessage().startsWith(exceptionMsg)) + exceptionThrown = true; + else + System.out.println("Wrong error message:" + + e.getMessage()); + } else { + throw e; + } + + if (exceptionExpected && (!exceptionThrown || f != null)) + throw new RuntimeException("IOException expected"); } } - - if (exceptionExpected && (!exceptionThrown || f != null)) - throw new RuntimeException("IOException is expected"); } } } @@ -111,8 +118,15 @@ String[] resvPre = { "LPT1.package.zip", "com7.4.package.zip" }; String[] resvSuf = { ".temp", ".temp" }; boolean exceptionExpected = - !(System.getProperty("os.name").endsWith("11") || + !(System.getProperty("os.name").matches("^.*[11|2025]$") || new OSVersion(10, 0).compareTo(OSVersion.current()) > 0); test("ReservedName", resvPre, resvSuf, exceptionExpected); + + System.out.println("OS name: " + System.getProperty("os.name") + "\n" + + "OS version: " + OSVersion.current()); + + // Here the test is for whether File.createTempFile hangs, so whether + // an exception is thrown is ignored: expectedException == null + test("ReservedName", resvPre, resvSuf, null); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/Assert.java openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/Assert.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/Assert.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/Assert.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,8 @@ /* * @test * @bug 4290640 4785473 + * @requires vm.flagless + * @library /test/lib * @build package1.Class1 package2.Class2 package1.package3.Class3 Assert * @run main/othervm Assert * @summary Test the assertion facility @@ -31,12 +33,17 @@ * @key randomness */ +import jdk.test.lib.process.OutputAnalyzer; import package1.*; import package2.*; import package1.package3.*; -import java.io.*; + +import java.util.ArrayList; +import java.util.List; import java.util.Random; +import static jdk.test.lib.process.ProcessTools.*; + public class Assert { private static Class1 testClass1; @@ -56,7 +63,7 @@ * off at class load time. Once the class is loaded its assertion status * does not change. */ - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Throwable { // Switch values: 0=don't touch, 1=off, 2 = on int[] switches = new int[7]; @@ -77,28 +84,17 @@ } // Spawn new VM and load classes - String command = System.getProperty("java.home") + - File.separator + "bin" + File.separator + "java Assert"; - - StringBuffer commandString = new StringBuffer(command); + List commands = new ArrayList<>(); + commands.add("Assert"); for(int j=0; j<7; j++) - commandString.append(" "+switches[j]); - - Process p = null; - p = Runtime.getRuntime().exec(commandString.toString()); - + commands.add(Integer.toString(switches[j])); + OutputAnalyzer outputAnalyzer = executeCommand(createLimitedTestJavaProcessBuilder(commands)); if (debug) { // See output of test VMs - BufferedReader blah = new BufferedReader( - new InputStreamReader(p.getInputStream())); - String outString = blah.readLine(); - while (outString != null) { - System.out.println("from BufferedReader:"+outString); - outString = blah.readLine(); - } + outputAnalyzer.asLines() + .stream() + .forEach(s -> System.out.println(s)); } - - p.waitFor(); - int result = p.exitValue(); + int result = outputAnalyzer.getExitValue(); if (debug) { // See which switch configs failed if (result == 0) { for(int k=6; k>=0; k--) diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/GetSystemPackage.java openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/GetSystemPackage.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/GetSystemPackage.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/GetSystemPackage.java 2025-04-09 19:45:33.000000000 +0000 @@ -24,6 +24,7 @@ /* * @test * @bug 8060130 + * @requires vm.flagless * @library /test/lib * @build package2.Class2 GetSystemPackage * @summary Test if getSystemPackage() return consistent values for cases @@ -41,6 +42,8 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; + +import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; public class GetSystemPackage { @@ -118,8 +121,9 @@ private static void runSubProcess(String messageOnError, String ... args) throws Exception { - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args); - int res = pb.directory(tmpFolder).inheritIO().start().waitFor(); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(args) + .directory(tmpFolder); + int res = ProcessTools.executeProcess(pb).getExitValue(); if (res != 0) { throw new RuntimeException(messageOnError); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/getResource/GetResource.java openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/getResource/GetResource.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/ClassLoader/getResource/GetResource.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/ClassLoader/getResource/GetResource.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -40,11 +40,9 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; -import jdk.test.lib.JDKToolFinder; import static jdk.test.lib.process.ProcessTools.*; import org.testng.annotations.BeforeTest; @@ -144,26 +142,14 @@ private void runTest(Path dir, List options, String expected) throws Throwable { - String javapath = JDKToolFinder.getJDKTool("java"); - List cmdLine = new ArrayList<>(); - cmdLine.add(javapath); options.forEach(cmdLine::add); cmdLine.add("GetResource"); cmdLine.add(expected); - - System.out.println("Command line: " + cmdLine); - ProcessBuilder pb = - new ProcessBuilder(cmdLine.stream().toArray(String[]::new)); - - // change working directory - pb.directory(dir.toFile()); - - // remove CLASSPATH environment variable - Map env = pb.environment(); - String value = env.remove("CLASSPATH"); - + ProcessBuilder pb = createTestJavaProcessBuilder(cmdLine); + pb.directory(dir.toFile()); // change working directory + pb.environment().remove("CLASSPATH"); // remove CLASSPATH environment variable executeCommand(pb).shouldHaveExitValue(0); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/SecurityManager/modules/CustomSecurityManagerTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,7 +64,7 @@ @Test(dataProvider = "testCases") public void testProvider(List args) throws Throwable { - ProcessBuilder processBuilder = ProcessTools.createLimitedTestJavaProcessBuilder(args); + ProcessBuilder processBuilder = ProcessTools.createTestJavaProcessBuilder(args); OutputAnalyzer outputAnalyzer = ProcessTools.executeCommand(processBuilder); outputAnalyzer.shouldHaveExitValue(0); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForImageTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForImageTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForImageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForImageTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm JDKLoggerForImageTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForJDKTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForJDKTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForJDKTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/JDKLoggerForJDKTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * 2. clients are in named/unnamed module, * patched system module, or Xbootclasspath * This test DOES require existence of java.logging module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm JDKLoggerForJDKTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/LoggerInImageTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/LoggerInImageTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/LoggerInImageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/LoggerInImageTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm LoggerInImageTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForImageTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForImageTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForImageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForImageTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm NamedLoggerForImageTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForJDKTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForJDKTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForJDKTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/NamedLoggerForJDKTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm NamedLoggerForJDKTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForImageTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForImageTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForImageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForImageTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm UnnamedLoggerForImageTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForJDKTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForJDKTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForJDKTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/LoggerFinder/modules/UnnamedLoggerForJDKTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ * patched system module, or Xbootclasspath * This test does not require existence of java.logging module, * but require jdk.compiler module + * @requires vm.flagless * @library /test/lib * @build Base jdk.test.lib.compiler.CompilerUtils * @run main/othervm UnnamedLoggerForJDKTest diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/System/SecurityManagerWarnings.java openjdk-17-17.0.15+6/test/jdk/java/lang/System/SecurityManagerWarnings.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/System/SecurityManagerWarnings.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/System/SecurityManagerWarnings.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +28,6 @@ * @library /test/lib */ -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.JarUtils; @@ -51,6 +50,7 @@ }; """); + System.setProperty("test.noclasspath", "true"); String testClasses = System.getProperty("test.classes"); allowTest(null, testClasses); @@ -131,13 +131,11 @@ static OutputAnalyzer run(String prop, String cp) throws Exception { ProcessBuilder pb; if (prop == null) { - pb = new ProcessBuilder( - JDKToolFinder.getJDKTool("java"), + pb = ProcessTools.createTestJavaProcessBuilder( "-cp", cp, "SecurityManagerWarnings", "run"); } else { - pb = new ProcessBuilder( - JDKToolFinder.getJDKTool("java"), + pb = ProcessTools.createTestJavaProcessBuilder( "-cp", cp, "-Djava.security.manager=" + prop, "-Djava.security.policy=policy", diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/PrivateInvokeTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/PrivateInvokeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/PrivateInvokeTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/PrivateInvokeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -67,8 +67,6 @@ String vstr = System.getProperty(THIS_CLASS.getSimpleName()+".verbose"); if (vstr == null) vstr = System.getProperty(THIS_CLASS.getName()+".verbose"); - if (vstr == null) - vstr = System.getProperty("test.verbose"); if (vstr != null) verbose = Integer.parseInt(vstr); } private static int referenceKind(Method m) { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/condy/CondyNestedResolutionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -44,7 +44,7 @@ */ public class CondyNestedResolutionTest { public static void main(String args[]) throws Throwable { - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder("CondyNestedResolution"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("CondyNestedResolution"); OutputAnalyzer oa = new OutputAnalyzer(pb.start()); oa.shouldContain("StackOverflowError"); oa.shouldContain("bsm1arg"); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/findSpecial/FindSpecialTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/findSpecial/FindSpecialTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/findSpecial/FindSpecialTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/findSpecial/FindSpecialTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,13 +37,11 @@ import java.nio.file.Path; import java.nio.file.Paths; -import jdk.test.lib.JDKToolFinder; -import jdk.test.lib.process.ProcessTools; +import static jdk.test.lib.process.ProcessTools.*; import org.testng.annotations.Test; public class FindSpecialTest { - static final String JAVA_LAUNCHER = JDKToolFinder.getJDKTool("java"); static final String TEST_CLASSES = System.getProperty("test.classes", "."); static final String TEST_CLASS_PATH = System.getProperty("test.class.path"); static final String TEST_MAIN_CLASS = "test.FindSpecial"; @@ -59,8 +57,9 @@ throw new Error(m1 + " not exist"); } String classpath = m1.toString() + File.pathSeparator + TEST_CLASS_PATH; - ProcessTools.executeCommand(JAVA_LAUNCHER, "-cp", classpath, TEST_MAIN_CLASS) - .shouldHaveExitValue(0); + executeCommand(createTestJavaProcessBuilder("-cp", classpath, + TEST_MAIN_CLASS)) + .shouldHaveExitValue(0); } /* @@ -72,10 +71,9 @@ if (Files.notExists(modules)) { throw new Error(modules + " not exist"); } - ProcessTools.executeCommand(JAVA_LAUNCHER, - "-cp", TEST_CLASS_PATH, - "-p", modules.toString(), - "-m", TEST_MODULE + "/" + TEST_MAIN_CLASS) - .shouldHaveExitValue(0); + executeCommand(createTestJavaProcessBuilder("-cp", TEST_CLASS_PATH, + "-p", modules.toString(), + "-m", TEST_MODULE + "/" + TEST_MAIN_CLASS)) + .shouldHaveExitValue(0); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LUtils.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LUtils.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LUtils.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LUtils.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/* - * support infrastructure to invoke a java class from the command line - */ -class LUtils { - static final com.sun.tools.javac.Main javac = - new com.sun.tools.javac.Main(); - static final File cwd = new File(".").getAbsoluteFile(); - static final String JAVAHOME = System.getProperty("java.home"); - static final boolean isWindows = - System.getProperty("os.name", "unknown").startsWith("Windows"); - static final File JAVA_BIN_FILE = new File(JAVAHOME, "bin"); - static final File JAVA_CMD = new File(JAVA_BIN_FILE, - isWindows ? "java.exe" : "java"); - static final File JAR_BIN_FILE = new File(JAVAHOME, "bin"); - static final File JAR_CMD = new File(JAR_BIN_FILE, - isWindows ? "jar.exe" : "jar"); - - protected LUtils() { - } - - public static void compile(String... args) { - if (javac.compile(args) != 0) { - throw new RuntimeException("compilation fails"); - } - } - - static void createFile(File outFile, List content) { - try { - Files.write(outFile.getAbsoluteFile().toPath(), content, - Charset.defaultCharset()); - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - static File getClassFile(File javaFile) { - return javaFile.getName().endsWith(".java") - ? new File(javaFile.getName().replace(".java", ".class")) - : null; - } - - static String getSimpleName(File inFile) { - String fname = inFile.getName(); - return fname.substring(0, fname.indexOf(".")); - } - - static TestResult doExec(String... cmds) { - return doExec(null, null, cmds); - } - - /* - * A method which executes a java cmd and returns the results in a container - */ - static TestResult doExec(Map envToSet, - java.util.Set envToRemove, String... cmds) { - String cmdStr = ""; - for (String x : cmds) { - cmdStr = cmdStr.concat(x + " "); - } - ProcessBuilder pb = new ProcessBuilder(cmds); - Map env = pb.environment(); - if (envToRemove != null) { - for (String key : envToRemove) { - env.remove(key); - } - } - if (envToSet != null) { - env.putAll(envToSet); - } - BufferedReader rdr = null; - try { - List outputList = new ArrayList<>(); - pb.redirectErrorStream(true); - Process p = pb.start(); - rdr = new BufferedReader(new InputStreamReader(p.getInputStream())); - String in = rdr.readLine(); - while (in != null) { - outputList.add(in); - in = rdr.readLine(); - } - p.waitFor(); - p.destroy(); - - return new TestResult(cmdStr, p.exitValue(), outputList, - env, new Throwable("current stack of the test")); - } catch (Exception ex) { - ex.printStackTrace(); - throw new RuntimeException(ex.getMessage()); - } - } - - static class TestResult { - String cmd; - int exitValue; - List testOutput; - Map env; - Throwable t; - - public TestResult(String str, int rv, List oList, - Map env, Throwable t) { - cmd = str; - exitValue = rv; - testOutput = oList; - this.env = env; - this.t = t; - } - - void assertZero(String message) { - if (exitValue != 0) { - System.err.println(this); - throw new RuntimeException(message); - } - } - - @Override - public String toString() { - StringWriter sw = new StringWriter(); - PrintWriter status = new PrintWriter(sw); - status.println("Cmd: " + cmd); - status.println("Return code: " + exitValue); - status.println("Environment variable:"); - for (String x : env.keySet()) { - status.println("\t" + x + "=" + env.get(x)); - } - status.println("Output:"); - for (String x : testOutput) { - status.println("\t" + x); - } - status.println("Exception:"); - status.println(t.getMessage()); - t.printStackTrace(status); - - return sw.getBuffer().toString(); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlDoPrivilegedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,19 +24,28 @@ /* * @test * @bug 8003881 - * @summary tests DoPrivileged action (implemented as lambda expressions) by - * inserting them into the BootClassPath. + * @library /test/lib/ * @modules jdk.compiler * jdk.zipfs - * @compile -XDignore.symbol.file LambdaAccessControlDoPrivilegedTest.java LUtils.java + * @compile LambdaAccessControlDoPrivilegedTest.java * @run main/othervm -Djava.security.manager=allow LambdaAccessControlDoPrivilegedTest + * @summary tests DoPrivileged action (implemented as lambda expressions) by + * inserting them into the BootClassPath. */ -import java.io.File; +import jdk.test.lib.process.OutputAnalyzer; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.spi.ToolProvider; + +import static jdk.test.lib.process.ProcessTools.*; -public class LambdaAccessControlDoPrivilegedTest extends LUtils { - public static void main(String... args) { +public class LambdaAccessControlDoPrivilegedTest { + public static void main(String... args) throws Exception { final List scratch = new ArrayList(); scratch.clear(); scratch.add("import java.security.*;"); @@ -47,9 +56,9 @@ scratch.add("});"); scratch.add("}"); scratch.add("}"); - File doprivJava = new File("DoPriv.java"); - File doprivClass = getClassFile(doprivJava); - createFile(doprivJava, scratch); + Path doprivJava = Path.of("DoPriv.java"); + Path doprivClass = Path.of("DoPriv.class"); + Files.write(doprivJava, scratch, Charset.defaultCharset()); scratch.clear(); scratch.add("public class Bar {"); @@ -59,30 +68,40 @@ scratch.add("}"); scratch.add("}"); - File barJava = new File("Bar.java"); - File barClass = getClassFile(barJava); - createFile(barJava, scratch); - - String[] javacArgs = {barJava.getName(), doprivJava.getName()}; - compile(javacArgs); - File jarFile = new File("foo.jar"); - String[] jargs = {"cvf", jarFile.getName(), doprivClass.getName()}; - TestResult tr = doExec(JAR_CMD.getAbsolutePath(), - "cvf", jarFile.getName(), - doprivClass.getName()); - if (tr.exitValue != 0){ - throw new RuntimeException(tr.toString()); + Path barJava = Path.of("Bar.java"); + Path barClass = Path.of("Bar.class"); + Files.write(barJava, scratch, Charset.defaultCharset()); + + compile(barJava.toString(), doprivJava.toString()); + + jar("cvf", "foo.jar", doprivClass.toString()); + Files.delete(doprivJava); + Files.delete(doprivClass); + + ProcessBuilder pb = createTestJavaProcessBuilder( + "-Xbootclasspath/a:foo.jar", + "-cp", ".", + "-Djava.security.manager=allow", + "Bar"); + executeProcess(pb).shouldHaveExitValue(0); + + Files.delete(barJava); + Files.delete(barClass); + Files.delete(Path.of("foo.jar")); + } + + static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar").orElseThrow(); + static final ToolProvider JAVAC = ToolProvider.findFirst("javac").orElseThrow(); + static void compile(String... args) throws IOException { + if (JAVAC.run(System.out, System.err, args) != 0) { + throw new RuntimeException("compilation fails"); + } + } + + static void jar(String... args) { + int rc = JAR_TOOL.run(System.out, System.err, args); + if (rc != 0){ + throw new RuntimeException("fail to create JAR file"); } - doprivJava.delete(); - doprivClass.delete(); - tr = doExec(JAVA_CMD.getAbsolutePath(), - "-Xbootclasspath/a:foo.jar", - "-cp", ".", - "-Djava.security.manager=allow", - "Bar"); - tr.assertZero("testDoPrivileged fails"); - barJava.delete(); - barClass.delete(); - jarFile.delete(); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAccessControlTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAccessControlTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAccessControlTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,14 +24,12 @@ /* * @test * @bug 8003881 - * @summary tests Lambda expression with a a security manager at top level * @modules jdk.compiler - * @compile -XDignore.symbol.file LambdaAccessControlTest.java LUtils.java - * * @run main/othervm -Djava.security.manager=allow LambdaAccessControlTest + * @summary tests Lambda expression with a security manager at top level */ -public class LambdaAccessControlTest extends LUtils { +public class LambdaAccessControlTest { public static void main(String... args) { System.setSecurityManager(new SecurityManager()); JJ iii = (new CC())::impl; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAsm.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAsm.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaAsm.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaAsm.java 2025-04-09 19:45:33.000000000 +0000 @@ -24,13 +24,14 @@ /* * @test * @bug 8027232 - * @summary ensures that j.l.i.InvokerByteCodeGenerator and ASM visitMethodInsn - * generate bytecodes with correct constant pool references + * @library /test/lib/ * @modules java.base/jdk.internal.org.objectweb.asm * jdk.jdeps/com.sun.tools.classfile * jdk.zipfs - * @compile -XDignore.symbol.file LambdaAsm.java LUtils.java + * @compile LambdaAsm.java * @run main/othervm LambdaAsm + * @summary ensures that j.l.i.InvokerByteCodeGenerator and ASM visitMethodInsn + * generate bytecodes with correct constant pool references */ import com.sun.tools.classfile.Attribute; import com.sun.tools.classfile.ClassFile; @@ -41,32 +42,35 @@ import com.sun.tools.classfile.Method; import java.io.ByteArrayInputStream; import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Files; import java.util.ArrayList; import java.nio.file.DirectoryStream; import java.nio.file.Path; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.MethodVisitor; +import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.OutputAnalyzer; import static java.nio.file.Files.*; import static jdk.internal.org.objectweb.asm.Opcodes.*; +import static jdk.test.lib.process.ProcessTools.*; public class LambdaAsm { + static final Path SRC = Path.of("src"); + static final Path CLASSES = Path.of("classes"); - static final File TestFile = new File("A.java"); - - static void init() { + static void init() throws Exception { emitCode(); - LUtils.compile(TestFile.getName()); - LUtils.TestResult tr = LUtils.doExec(LUtils.JAVA_CMD.getAbsolutePath(), + CompilerUtils.compile(SRC, CLASSES); + OutputAnalyzer outputAnalyzer = executeProcess(createTestJavaProcessBuilder( "-Djdk.internal.lambda.dumpProxyClasses=.", - "-cp", ".", "A"); - if (tr.exitValue != 0) { - System.out.println("Error: " + tr.toString()); - throw new RuntimeException("could not create proxy classes"); - } + "-cp", CLASSES.toString(), "A")); + outputAnalyzer.shouldHaveExitValue(0); } - static void emitCode() { + static void emitCode() throws Exception { ArrayList scratch = new ArrayList<>(); scratch.add("import java.util.function.*;"); scratch.add("class A {"); @@ -88,7 +92,10 @@ scratch.add(" I.d();"); scratch.add(" }"); scratch.add("}"); - LUtils.createFile(TestFile, scratch); + + Path testFile = SRC.resolve("A.java"); + Files.createDirectories(SRC); + Files.write(testFile, scratch, Charset.defaultCharset()); } static void checkMethod(String cname, String mname, ConstantPool cp, diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaStackTrace.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaStackTrace.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LambdaStackTrace.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LambdaStackTrace.java 2025-04-09 19:45:33.000000000 +0000 @@ -24,20 +24,23 @@ /* * @test * @bug 8025636 - * @summary Synthetic frames should be hidden in exceptions + * @library /test/lib/ * @modules java.base/jdk.internal.org.objectweb.asm * jdk.compiler - * @compile -XDignore.symbol.file LUtils.java LambdaStackTrace.java + * @compile LambdaStackTrace.java * @run main LambdaStackTrace + * @summary Synthetic frames should be hidden in exceptions */ import jdk.internal.org.objectweb.asm.ClassWriter; +import jdk.test.lib.compiler.CompilerUtils; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_ABSTRACT; @@ -47,7 +50,7 @@ public class LambdaStackTrace { - static File classes = new File(System.getProperty("test.classes")); + static Path CLASSES = Path.of(System.getProperty("test.classes", ".")); public static void main(String[] args) throws Exception { testBasic(); @@ -121,12 +124,8 @@ // We can't let javac compile these interfaces because in > 1.8 it will insert // bridge methods into the interfaces - we want code that looks like <= 1.7, // so we generate it. - try (FileOutputStream fw = new FileOutputStream(new File(classes, "Maker.class"))) { - fw.write(generateMaker()); - } - try (FileOutputStream fw = new FileOutputStream(new File(classes, "StringMaker.class"))) { - fw.write(generateStringMaker()); - } + Files.write(CLASSES.resolve("Maker.class"), generateMaker()); + Files.write(CLASSES.resolve("StringMaker.class"), generateStringMaker()); } private static byte[] generateMaker() { @@ -154,7 +153,7 @@ } - static void emitCode(File f) { + static void emitCode(Path file) throws IOException { ArrayList scratch = new ArrayList<>(); scratch.add("public class Caller {"); scratch.add(" public static void callStringMaker() {"); @@ -166,13 +165,17 @@ scratch.add(" ((Maker) sm).make();"); // <-- This will call the bridge method scratch.add(" }"); scratch.add("}"); - LUtils.createFile(f, scratch); + + Files.write(file, scratch, Charset.defaultCharset()); } - static void compileCaller() { - File caller = new File(classes, "Caller.java"); + static void compileCaller() throws IOException { + Path src = Path.of("src"); + Files.createDirectories(src); + + Path caller = src.resolve("Caller.java"); emitCode(caller); - LUtils.compile("-cp", classes.getAbsolutePath(), "-d", classes.getAbsolutePath(), caller.getAbsolutePath()); + CompilerUtils.compile(src, CLASSES, "-cp", CLASSES.toAbsolutePath().toString()); } private static void verifyFrames(StackTraceElement[] stack, String... patterns) throws Exception { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,33 +24,41 @@ /* * @test * @bug 8023524 - * @summary tests logging generated classes for lambda + * @requires vm.flagless + * @library /test/lib/ * @library /java/nio/file * @modules jdk.compiler * jdk.zipfs * @run testng LogGeneratedClassesTest + * @summary tests logging generated classes for lambda */ -import java.io.File; import java.io.IOException; +import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.FileStore; import java.nio.file.attribute.PosixFileAttributeView; +import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.OutputAnalyzer; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.testng.SkipException; import static java.nio.file.attribute.PosixFilePermissions.*; +import static jdk.test.lib.process.ProcessTools.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; -public class LogGeneratedClassesTest extends LUtils { +public class LogGeneratedClassesTest { + static final Path DUMP_LAMBDA_PROXY_CLASS_FILES = Path.of("DUMP_LAMBDA_PROXY_CLASS_FILES"); + static final Path CLASSES = Path.of("classes").toAbsolutePath(); String longFQCN; @BeforeClass @@ -73,9 +81,8 @@ scratch.add(" }"); scratch.add("}"); - File test = new File("TestLambda.java"); - createFile(test, scratch); - compile("-d", ".", test.getName()); + Path testLambda = Path.of("TestLambda.java"); + Files.write(testLambda, scratch, Charset.defaultCharset()); scratch.remove(0); scratch.remove(0); @@ -90,84 +97,91 @@ sb.append(";"); sb.insert(0, "package "); scratch.add(0, sb.toString()); - test = new File("LongPackageName.java"); - createFile(test, scratch); - compile("-d", ".", test.getName()); - - // create target - Files.createDirectory(Paths.get("dump")); - Files.createDirectories(Paths.get("dumpLong/com/example/nonsense")); - Files.createFile(Paths.get("dumpLong/com/example/nonsense/nonsense")); - Files.createFile(Paths.get("file")); + Path lpnTest = Path.of("LongPackageName.java"); + Files.write(lpnTest, scratch, Charset.defaultCharset()); + + CompilerUtils.compile(Path.of("."), CLASSES); } @AfterClass public void cleanup() throws IOException { Files.delete(Paths.get("TestLambda.java")); Files.delete(Paths.get("LongPackageName.java")); - Files.delete(Paths.get("file")); - TestUtil.removeAll(Paths.get("com")); + TestUtil.removeAll(DUMP_LAMBDA_PROXY_CLASS_FILES); + TestUtil.removeAll(Paths.get("notDir")); TestUtil.removeAll(Paths.get("dump")); TestUtil.removeAll(Paths.get("dumpLong")); } @Test - public void testNotLogging() { - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", + public void testNotLogging() throws Exception { + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), "-Djava.security.manager=allow", "com.example.TestLambda"); - tr.assertZero("Should still return 0"); + executeProcess(pb).shouldHaveExitValue(0); } @Test - public void testLogging() throws IOException { + public void testLogging() throws Exception { + Path testDir = Path.of("dump"); + Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES); + Files.createDirectory(testDir); + Files.createDirectory(dumpDir); assertTrue(Files.exists(Paths.get("dump"))); - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), "-Djava.security.manager=allow", - "-Djdk.internal.lambda.dumpProxyClasses=dump", - "com.example.TestLambda"); + "-Djdk.internal.lambda.dumpProxyClasses=" + DUMP_LAMBDA_PROXY_CLASS_FILES, + "com.example.TestLambda").directory(testDir.toFile()); + executeProcess(pb).shouldHaveExitValue(0); + // 2 our own class files. We don't care about the others assertEquals(Files.find( - Paths.get("dump"), + dumpDir, 99, - (p, a) -> p.startsWith(Paths.get("dump/com/example")) + (p, a) -> p.startsWith(dumpDir.resolve("com/example")) && a.isRegularFile()).count(), - 2, "Two lambda captured"); - tr.assertZero("Should still return 0"); + 2, "Two lambda captured"); } @Test - public void testDumpDirNotExist() throws IOException { - assertFalse(Files.exists(Paths.get("notExist"))); - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", - "-Djava.security.manager=allow", - "-Djdk.internal.lambda.dumpProxyClasses=notExist", - "com.example.TestLambda"); - assertEquals(tr.testOutput.stream() + public void testDumpDirNotExist() throws Exception { + Path testDir = Path.of("NotExist"); + Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES); + Files.createDirectory(testDir); + TestUtil.removeAll(dumpDir); + assertFalse(Files.exists(dumpDir)); + + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), + "-Djava.security.manager=allow", + "-Djdk.internal.lambda.dumpProxyClasses=" + DUMP_LAMBDA_PROXY_CLASS_FILES, + "com.example.TestLambda").directory(testDir.toFile()); + OutputAnalyzer outputAnalyzer = executeProcess(pb); + outputAnalyzer.shouldHaveExitValue(0); + assertEquals(outputAnalyzer.asLines().stream() .filter(s -> s.startsWith("WARNING")) .filter(s -> s.contains("does not exist")) .count(), 1, "only show error once"); - tr.assertZero("Should still return 0"); } @Test - public void testDumpDirIsFile() throws IOException { - assertTrue(Files.isRegularFile(Paths.get("file"))); - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", - "-Djava.security.manager=allow", - "-Djdk.internal.lambda.dumpProxyClasses=file", - "com.example.TestLambda"); - assertEquals(tr.testOutput.stream() - .filter(s -> s.startsWith("WARNING")) - .filter(s -> s.contains("not a directory")) - .count(), - 1, "only show error once"); - tr.assertZero("Should still return 0"); + public void testDumpDirIsFile() throws Exception { + Path testDir = Path.of("notDir"); + Path dumpFile = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES); + Files.createDirectory(testDir); + Files.createFile(dumpFile); + assertTrue(Files.isRegularFile(dumpFile)); + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), + "-Djava.security.manager=allow", + "-Djdk.internal.lambda.dumpProxyClasses=" + DUMP_LAMBDA_PROXY_CLASS_FILES, + "com.example.TestLambda").directory(testDir.toFile()); + executeProcess(pb) + .shouldContain("WARNING: Path DUMP_LAMBDA_PROXY_CLASS_FILES is not a directory") + .shouldHaveExitValue(0); } private static boolean isWriteableDirectory(Path p) { @@ -194,73 +208,77 @@ } @Test - public void testDumpDirNotWritable() throws IOException { - if (!Files.getFileStore(Paths.get(".")) - .supportsFileAttributeView(PosixFileAttributeView.class)) { + public void testDumpDirNotWritable() throws Exception { + FileStore fs; + try { + fs = Files.getFileStore(Paths.get(".")); + } catch (IOException e) { + throw new SkipException("WARNING: IOException occurred: " + e + ", Skipping testDumpDirNotWritable test."); + } + if (!fs.supportsFileAttributeView(PosixFileAttributeView.class)) { // No easy way to setup readonly directory without POSIX - // We would like to skip the test with a cause with - // throw new SkipException("Posix not supported"); - // but jtreg will report failure so we just pass the test - // which we can look at if jtreg changed its behavior - System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); - return; + throw new SkipException("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test."); } - Files.createDirectory(Paths.get("readOnly"), + Path testDir = Path.of("readOnly"); + Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES); + Files.createDirectory(testDir); + Files.createDirectory(dumpDir, asFileAttribute(fromString("r-xr-xr-x"))); try { - if (isWriteableDirectory(Paths.get("readOnly"))) { + if (isWriteableDirectory(dumpDir)) { // Skipping the test: it's allowed to write into read-only directory // (e.g. current user is super user). - System.out.println("WARNING: readOnly directory is writeable. Skipping testDumpDirNotWritable test."); - return; + throw new SkipException("WARNING: The dump directory is writeable. Skipping testDumpDirNotWritable test."); } - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), "-Djava.security.manager=allow", - "-Djdk.internal.lambda.dumpProxyClasses=readOnly", - "com.example.TestLambda"); - assertEquals(tr.testOutput.stream() - .filter(s -> s.startsWith("WARNING")) - .filter(s -> s.contains("not writable")) - .count(), - 1, "only show error once"); - tr.assertZero("Should still return 0"); + "-Djdk.internal.lambda.dumpProxyClasses=" + DUMP_LAMBDA_PROXY_CLASS_FILES, + "com.example.TestLambda").directory(testDir.toFile()); + executeProcess(pb) + .shouldContain("DUMP_LAMBDA_PROXY_CLASS_FILES is not writable") + .shouldHaveExitValue(0); } finally { - TestUtil.removeAll(Paths.get("readOnly")); + TestUtil.removeAll(testDir); } } @Test - public void testLoggingException() throws IOException { + public void testLoggingException() throws Exception { + Path testDir = Path.of("dumpLong"); + Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES); + Files.createDirectories(dumpDir.resolve("com/example/nonsense")); + Files.createFile(dumpDir.resolve("com/example/nonsense/nonsense")); assertTrue(Files.exists(Paths.get("dumpLong"))); - TestResult tr = doExec(JAVA_CMD.getAbsolutePath(), - "-cp", ".", - "-Djava.security.manager=allow", - "-Djdk.internal.lambda.dumpProxyClasses=dumpLong", - longFQCN); - assertEquals(tr.testOutput.stream() + ProcessBuilder pb = createLimitedTestJavaProcessBuilder( + "-cp", CLASSES.toString(), + "-Djava.security.manager=allow", + "-Djdk.internal.lambda.dumpProxyClasses=" + DUMP_LAMBDA_PROXY_CLASS_FILES, + longFQCN).directory(testDir.toFile()); + OutputAnalyzer outputAnalyzer = executeProcess(pb); + outputAnalyzer.shouldHaveExitValue(0); + assertEquals(outputAnalyzer.asLines().stream() .filter(s -> s.startsWith("WARNING: Exception")) .count(), 2, "show error each capture"); - // dumpLong/com/example/nonsense/nonsense - Path dumpPath = Paths.get("dumpLong/com/example/nonsense"); + // dumpLong/DUMP_LAMBDA_PROXY_CLASS_FILES/com/example/nonsense/nonsense + Path dumpPath = dumpDir.resolve("com/example/nonsense"); Predicate filter = p -> p.getParent() == null || dumpPath.startsWith(p) || p.startsWith(dumpPath); boolean debug = true; if (debug) { - Files.walk(Paths.get("dumpLong")) + Files.walk(dumpDir) .forEachOrdered(p -> { if (filter.test(p)) { System.out.println("accepted: " + p.toString()); } else { - System.out.println("filetered out: " + p.toString()); + System.out.println("filtered out: " + p.toString()); } }); } - assertEquals(Files.walk(Paths.get("dumpLong")) + assertEquals(Files.walk(dumpDir) .filter(filter) .count(), 5, "Two lambda captured failed to log"); - tr.assertZero("Should still return 0"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java openjdk-17-17.0.15+6/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java --- openjdk-17-17.0.14+7/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/lang/reflect/exeCallerAccessTest/CallerAccessTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,34 +34,15 @@ // Test disabled on AIX since we cannot invoke the JVM on the primordial thread. -import java.io.File; -import java.util.Map; import jdk.test.lib.Platform; -import jdk.test.lib.process.OutputAnalyzer; - -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; +import jdk.test.lib.process.ProcessTools; public class CallerAccessTest { - public static void main(String[] args) throws IOException { - Path launcher = Paths.get(System.getProperty("test.nativepath"), "CallerAccessTest"); - ProcessBuilder pb = new ProcessBuilder(launcher.toString()); - Map env = pb.environment(); - - String libDir = Platform.libDir().toString(); - String vmDir = Platform.jvmLibDir().toString(); - - // set up shared library path - String sharedLibraryPathEnvName = Platform.sharedLibraryPathVariableName(); - env.compute(sharedLibraryPathEnvName, - (k, v) -> (v == null) ? libDir : v + File.pathSeparator + libDir); - env.compute(sharedLibraryPathEnvName, - (k, v) -> (v == null) ? vmDir : v + File.pathSeparator + vmDir); - - System.out.println("Launching: " + launcher + " shared library path: " + - env.get(sharedLibraryPathEnvName)); - new OutputAnalyzer(pb.start()).shouldHaveExitValue(0); + public static void main(String[] args) throws Exception { + ProcessBuilder pb = ProcessTools.createNativeTestProcessBuilder("CallerAccessTest"); + System.out.println("Launching: " + pb.command() + " shared library path: " + + pb.environment().get(Platform.sharedLibraryPathVariableName())); + ProcessTools.executeProcess(pb).shouldHaveExitValue(0); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/net/Socket/CloseAvailable.java openjdk-17-17.0.15+6/test/jdk/java/net/Socket/CloseAvailable.java --- openjdk-17-17.0.14+7/test/jdk/java/net/Socket/CloseAvailable.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/net/Socket/CloseAvailable.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ * @test * @bug 4091859 8189366 * @library /test/lib - * @summary Test Socket.available() + * @summary Test Socket.getInputStream().available() * @run main CloseAvailable * @run main/othervm -Djava.net.preferIPv4Stack=true CloseAvailable */ @@ -48,110 +48,141 @@ testIOEOnClosed(false); } + /* + * Verifies that the Socket.getInputStream().available() throws an IOException + * if invoked after the socket has been closed. + */ static void testClose() throws IOException { - boolean error = true; - InetAddress addr = InetAddress.getLocalHost(); - ServerSocket ss = new ServerSocket(0, 0, addr); - int port = ss.getLocalPort(); - - Thread t = new Thread(new Thread("Close-Available-1") { - public void run() { - try { - Socket s = new Socket(addr, port); - s.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - - t.start(); - - Socket soc = ss.accept(); - ss.close(); - - DataInputStream is = new DataInputStream(soc.getInputStream()); - is.close(); - + System.out.println("testClose"); + final InetAddress addr = InetAddress.getLoopbackAddress(); + final Socket acceptedSocket; + try (final ServerSocket ss = new ServerSocket(0, 0, addr)) { + System.out.println("created server socket: " + ss); + final int port = ss.getLocalPort(); + // start a thread which initiates a socket connection to the server + //Thread.ofPlatform().name("Close-Available-1") + // .start(() -> { + Thread t = new Thread(new Thread("Close-Available-1") { + public void run() { + try { + final Socket s = new Socket(addr, port); + System.out.println("created socket: " + s); + s.close(); + System.out.println("closed socket: " + s); + } catch (Exception e) { + System.err.println("exception in " + Thread.currentThread().getName() + + ": " + e); + e.printStackTrace(); + } + } + }); + + t.start(); + + // accept the client connect + acceptedSocket = ss.accept(); + System.out.println(ss + " accepted connection " + acceptedSocket); + } // (intentionally) close the ServerSocket + + final DataInputStream is = new DataInputStream(acceptedSocket.getInputStream()); + is.close(); // close the inputstream and thus the underlying socket + System.out.println("closed inputstream of socket: " + acceptedSocket); try { - is.available(); - } - catch (IOException ex) { - error = false; + final int av = is.available(); + // available() was expected to fail but didn't + throw new AssertionError("Socket.getInputStream().available() was expected to fail on " + + acceptedSocket + " but returned " + av); + } catch (IOException ex) { + // expected IOException + System.out.println("received the expected IOException: " + ex); } - if (error) - throw new RuntimeException("Available() can be called after stream closed."); } - // Verifies consistency of `available` behaviour when EOF reached, both - // explicitly and implicitly. + /* + * Verifies consistency of Socket.getInputStream().available() behaviour when EOF reached, both + * explicitly and implicitly. + */ static void testEOF(boolean readUntilEOF) throws IOException { System.out.println("testEOF, readUntilEOF: " + readUntilEOF); - InetAddress addr = InetAddress.getLoopbackAddress(); - ServerSocket ss = new ServerSocket(); - ss.bind(new InetSocketAddress(addr, 0), 0); - int port = ss.getLocalPort(); - - try (Socket s = new Socket(addr, port)) { - s.getOutputStream().write(0x42); - s.shutdownOutput(); - - try (Socket soc = ss.accept()) { - ss.close(); - - InputStream is = soc.getInputStream(); - int b = is.read(); - assert b == 0x42; - assert !s.isClosed(); - if (readUntilEOF) { - b = is.read(); - assert b == -1; + final InetAddress addr = InetAddress.getLoopbackAddress(); + try (final ServerSocket ss = new ServerSocket()) { + ss.bind(new InetSocketAddress(addr, 0), 0); + System.out.println("server socket bound: " + ss); + final int port = ss.getLocalPort(); + try (final Socket s = new Socket(addr, port)) { + System.out.println("created socket: " + s); + s.getOutputStream().write(0x42); + s.shutdownOutput(); + + try (final Socket soc = ss.accept()) { + System.out.println("accepted socket: " + soc); + ss.close(); + System.out.println("closed server socket: " + ss); + + final InputStream is = soc.getInputStream(); + int b = is.read(); + assert b == 0x42 : "unexpected byte read: " + b; + assert !s.isClosed() : "socket " + s + " is unexpectedly closed"; + if (readUntilEOF) { + b = is.read(); + assert b == -1 : "unexpected number of bytes read: " + b; + } + + int a; + for (int i = 0; i < 100; i++) { + a = is.available(); + System.out.print(a + ", "); + if (a != 0) { + throw new RuntimeException("Unexpected non-zero available: " + a); + } + } + assert !s.isClosed() : "socket " + s + " is unexpectedly closed"; + final int more = is.read(); + assert more == -1 : "unexpected byte read: " + more; } - - int a; - for (int i = 0; i < 100; i++) { - a = is.available(); - System.out.print(a + ", "); - if (a != 0) - throw new RuntimeException("Unexpected non-zero available: " + a); - } - assert !s.isClosed(); - assert is.read() == -1; } } System.out.println("\ncomplete"); } - // Verifies IOException thrown by `available`, on a closed input stream - // that may, or may not, have reached EOF prior to closure. + /* + * Verifies IOException thrown by Socket.getInputStream().available(), on a closed input stream + * that may, or may not, have reached EOF prior to closure. + */ static void testIOEOnClosed(boolean readUntilEOF) throws IOException { System.out.println("testIOEOnClosed, readUntilEOF: " + readUntilEOF); - InetAddress addr = InetAddress.getLoopbackAddress(); - ServerSocket ss = new ServerSocket(); - ss.bind(new InetSocketAddress(addr, 0), 0); - int port = ss.getLocalPort(); - - try (Socket s = new Socket(addr, port)) { - s.getOutputStream().write(0x43); - s.shutdownOutput(); - - try (Socket soc = ss.accept()) { - ss.close(); - - InputStream is = soc.getInputStream(); - int b = is.read(); - assert b == 0x43; - assert !s.isClosed(); - if (readUntilEOF) { - b = is.read(); - assert b == -1; - } - is.close(); - try { - b = is.available(); - throw new RuntimeException("UNEXPECTED successful read: " + b); - } catch (IOException expected) { - System.out.println("caught expected IOException:" + expected); + final InetAddress addr = InetAddress.getLoopbackAddress(); + try (final ServerSocket ss = new ServerSocket()) { + ss.bind(new InetSocketAddress(addr, 0), 0); + System.out.println("server socket bound: " + ss); + final int port = ss.getLocalPort(); + + try (final Socket s = new Socket(addr, port)) { + System.out.println("created socket: " + s); + s.getOutputStream().write(0x43); + s.shutdownOutput(); + + try (final Socket soc = ss.accept()) { + System.out.println("accepted socket: " + soc); + ss.close(); + System.out.println("closed server socket: " + ss); + + final InputStream is = soc.getInputStream(); + int b = is.read(); + assert b == 0x43 : "unexpected byte read: " + b; + assert !s.isClosed() : "socket " + s + " is unexpectedly closed"; + if (readUntilEOF) { + b = is.read(); + assert b == -1 : "unexpected byte read: " + b; + } + is.close(); + System.out.println("closed inputstream of socket: " + soc); + try { + b = is.available(); + throw new RuntimeException("UNEXPECTED successful read: " + b); + } catch (IOException expected) { + System.out.println("caught expected IOException:" + expected); + } } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/net/httpclient/ManyRequests2.java openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/ManyRequests2.java --- openjdk-17-17.0.14+7/test/jdk/java/net/httpclient/ManyRequests2.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/ManyRequests2.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,13 +33,13 @@ * @compile ../../../com/sun/net/httpserver/EchoHandler.java * @compile ../../../com/sun/net/httpserver/FileServerHandler.java * @build ManyRequests ManyRequests2 - * @run main/othervm/timeout=40 -Dtest.XFixed=true + * @run main/othervm/timeout=400 -Dsun.net.httpserver.idleInterval=400 -Dtest.XFixed=true * -Djdk.httpclient.HttpClient.log=channel ManyRequests2 - * @run main/othervm/timeout=40 -Dtest.XFixed=true -Dtest.insertDelay=true + * @run main/othervm/timeout=400 -Dsun.net.httpserver.idleInterval=400 -Dtest.XFixed=true -Dtest.insertDelay=true * -Djdk.httpclient.HttpClient.log=channel ManyRequests2 - * @run main/othervm/timeout=40 -Dtest.XFixed=true -Dtest.chunkSize=64 + * @run main/othervm/timeout=400 -Dsun.net.httpserver.idleInterval=400 -Dtest.XFixed=true -Dtest.chunkSize=64 * -Djdk.httpclient.HttpClient.log=channel ManyRequests2 - * @run main/othervm/timeout=40 -Djdk.internal.httpclient.debug=true + * @run main/othervm/timeout=400 -Dsun.net.httpserver.idleInterval=400 -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.HttpClient.log=channel * -Dtest.XFixed=true -Dtest.insertDelay=true * -Dtest.chunkSize=64 ManyRequests2 diff -Nru openjdk-17-17.0.14+7/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/net/httpclient/PlainProxyConnectionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,8 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; +import jdk.httpclient.test.lib.common.HttpServerAdapters; + import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; @@ -51,15 +53,28 @@ * @bug 8230526 * @summary Verifies that PlainProxyConnections are cached and reused properly. We do this by * verifying that the remote address of the HTTP exchange (on the fake proxy server) - * is always the same InetSocketAddress. - * @modules jdk.httpserver - * @run main/othervm PlainProxyConnectionTest - * @author danielfuchs + * is always the same InetSocketAddress. Logging verbosity is increased to aid in + * diagnosis of intermittent failures. + * @library /test/lib + * /test/jdk/java/net/httpclient/lib + * @run main/othervm + * -Djdk.httpclient.HttpClient.log=headers,requests,trace + * -Djdk.internal.httpclient.debug=true + * PlainProxyConnectionTest */ public class PlainProxyConnectionTest { + // Increase logging verbosity to troubleshoot intermittent failures + static { + HttpServerAdapters.enableServerLogging(); + } + static final String RESPONSE = "

    Hello World!"; - static final String PATH = "/foo/"; + + // Adding some salt to the path to avoid other parallel running tests mistakenly connect to our test server + private static final String PATH = String.format( + "/%s-%d", PlainProxyConnectionTest.class.getSimpleName(), PlainProxyConnectionTest.class.hashCode()); + static final ConcurrentLinkedQueue connections = new ConcurrentLinkedQueue<>(); // For convenience the server is used both as a plain server and as a plain proxy. diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/channels/FileChannel/LoopingTruncate.java openjdk-17-17.0.15+6/test/jdk/java/nio/channels/FileChannel/LoopingTruncate.java --- openjdk-17-17.0.14+7/test/jdk/java/nio/channels/FileChannel/LoopingTruncate.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/channels/FileChannel/LoopingTruncate.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8137121 8137230 * @summary (fc) Infinite loop FileChannel.truncate @@ -31,12 +31,12 @@ */ import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; import java.nio.channels.ClosedByInterruptException; +import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; -import static java.nio.file.StandardOpenOption.*; import java.util.concurrent.TimeUnit; +import static java.nio.file.StandardOpenOption.*; import static jdk.test.lib.Utils.adjustTimeout; public class LoopingTruncate { @@ -48,7 +48,10 @@ static long TIMEOUT = adjustTimeout(20_000); public static void main(String[] args) throws Throwable { - Path path = Files.createTempFile("LoopingTruncate.tmp", null); + // Intentionally opting out from the default `java.io.tmpdir`. + // It occasionally lacks the sufficient disk space this test needs. + Path pathDir = Path.of(System.getProperty("user.dir")); + Path path = Files.createTempFile(pathDir, "LoopingTruncate.tmp", null); try (FileChannel fc = FileChannel.open(path, CREATE, WRITE)) { fc.position(FATEFUL_SIZE + 1L); System.out.println(" Writing large file..."); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/channels/Selector/WakeupNow.java openjdk-17-17.0.15+6/test/jdk/java/nio/channels/Selector/WakeupNow.java --- openjdk-17-17.0.14+7/test/jdk/java/nio/channels/Selector/WakeupNow.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/channels/Selector/WakeupNow.java 2025-04-09 19:45:33.000000000 +0000 @@ -26,7 +26,9 @@ * @summary Ensure that the wakeup state is cleared by selectNow() */ -import java.nio.channels.*; +import java.nio.channels.Pipe; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; public class WakeupNow { @@ -47,14 +49,15 @@ // ensure wakeup is consumed by selectNow Thread.sleep(2000); sel.selectNow(); - long startTime = System.currentTimeMillis(); + long startTime = System.nanoTime(); int n = sel.select(2000); - long endTime = System.currentTimeMillis(); + long endTime = System.nanoTime(); p.source().close(); p.sink().close(); sel.close(); - if (endTime - startTime < 1000) - throw new RuntimeException("test failed"); + long delta = endTime - startTime; + if (delta < 1_000_000_000) + throw new RuntimeException("test failed with delta " + delta); } // Test if selectNow clears wakeup with only the wakeup fd @@ -62,18 +65,17 @@ // This fails before the fix on Solaris private static void test2() throws Exception { Selector sel = Selector.open(); - Pipe p = Pipe.open(); - p.source().configureBlocking(false); sel.wakeup(); // ensure wakeup is consumed by selectNow Thread.sleep(2000); sel.selectNow(); - long startTime = System.currentTimeMillis(); + long startTime = System.nanoTime(); int n = sel.select(2000); - long endTime = System.currentTimeMillis(); + long endTime = System.nanoTime(); sel.close(); - if (endTime - startTime < 1000) - throw new RuntimeException("test failed"); + long delta = endTime - startTime; + if (delta < 1_000_000_000) + throw new RuntimeException("test failed with delta " + delta); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/file/Files/probeContentType/Basic.java openjdk-17-17.0.15+6/test/jdk/java/nio/file/Files/probeContentType/Basic.java --- openjdk-17-17.0.14+7/test/jdk/java/nio/file/Files/probeContentType/Basic.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/file/Files/probeContentType/Basic.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ import jdk.test.lib.Platform; import jdk.test.lib.OSVersion; +import jdk.internal.util.StaticProperty; /** * Uses Files.probeContentType to probe html file, custom file type, and minimal @@ -82,7 +83,7 @@ if (!expected.equals(actual)) { if (!Platform.isWindows()) { Path userMimeTypes = - Paths.get(System.getProperty("user.home"), ".mime.types"); + Paths.get(StaticProperty.userHome(), ".mime.types"); checkMimeTypesFile(userMimeTypes); Path etcMimeTypes = Paths.get("/etc/mime.types"); @@ -187,9 +188,10 @@ exTypes.add(new ExType("xlsx", List.of("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))); // exTypes.add(new ExType("wasm", List.of("application/wasm"))); Note. "wasm" is added via JDK-8297609 (Java 20) which not exist in current java version yet - // extensions with content type that differs on Windows 11+ + // extensions with content type that differs on Windows 11+ and + // Windows Server 2025 if (Platform.isWindows() && - (System.getProperty("os.name").endsWith("11") || + (System.getProperty("os.name").matches("^.*[11|2025]$") || new OSVersion(10, 0).compareTo(OSVersion.current()) > 0)) { System.out.println("Windows 11+ detected: using different types"); exTypes.add(new ExType("bz2", List.of("application/bz2", "application/x-bzip2", "application/x-bzip", "application/x-compressed"))); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTime.java openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTime.java --- openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTime.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTime.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,6 @@ /* * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,7 +29,7 @@ * @library ../.. /test/lib * @build jdk.test.lib.Platform * @comment We see this failing with "UnsatisfiedLinkError: Native Library ...libCreationTimeHelper.so already loaded in another classloader". Thus run as othervm - * @run main/othervm CreationTime + * @run main/othervm/native CreationTime */ /* @test id=cwd @@ -37,7 +38,7 @@ * scratch directory maybe at diff disk partition to /tmp on linux. * @library ../.. /test/lib * @build jdk.test.lib.Platform - * @run main/native CreationTime . + * @run main/othervm/native CreationTime . */ import java.nio.file.Path; @@ -51,8 +52,6 @@ public class CreationTime { - private static final java.io.PrintStream err = System.err; - /** * Reads the creationTime attribute */ @@ -78,14 +77,9 @@ FileTime creationTime = creationTime(file); Instant now = Instant.now(); if (Math.abs(creationTime.toMillis()-now.toEpochMilli()) > 10000L) { - System.out.println("creationTime.toMillis() == " + creationTime.toMillis()); - // If the file system doesn't support birth time, then skip this test - if (creationTime.toMillis() == 0) { - throw new SkippedException("birth time not support for: " + file); - } else { - err.println("File creation time reported as: " + creationTime); - throw new RuntimeException("Expected to be close to: " + now); - } + System.err.println("creationTime.toMillis() == " + creationTime.toMillis()); + System.err.println("File creation time reported as: " + creationTime); + throw new RuntimeException("Expected to be close to: " + now); } /** @@ -104,7 +98,12 @@ } } else if (Platform.isLinux()) { // Creation time read depends on statx system call support - supportsCreationTimeRead = CreationTimeHelper.linuxIsCreationTimeSupported(); + try { + supportsCreationTimeRead = CreationTimeHelper. + linuxIsCreationTimeSupported(file.toAbsolutePath().toString()); + } catch (Throwable e) { + supportsCreationTimeRead = false; + } // Creation time updates are not supported on Linux supportsCreationTimeWrite = false; } @@ -119,8 +118,11 @@ Instant plusHour = Instant.now().plusSeconds(60L * 60L); Files.setLastModifiedTime(file, FileTime.from(plusHour)); FileTime current = creationTime(file); - if (!current.equals(creationTime)) + if (!current.equals(creationTime)) { + System.err.println("current = " + current); + System.err.println("creationTime = " + creationTime); throw new RuntimeException("Creation time should not have changed"); + } } /** diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTimeHelper.java openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTimeHelper.java --- openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTimeHelper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/CreationTimeHelper.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,6 @@ /* * Copyright (c) 2023, Red Hat, Inc. + * Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,6 +21,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + public class CreationTimeHelper { static { @@ -27,5 +29,5 @@ } // Helper so as to determine 'statx' support on the runtime system - static native boolean linuxIsCreationTimeSupported(); + static native boolean linuxIsCreationTimeSupported(String file); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/libCreationTimeHelper.c openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/libCreationTimeHelper.c --- openjdk-17-17.0.14+7/test/jdk/java/nio/file/attribute/BasicFileAttributeView/libCreationTimeHelper.c 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/nio/file/attribute/BasicFileAttributeView/libCreationTimeHelper.c 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,6 @@ /* * Copyright (c) 2023, Red Hat, Inc. + * Copyright (c) 2024 Alibaba Group Holding Limited. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,17 +22,120 @@ * questions. */ #include "jni.h" +#include #if defined(__linux__) +#include +#include +#include +#include #include +#ifndef STATX_BASIC_STATS +#define STATX_BASIC_STATS 0x000007ffU +#endif +#ifndef STATX_BTIME +#define STATX_BTIME 0x00000800U +#endif +#ifndef RTLD_DEFAULT +#define RTLD_DEFAULT RTLD_LOCAL +#endif +#ifndef AT_SYMLINK_NOFOLLOW +#define AT_SYMLINK_NOFOLLOW 0x100 +#endif +#ifndef AT_FDCWD +#define AT_FDCWD -100 +#endif + +#ifndef __GLIBC__ +// Alpine doesn't know these types, define them +typedef unsigned int __uint32_t; +typedef unsigned short __uint16_t; +typedef unsigned long int __uint64_t; #endif +/* + * Timestamp structure for the timestamps in struct statx. + */ +struct my_statx_timestamp { + int64_t tv_sec; + __uint32_t tv_nsec; + int32_t __reserved; +}; + +/* + * struct statx used by statx system call on >= glibc 2.28 + * systems + */ +struct my_statx +{ + __uint32_t stx_mask; + __uint32_t stx_blksize; + __uint64_t stx_attributes; + __uint32_t stx_nlink; + __uint32_t stx_uid; + __uint32_t stx_gid; + __uint16_t stx_mode; + __uint16_t __statx_pad1[1]; + __uint64_t stx_ino; + __uint64_t stx_size; + __uint64_t stx_blocks; + __uint64_t stx_attributes_mask; + struct my_statx_timestamp stx_atime; + struct my_statx_timestamp stx_btime; + struct my_statx_timestamp stx_ctime; + struct my_statx_timestamp stx_mtime; + __uint32_t stx_rdev_major; + __uint32_t stx_rdev_minor; + __uint32_t stx_dev_major; + __uint32_t stx_dev_minor; + __uint64_t __statx_pad2[14]; +}; + +typedef int statx_func(int dirfd, const char *restrict pathname, int flags, + unsigned int mask, struct my_statx *restrict statxbuf); + +static statx_func* my_statx_func = NULL; +#endif //#defined(__linux__) + // static native boolean linuxIsCreationTimeSupported() JNIEXPORT jboolean JNICALL -Java_CreationTimeHelper_linuxIsCreationTimeSupported(JNIEnv *env, jclass cls) -{ +Java_CreationTimeHelper_linuxIsCreationTimeSupported(JNIEnv *env, jclass cls, jstring file) { #if defined(__linux__) - void* statx_func = dlsym(RTLD_DEFAULT, "statx"); - return statx_func != NULL ? JNI_TRUE : JNI_FALSE; + struct my_statx stx = {0}; + int ret, atflag = AT_SYMLINK_NOFOLLOW; + unsigned int mask = STATX_BASIC_STATS | STATX_BTIME; + + my_statx_func = (statx_func*) dlsym(RTLD_DEFAULT, "statx"); + if (my_statx_func == NULL) { + return false; + } + + if (file == NULL) { + printf("input file error!\n"); + return JNI_FALSE; + } + const char *utfChars = (*env)->GetStringUTFChars(env, file, NULL); + if (utfChars == NULL) { + printf("jstring convert to char array error!\n"); + return JNI_FALSE; + } + + ret = my_statx_func(AT_FDCWD, utfChars, atflag, mask, &stx); + + if (file != NULL && utfChars != NULL) { + (*env)->ReleaseStringUTFChars(env, file, utfChars); + } + + if (ret != 0) { + return JNI_FALSE; + } + + // On some systems where statx is available but birth time might still not + // be supported as it's file system specific. The only reliable way to + // check for supported or not is looking at the filled in STATX_BTIME bit + // in the returned statx buffer mask. + if ((stx.stx_mask & STATX_BTIME) != 0) + return JNI_TRUE; + return JNI_FALSE; #else return JNI_FALSE; #endif diff -Nru openjdk-17-17.0.14+7/test/jdk/java/security/Policy/Root/Root.java openjdk-17-17.0.15+6/test/jdk/java/security/Policy/Root/Root.java --- openjdk-17-17.0.14+7/test/jdk/java/security/Policy/Root/Root.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/security/Policy/Root/Root.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,27 +22,82 @@ */ /* - * + * @test * @bug 4619757 * @summary User Policy Setting is not recognized on Netscape 6 * when invoked as root. - * @run main/manual Root + * @library /test/lib + * @requires os.family != "windows" + * @run testng/othervm/manual Root */ /* - * Place Root.policy in the root home directory (/), - * as /.java.policy and run as test as root user. - */ +* Run test as root user. +* */ + +import org.testng.Assert; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.security.*; public class Root { - public static void main(String[] args) { - Policy p = Policy.getPolicy(); - if (p.implies(Root.class.getProtectionDomain(), new AllPermission())) { - System.out.println("Test succeeded"); - } else { - throw new SecurityException("Test failed"); + private static final String SRC = System.getProperty("test.src"); + private static final String ROOT = System.getProperty("user.home"); + private static final Path SOURCE = Paths.get(SRC, "Root.policy"); + private static final Path TARGET = Paths.get(ROOT, ".java.policy"); + private static final Path BACKUP = Paths.get(ROOT, ".backup.policy"); + private static final String ROOT_USER_ID = "0"; + + @BeforeTest + public void setup() throws IOException { + // Backup user policy file if it already exists + if (TARGET.toFile().exists()) { + Files.copy(TARGET, BACKUP, StandardCopyOption.REPLACE_EXISTING); } + Files.copy(SOURCE, TARGET, StandardCopyOption.REPLACE_EXISTING); + } + + @AfterTest + public void cleanUp() throws IOException { + Files.delete(TARGET); + // Restore original policy file if backup exists + if (BACKUP.toFile().exists()) { + Files.copy(BACKUP, TARGET, StandardCopyOption.REPLACE_EXISTING); + Files.delete(BACKUP); + } + } + + @Test + private void test() throws InterruptedException, IOException { + System.out.println("Run test as root user."); + + Process process = Runtime.getRuntime().exec("id -u"); + process.waitFor(); + if (process.exitValue() != 0) { + throw new RuntimeException("Failed to retrieve user id."); + } + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream()))) { + String line = reader.readLine(); + + if (!ROOT_USER_ID.equals(line)) { + throw new RuntimeException( + "This test needs to be run with root privilege."); + } + } + + Policy p = Policy.getPolicy(); + Assert.assertTrue(p.implies(Root.class.getProtectionDomain(), + new AllPermission())); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/security/Security/ConfigFileTest.java openjdk-17-17.0.15+6/test/jdk/java/security/Security/ConfigFileTest.java --- openjdk-17-17.0.14+7/test/jdk/java/security/Security/ConfigFileTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/security/Security/ConfigFileTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,7 @@ * questions. */ +import jdk.test.lib.Utils; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; @@ -30,7 +31,9 @@ import java.security.Provider; import java.security.Security; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Optional; /* @@ -50,6 +53,9 @@ private static boolean overrideDetected = false; + private static Path COPY_JDK_DIR = Path.of("./jdk-8155246-tmpdir"); + private static Path COPIED_JAVA = COPY_JDK_DIR.resolve("bin").resolve("java"); + public static void main(String[] args) throws Exception { Path copyJdkDir = Path.of("./jdk-8155246-tmpdir"); Path copiedJava = Optional.of( @@ -72,29 +78,29 @@ String extraPropsFile = Path.of(System.getProperty("test.src"), "override.props").toString(); // sanity test -XshowSettings:security option - exerciseShowSettingsSecurity(copiedJava.toString(), "-cp", System.getProperty("test.classes"), - "-Djava.security.debug=all", "-XshowSettings:security", "ConfigFileTest", "runner"); + exerciseShowSettingsSecurity(buildCommand("-cp", System.getProperty("test.classes"), + "-Djava.security.debug=all", "-XshowSettings:security", "ConfigFileTest", "runner")); // exercise some debug flags while we're here // regular JDK install - should expect success exerciseSecurity(0, "java", - copiedJava.toString(), "-cp", System.getProperty("test.classes"), - "-Djava.security.debug=all", "-Djavax.net.debug=all", "ConfigFileTest", "runner"); + buildCommand("-cp", System.getProperty("test.classes"), + "-Djava.security.debug=all", "-Djavax.net.debug=all", "ConfigFileTest", "runner")); // given an overriding security conf file that doesn't exist, we shouldn't // overwrite the properties from original/master security conf file exerciseSecurity(0, "SUN version", - copiedJava.toString(), "-cp", System.getProperty("test.classes"), + buildCommand("-cp", System.getProperty("test.classes"), "-Djava.security.debug=all", "-Djavax.net.debug=all", "-Djava.security.properties==file:///" + extraPropsFile + "badFileName", - "ConfigFileTest", "runner"); + "ConfigFileTest", "runner")); // test JDK launch with customized properties file exerciseSecurity(0, "NumProviders: 6", - copiedJava.toString(), "-cp", System.getProperty("test.classes"), + buildCommand("-cp", System.getProperty("test.classes"), "-Djava.security.debug=all", "-Djavax.net.debug=all", "-Djava.security.properties==file:///" + extraPropsFile, - "ConfigFileTest", "runner"); + "ConfigFileTest", "runner")); // delete the master conf file Files.delete(Path.of(copyJdkDir.toString(), "conf", @@ -102,16 +108,16 @@ // launch JDK without java.security file being present or specified exerciseSecurity(1, "Error loading java.security file", - copiedJava.toString(), "-cp", System.getProperty("test.classes"), + buildCommand("-cp", System.getProperty("test.classes"), "-Djava.security.debug=all", "-Djavax.net.debug=all", - "ConfigFileTest", "runner"); + "ConfigFileTest", "runner")); // test the override functionality also. Should not be allowed since // "security.overridePropertiesFile=true" Security property is missing. exerciseSecurity(1, "Error loading java.security file", - copiedJava.toString(), "-cp", System.getProperty("test.classes"), + buildCommand("-cp", System.getProperty("test.classes"), "-Djava.security.debug=all", "-Djavax.net.debug=all", - "-Djava.security.properties==file:///" + extraPropsFile, "ConfigFileTest", "runner"); + "-Djava.security.properties==file:///" + extraPropsFile, "ConfigFileTest", "runner")); if (!overrideDetected) { throw new RuntimeException("Override scenario not seen"); @@ -119,8 +125,14 @@ } } - private static void exerciseSecurity(int exitCode, String output, String... args) throws Exception { - ProcessBuilder process = new ProcessBuilder(args); + private static ProcessBuilder buildCommand(String... command) { + ArrayList args = new ArrayList<>(); + args.add(COPIED_JAVA.toString()); + Collections.addAll(args, Utils.prependTestJavaOpts(command)); + return new ProcessBuilder(args); + } + + private static void exerciseSecurity(int exitCode, String output, ProcessBuilder process) throws Exception { OutputAnalyzer oa = ProcessTools.executeProcess(process); oa.shouldHaveExitValue(exitCode) .shouldContain(output); @@ -141,8 +153,7 @@ } // exercise the -XshowSettings:security launcher - private static void exerciseShowSettingsSecurity(String... args) throws Exception { - ProcessBuilder process = new ProcessBuilder(args); + private static void exerciseShowSettingsSecurity(ProcessBuilder process) throws Exception { OutputAnalyzer oa = ProcessTools.executeProcess(process); oa.shouldHaveExitValue(0) .shouldContain("Security properties:") diff -Nru openjdk-17-17.0.14+7/test/jdk/java/security/cert/CertPathValidator/OCSP/OCSPTimeout.java openjdk-17-17.0.15+6/test/jdk/java/security/cert/CertPathValidator/OCSP/OCSPTimeout.java --- openjdk-17-17.0.14+7/test/jdk/java/security/cert/CertPathValidator/OCSP/OCSPTimeout.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/security/cert/CertPathValidator/OCSP/OCSPTimeout.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +// +// Security properties, once set, cannot revert to unset. To avoid +// conflicts with tests running in the same VM isolate this test by +// running it in otherVM mode. +// + +/** + * @test + * @bug 8179502 + * @summary Enhance OCSP, CRL and Certificate Fetch Timeouts + * @modules java.base/sun.security.x509 + * java.base/sun.security.provider.certpath + * java.base/sun.security.util + * @library ../../../../../java/security/testlibrary + * @build CertificateBuilder SimpleOCSPServer + * @run main/othervm -Djava.security.debug=certpath OCSPTimeout 1000 true + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.ocsp.readtimeout=5 OCSPTimeout 1000 true + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.ocsp.readtimeout=1 OCSPTimeout 5000 false + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.ocsp.readtimeout=1s OCSPTimeout 5000 false + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.ocsp.readtimeout=1500ms OCSPTimeout 5000 false + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.ocsp.readtimeout=4500ms OCSPTimeout 1000 true + */ + +import java.io.*; +import java.math.BigInteger; +import java.net.*; +import java.security.*; +import java.security.cert.Certificate; +import java.security.spec.ECGenParameterSpec; +import java.util.*; +import java.security.cert.*; +import java.util.concurrent.TimeUnit; + +import sun.security.testlibrary.SimpleOCSPServer; +import sun.security.testlibrary.CertificateBuilder; + +import static java.security.cert.PKIXRevocationChecker.Option.*; + +public class OCSPTimeout { + + static String passwd = "passphrase"; + static String ROOT_ALIAS = "root"; + static String EE_ALIAS = "endentity"; + + // Enable debugging for additional output + static final boolean debug = true; + + // PKI components we will need for this test + static X509Certificate rootCert; // The root CA certificate + static X509Certificate eeCert; // The end entity certificate + static KeyStore rootKeystore; // Root CA Keystore + static KeyStore eeKeystore; // End Entity Keystore + static KeyStore trustStore; // SSL Client trust store + static SimpleOCSPServer rootOcsp; // Root CA OCSP Responder + static int rootOcspPort; // Port number for root OCSP + + public static void main(String[] args) throws Exception { + int ocspTimeout = 15000; + boolean expected = false; + + createPKI(); + + try { + if (args[0] != null) { + ocspTimeout = Integer.parseInt(args[0]); + } + rootOcsp.setDelay(ocspTimeout); + + expected = (args[1] != null && Boolean.parseBoolean(args[1])); + log("Test case expects to " + (expected ? "pass" : "fail")); + + // validate chain + CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); + PKIXRevocationChecker prc = + (PKIXRevocationChecker) cpv.getRevocationChecker(); + prc.setOptions(EnumSet.of(NO_FALLBACK, SOFT_FAIL)); + PKIXParameters params = + new PKIXParameters(Set.of(new TrustAnchor(rootCert, null))); + params.addCertPathChecker(prc); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + CertPath cp = cf.generateCertPath(List.of(eeCert)); + cpv.validate(cp, params); + + // unwrap soft fail exceptions and check for SocketTimeoutException + List softExc = prc.getSoftFailExceptions(); + if (expected) { + if (!softExc.isEmpty()) { + log("Expected to pass, found " + softExc.size() + + " soft fail exceptions"); + for (CertPathValidatorException cpve : softExc) { + log("Exception: " + cpve); + } + throw new RuntimeException("Expected to pass, found " + + softExc.size() + " soft fail exceptions"); + } + } else { + // If we expect to fail the validation then there should be a + // SocketTimeoutException + boolean found = false; + for (CertPathValidatorException softFail : softExc) { + log("CPVE: " + softFail); + Throwable cause = softFail.getCause(); + log("Cause: " + cause); + while (cause != null) { + if (cause instanceof SocketTimeoutException) { + found = true; + break; + } + cause = cause.getCause(); + } + if (found) { + break; + } + } + + if (!found) { + throw new RuntimeException("SocketTimeoutException not thrown"); + } + } + } finally { + rootOcsp.stop(); + rootOcsp.shutdownNow(); + } + } + + /** + * Creates the PKI components necessary for this test, including + * Root CA, Intermediate CA and SSL server certificates, the keystores + * for each entity, a client trust store, and starts the OCSP responders. + */ + private static void createPKI() throws Exception { + CertificateBuilder cbld = new CertificateBuilder(); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); + keyGen.initialize(new ECGenParameterSpec("secp256r1")); + KeyStore.Builder keyStoreBuilder = + KeyStore.Builder.newInstance("PKCS12", null, + new KeyStore.PasswordProtection(passwd.toCharArray())); + + // Generate Root and EE keys + KeyPair rootCaKP = keyGen.genKeyPair(); + log("Generated Root CA KeyPair"); + KeyPair eeKP = keyGen.genKeyPair(); + log("Generated End Entity KeyPair"); + + // Set up the Root CA Cert + cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany"); + cbld.setPublicKey(rootCaKP.getPublic()); + cbld.setSerialNumber(new BigInteger("1")); + // Make a 3 year validity starting from 60 days ago + long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60); + long end = start + TimeUnit.DAYS.toMillis(1085); + cbld.setValidity(new Date(start), new Date(end)); + addCommonExts(cbld, rootCaKP.getPublic(), rootCaKP.getPublic()); + addCommonCAExts(cbld); + // Make our Root CA Cert! + rootCert = cbld.build(null, rootCaKP.getPrivate(), + "SHA256withECDSA"); + log("Root CA Created:\n%s", certInfo(rootCert)); + + // Now build a keystore and add the keys and cert + rootKeystore = keyStoreBuilder.getKeyStore(); + Certificate[] rootChain = {rootCert}; + rootKeystore.setKeyEntry(ROOT_ALIAS, rootCaKP.getPrivate(), + passwd.toCharArray(), rootChain); + + // Now fire up the OCSP responder + rootOcsp = new SimpleOCSPServer(rootKeystore, passwd, ROOT_ALIAS, null); + rootOcsp.enableLog(debug); + rootOcsp.setNextUpdateInterval(3600); + rootOcsp.setDisableContentLength(true); + rootOcsp.start(); + + // Wait 60 seconds for server ready + boolean readyStatus = rootOcsp.awaitServerReady(60, TimeUnit.SECONDS); + if (!readyStatus) { + throw new RuntimeException("Server not ready"); + } + + rootOcspPort = rootOcsp.getPort(); + String rootRespURI = "http://localhost:" + rootOcspPort; + log("Root OCSP Responder URI is %s", rootRespURI); + + // Now that we have the root keystore and OCSP responder we can + // create our end entity certificate + cbld.reset(); + cbld.setSubjectName("CN=SSLCertificate, O=SomeCompany"); + cbld.setPublicKey(eeKP.getPublic()); + cbld.setSerialNumber(new BigInteger("4096")); + // Make a 1 year validity starting from 7 days ago + start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7); + end = start + TimeUnit.DAYS.toMillis(365); + cbld.setValidity(new Date(start), new Date(end)); + + // Add extensions + addCommonExts(cbld, eeKP.getPublic(), rootCaKP.getPublic()); + boolean[] kuBits = {true, false, false, false, false, false, + false, false, false}; + cbld.addKeyUsageExt(kuBits); + List ekuOids = new ArrayList<>(); + ekuOids.add("1.3.6.1.5.5.7.3.1"); + ekuOids.add("1.3.6.1.5.5.7.3.2"); + cbld.addExtendedKeyUsageExt(ekuOids); + cbld.addSubjectAltNameDNSExt(Collections.singletonList("localhost")); + cbld.addAIAExt(Collections.singletonList(rootRespURI)); + // Make our End Entity Cert! + eeCert = cbld.build(rootCert, rootCaKP.getPrivate(), + "SHA256withECDSA"); + log("SSL Certificate Created:\n%s", certInfo(eeCert)); + + // Provide end entity cert revocation info to the Root CA + // OCSP responder. + Map revInfo = + new HashMap<>(); + revInfo.put(eeCert.getSerialNumber(), + new SimpleOCSPServer.CertStatusInfo( + SimpleOCSPServer.CertStatus.CERT_STATUS_GOOD)); + rootOcsp.updateStatusDb(revInfo); + + // Now build a keystore and add the keys, chain and root cert as a TA + eeKeystore = keyStoreBuilder.getKeyStore(); + Certificate[] eeChain = {eeCert, rootCert}; + eeKeystore.setKeyEntry(EE_ALIAS, eeKP.getPrivate(), + passwd.toCharArray(), eeChain); + eeKeystore.setCertificateEntry(ROOT_ALIAS, rootCert); + + // And finally a Trust Store for the client + trustStore = keyStoreBuilder.getKeyStore(); + trustStore.setCertificateEntry(ROOT_ALIAS, rootCert); + } + + private static void addCommonExts(CertificateBuilder cbld, + PublicKey subjKey, PublicKey authKey) throws IOException { + cbld.addSubjectKeyIdExt(subjKey); + cbld.addAuthorityKeyIdExt(authKey); + } + + private static void addCommonCAExts(CertificateBuilder cbld) + throws IOException { + cbld.addBasicConstraintsExt(true, true, -1); + // Set key usage bits for digitalSignature, keyCertSign and cRLSign + boolean[] kuBitSettings = {true, false, false, false, false, true, + true, false, false}; + cbld.addKeyUsageExt(kuBitSettings); + } + + /** + * Helper routine that dumps only a few cert fields rather than + * the whole toString() output. + * + * @param cert an X509Certificate to be displayed + * + * @return the String output of the issuer, subject and + * serial number + */ + private static String certInfo(X509Certificate cert) { + StringBuilder sb = new StringBuilder(); + sb.append("Issuer: ").append(cert.getIssuerX500Principal()). + append("\n"); + sb.append("Subject: ").append(cert.getSubjectX500Principal()). + append("\n"); + sb.append("Serial: ").append(cert.getSerialNumber()).append("\n"); + return sb.toString(); + } + + /** + * Log a message on stdout + * + * @param format the format string for the log entry + * @param args zero or more arguments corresponding to the format string + */ + private static void log(String format, Object ... args) { + System.out.format(format + "\n", args); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/security/testlibrary/CertificateBuilder.java openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/CertificateBuilder.java --- openjdk-17-17.0.14+7/test/jdk/java/security/testlibrary/CertificateBuilder.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/CertificateBuilder.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -115,8 +115,9 @@ * @param name An {@link X500Principal} to be used as the subject name * on this certificate. */ - public void setSubjectName(X500Principal name) { + public CertificateBuilder setSubjectName(X500Principal name) { subjectName = name; + return this; } /** @@ -124,8 +125,9 @@ * * @param name The subject name in RFC 2253 format */ - public void setSubjectName(String name) { + public CertificateBuilder setSubjectName(String name) { subjectName = new X500Principal(name); + return this; } /** @@ -133,8 +135,9 @@ * * @param pubKey The {@link PublicKey} to be used on this certificate. */ - public void setPublicKey(PublicKey pubKey) { + public CertificateBuilder setPublicKey(PublicKey pubKey) { publicKey = Objects.requireNonNull(pubKey, "Caught null public key"); + return this; } /** @@ -143,9 +146,10 @@ * @param nbDate A {@link Date} object specifying the start of the * certificate validity period. */ - public void setNotBefore(Date nbDate) { + public CertificateBuilder setNotBefore(Date nbDate) { Objects.requireNonNull(nbDate, "Caught null notBefore date"); notBefore = (Date)nbDate.clone(); + return this; } /** @@ -154,9 +158,10 @@ * @param naDate A {@link Date} object specifying the end of the * certificate validity period. */ - public void setNotAfter(Date naDate) { + public CertificateBuilder setNotAfter(Date naDate) { Objects.requireNonNull(naDate, "Caught null notAfter date"); notAfter = (Date)naDate.clone(); + return this; } /** @@ -167,9 +172,8 @@ * @param naDate A {@link Date} object specifying the end of the * certificate validity period. */ - public void setValidity(Date nbDate, Date naDate) { - setNotBefore(nbDate); - setNotAfter(naDate); + public CertificateBuilder setValidity(Date nbDate, Date naDate) { + return setNotBefore(nbDate).setNotAfter(naDate); } /** @@ -177,9 +181,10 @@ * * @param serial A serial number in {@link BigInteger} form. */ - public void setSerialNumber(BigInteger serial) { + public CertificateBuilder setSerialNumber(BigInteger serial) { Objects.requireNonNull(serial, "Caught null serial number"); serialNumber = serial; + return this; } @@ -188,9 +193,10 @@ * * @param ext The extension to be added. */ - public void addExtension(Extension ext) { + public CertificateBuilder addExtension(Extension ext) { Objects.requireNonNull(ext, "Caught null extension"); extensions.put(ext.getId(), ext); + return this; } /** @@ -199,11 +205,12 @@ * @param extList The {@link List} of extensions to be added to * the certificate. */ - public void addExtensions(List extList) { + public CertificateBuilder addExtensions(List extList) { Objects.requireNonNull(extList, "Caught null extension list"); for (Extension ext : extList) { extensions.put(ext.getId(), ext); } + return this; } /** @@ -213,7 +220,8 @@ * * @throws IOException if an encoding error occurs. */ - public void addSubjectAltNameDNSExt(List dnsNames) throws IOException { + public CertificateBuilder addSubjectAltNameDNSExt(List dnsNames) + throws IOException { if (!dnsNames.isEmpty()) { GeneralNames gNames = new GeneralNames(); for (String name : dnsNames) { @@ -222,29 +230,57 @@ addExtension(new SubjectAlternativeNameExtension(false, gNames)); } + return this; } /** * Helper method to add one or more OCSP URIs to the Authority Info Access - * certificate extension. + * certificate extension. Location strings can be in two forms: + * 1) Just a URI by itself: This will be treated as using the OCSP + * access description (legacy behavior). + * 2) An access description name (case-insensitive) followed by a + * pipe (|) and the URI (e.g. OCSP|http://ocsp.company.com/revcheck). + * Current description names are OCSP and CAISSUER. Others may be + * added later. * - * @param locations A list of one or more OCSP responder URIs as strings + * @param locations A list of one or more access descriptor URIs as strings * * @throws IOException if an encoding error occurs. */ - public void addAIAExt(List locations) + public CertificateBuilder addAIAExt(List locations) throws IOException { if (!locations.isEmpty()) { List acDescList = new ArrayList<>(); - for (String ocspUri : locations) { - acDescList.add(new AccessDescription( - AccessDescription.Ad_OCSP_Id, - new GeneralName(new URIName(ocspUri)))); + for (String loc : locations) { + String[] tokens = loc.split("\\|", 2); + ObjectIdentifier adObj; + String uriLoc; + if (tokens.length == 1) { + // Legacy form, assume OCSP + adObj = AccessDescription.Ad_OCSP_Id; + uriLoc = tokens[0]; + } else { + switch (tokens[0].toUpperCase()) { + case "OCSP": + adObj = AccessDescription.Ad_OCSP_Id; + break; + case "CAISSUER": + adObj = AccessDescription.Ad_CAISSUERS_Id; + break; + default: + throw new IOException("Unknown AD: " + tokens[0]); + } + uriLoc = tokens[1]; + } + acDescList.add(new AccessDescription(adObj, + new GeneralName(new URIName(uriLoc)))); } addExtension(new AuthorityInfoAccessExtension(acDescList)); } + return this; } + /** * Set a Key Usage extension for the certificate. The extension will * be marked critical. @@ -254,8 +290,9 @@ * * @throws IOException if an encoding error occurs. */ - public void addKeyUsageExt(boolean[] bitSettings) throws IOException { - addExtension(new KeyUsageExtension(bitSettings)); + public CertificateBuilder addKeyUsageExt(boolean[] bitSettings) + throws IOException { + return addExtension(new KeyUsageExtension(bitSettings)); } /** @@ -270,9 +307,10 @@ * * @throws IOException if an encoding error occurs. */ - public void addBasicConstraintsExt(boolean crit, boolean isCA, + public CertificateBuilder addBasicConstraintsExt(boolean crit, boolean isCA, int maxPathLen) throws IOException { - addExtension(new BasicConstraintsExtension(crit, isCA, maxPathLen)); + return addExtension(new BasicConstraintsExtension(crit, isCA, + maxPathLen)); } /** @@ -282,9 +320,9 @@ * * @throws IOException if an encoding error occurs. */ - public void addAuthorityKeyIdExt(X509Certificate authorityCert) + public CertificateBuilder addAuthorityKeyIdExt(X509Certificate authorityCert) throws IOException { - addAuthorityKeyIdExt(authorityCert.getPublicKey()); + return addAuthorityKeyIdExt(authorityCert.getPublicKey()); } /** @@ -294,9 +332,11 @@ * * @throws IOException if an encoding error occurs. */ - public void addAuthorityKeyIdExt(PublicKey authorityKey) throws IOException { + public CertificateBuilder addAuthorityKeyIdExt(PublicKey authorityKey) + throws IOException { KeyIdentifier kid = new KeyIdentifier(authorityKey); - addExtension(new AuthorityKeyIdentifierExtension(kid, null, null)); + return addExtension(new AuthorityKeyIdentifierExtension(kid, + null, null)); } /** @@ -306,9 +346,10 @@ * * @throws IOException if an encoding error occurs. */ - public void addSubjectKeyIdExt(PublicKey subjectKey) throws IOException { + public CertificateBuilder addSubjectKeyIdExt(PublicKey subjectKey) + throws IOException { byte[] keyIdBytes = new KeyIdentifier(subjectKey).getIdentifier(); - addExtension(new SubjectKeyIdentifierExtension(keyIdBytes)); + return addExtension(new SubjectKeyIdentifierExtension(keyIdBytes)); } /** @@ -318,7 +359,7 @@ * * @throws IOException if an encoding error occurs. */ - public void addExtendedKeyUsageExt(List ekuOids) + public CertificateBuilder addExtendedKeyUsageExt(List ekuOids) throws IOException { if (!ekuOids.isEmpty()) { Vector oidVector = new Vector<>(); @@ -327,13 +368,14 @@ } addExtension(new ExtendedKeyUsageExtension(oidVector)); } + return this; } /** * Clear all settings and return the {@code CertificateBuilder} to * its default state. */ - public void reset() { + public CertificateBuilder reset() { extensions.clear(); subjectName = null; notBefore = null; @@ -342,6 +384,7 @@ publicKey = null; signatureBytes = null; tbsCertBytes = null; + return this; } /** @@ -383,7 +426,7 @@ * @param issuerCert The certificate of the issuing authority, or * {@code null} if the resulting certificate is self-signed. * @param issuerKey The private key of the issuing authority - * @param signAlg The signature algorithm object + * @param algName The signature algorithm object * * @return The DER-encoded X.509 certificate * @@ -449,10 +492,13 @@ DerOutputStream tbsCertSeq = new DerOutputStream(); DerOutputStream tbsCertItems = new DerOutputStream(); - // Hardcode to V3 - byte[] v3int = {0x02, 0x01, 0x02}; - tbsCertItems.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, - (byte)0), v3int); + // If extensions exist then it needs to be v3, otherwise + // we can make it v1 and omit the version field as v1 is the default. + if (!extensions.isEmpty()) { + byte[] v3int = {0x02, 0x01, 0x02}; + tbsCertItems.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, + (byte) 0), v3int); + } // Serial Number SerialNumber sn = new SerialNumber(serialNumber); @@ -482,7 +528,7 @@ // SubjectPublicKeyInfo tbsCertItems.write(publicKey.getEncoded()); - // TODO: Extensions! + // Encode any extensions in the builder encodeExtensions(tbsCertItems); // Wrap it all up in a SEQUENCE and return the bytes @@ -523,5 +569,4 @@ tbsStream.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)3), extSequence); } - } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/security/testlibrary/SimpleOCSPServer.java openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/SimpleOCSPServer.java --- openjdk-17-17.0.14+7/test/jdk/java/security/testlibrary/SimpleOCSPServer.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/security/testlibrary/SimpleOCSPServer.java 2025-04-09 19:45:33.000000000 +0000 @@ -574,8 +574,8 @@ */ private synchronized void log(String message) { if (logEnabled || debug != null) { - System.out.println("[" + Thread.currentThread().getName() + "]: " + - message); + System.out.println("[" + Thread.currentThread().getName() + "][" + + System.currentTimeMillis() + "]: " + message); } } @@ -729,6 +729,7 @@ // wait out the delay here before any other processing. try { if (delayMsec > 0) { + log("Delaying response for " + delayMsec + " milliseconds."); Thread.sleep(delayMsec); } } catch (InterruptedException ie) { @@ -910,6 +911,13 @@ */ private LocalOcspRequest parseHttpOcspGet(String[] headerTokens, InputStream inStream) throws IOException, CertificateException { + // Display the whole request + StringBuilder sb = new StringBuilder("OCSP GET REQUEST\n"); + for (String hTok : headerTokens) { + sb.append(hTok).append("\n"); + } + log(sb.toString()); + // Before we process the remainder of the GET URL, we should drain // the InputStream of any other header data. We (for now) won't // use it, but will display the contents if logging is enabled. @@ -1002,6 +1010,10 @@ CertificateException { Objects.requireNonNull(requestBytes, "Received null input"); + // Display the DER encoding before parsing + log("Local OCSP Request Constructor, parsing bytes:\n" + + dumpHexBytes(requestBytes)); + DerInputStream dis = new DerInputStream(requestBytes); // Parse the top-level structure, it should have no more than diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/BreakIterator/BreakIteratorTest.java openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/BreakIteratorTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/BreakIterator/BreakIteratorTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/BreakIteratorTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,8 +26,7 @@ * @bug 4035266 4052418 4068133 4068137 4068139 4086052 4095322 4097779 * 4097920 4098467 4111338 4113835 4117554 4143071 4146175 4152117 * 4152416 4153072 4158381 4214367 4217703 4638433 8264765 - * @library /java/text/testlib - * @run main/timeout=2000 BreakIteratorTest + * @run junit/timeout=2000 BreakIteratorTest * @summary test BreakIterator */ @@ -75,24 +74,16 @@ import java.util.Enumeration; import java.io.*; -public class BreakIteratorTest extends IntlTest -{ - private BreakIterator characterBreak; - private BreakIterator wordBreak; - private BreakIterator lineBreak; - private BreakIterator sentenceBreak; +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new BreakIteratorTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BreakIteratorTest { + private final BreakIterator characterBreak = BreakIterator.getCharacterInstance(); + private final BreakIterator wordBreak = BreakIterator.getWordInstance(); + private final BreakIterator lineBreak = BreakIterator.getLineInstance(); + private final BreakIterator sentenceBreak = BreakIterator.getSentenceInstance(); - public BreakIteratorTest() - { - characterBreak = BreakIterator.getCharacterInstance(); - wordBreak = BreakIterator.getWordInstance(); - lineBreak = BreakIterator.getLineInstance(); - sentenceBreak = BreakIterator.getSentenceInstance(); - } //========================================================================= // general test subroutines @@ -112,15 +103,12 @@ Vector nextResults = testFirstAndNext(bi, text); Vector previousResults = testLastAndPrevious(bi, text); - logln("comparing forward and backward..."); - int errs = getErrorCount(); + System.out.println("comparing forward and backward..."); compareFragmentLists("forward iteration", "backward iteration", nextResults, previousResults); - if (getErrorCount() == errs) { - logln("comparing expected and actual..."); - compareFragmentLists("expected result", "actual result", expectedResult, - nextResults); - } + System.out.println("comparing expected and actual..."); + compareFragmentLists("expected result", "actual result", expectedResult, + nextResults); int[] boundaries = new int[expectedResult.size() + 3]; boundaries[0] = BreakIterator.DONE; @@ -143,19 +131,19 @@ Vector result = new Vector(); if (p != 0) - errln("first() returned " + p + " instead of 0"); + fail("first() returned " + p + " instead of 0"); while (p != BreakIterator.DONE) { p = bi.next(); if (p != BreakIterator.DONE) { if (p <= lastP) - errln("next() failed to move forward: next() on position " + fail("next() failed to move forward: next() on position " + lastP + " yielded " + p); result.addElement(text.substring(lastP, p)); } else { if (lastP != text.length()) - errln("next() returned DONE prematurely: offset was " + fail("next() returned DONE prematurely: offset was " + lastP + " instead of " + text.length()); } lastP = p; @@ -169,19 +157,19 @@ Vector result = new Vector(); if (p != text.length()) - errln("last() returned " + p + " instead of " + text.length()); + fail("last() returned " + p + " instead of " + text.length()); while (p != BreakIterator.DONE) { p = bi.previous(); if (p != BreakIterator.DONE) { if (p >= lastP) - errln("previous() failed to move backward: previous() on position " + fail("previous() failed to move backward: previous() on position " + lastP + " yielded " + p); result.insertElementAt(text.substring(p, lastP), 0); } else { if (lastP != 0) - errln("previous() returned DONE prematurely: offset was " + fail("previous() returned DONE prematurely: offset was " + lastP + " instead of 0"); } lastP = p; @@ -224,27 +212,28 @@ ++tempP2; } } - logln("*** " + f1Name + " has:"); + System.out.println("*** " + f1Name + " has:"); while (p1 <= tempP1 && p1 < f1.size()) { s1 = (String)f1.elementAt(p1); t1 += s1.length(); debugLogln(" *** >" + s1 + "<"); ++p1; } - logln("***** " + f2Name + " has:"); + System.out.println("***** " + f2Name + " has:"); while (p2 <= tempP2 && p2 < f2.size()) { s2 = (String)f2.elementAt(p2); t2 += s2.length(); debugLogln(" ***** >" + s2 + "<"); ++p2; } - errln("Discrepancy between " + f1Name + " and " + f2Name + "\n---\n" + f1 +"\n---\n" + f2); + fail("Discrepancy between " + f1Name + " and " + f2Name + + "\n---\n" + f1 +"\n---\n" + f2); } } } private void testFollowing(BreakIterator bi, String text, int[] boundaries) { - logln("testFollowing():"); + System.out.println("testFollowing():"); int p = 2; int i = 0; try { @@ -253,59 +242,59 @@ ++p; int b = bi.following(i); - logln("bi.following(" + i + ") -> " + b); + System.out.println("bi.following(" + i + ") -> " + b); if (b != boundaries[p]) - errln("Wrong result from following() for " + i + ": expected " + boundaries[p] + fail("Wrong result from following() for " + i + ": expected " + boundaries[p] + ", got " + b); } } catch (IllegalArgumentException illargExp) { - errln("IllegalArgumentException caught from following() for offset: " + i); + fail("IllegalArgumentException caught from following() for offset: " + i); } } private void testPreceding(BreakIterator bi, String text, int[] boundaries) { - logln("testPreceding():"); + System.out.println("testPreceding():"); int p = 0; int i = 0; try { for (i = 0; i <= text.length(); i++) { // change to <= when new BI code goes in int b = bi.preceding(i); - logln("bi.preceding(" + i + ") -> " + b); + System.out.println("bi.preceding(" + i + ") -> " + b); if (b != boundaries[p]) - errln("Wrong result from preceding() for " + i + ": expected " + boundaries[p] + fail("Wrong result from preceding() for " + i + ": expected " + boundaries[p] + ", got " + b); if (i == boundaries[p + 1]) ++p; } } catch (IllegalArgumentException illargExp) { - errln("IllegalArgumentException caught from preceding() for offset: " + i); + fail("IllegalArgumentException caught from preceding() for offset: " + i); } } private void testIsBoundary(BreakIterator bi, String text, int[] boundaries) { - logln("testIsBoundary():"); + System.out.println("testIsBoundary():"); int p = 1; boolean isB; for (int i = 0; i <= text.length(); i++) { // change to <= when new BI code goes in isB = bi.isBoundary(i); - logln("bi.isBoundary(" + i + ") -> " + isB); + System.out.println("bi.isBoundary(" + i + ") -> " + isB); if (i == boundaries[p]) { if (!isB) - errln("Wrong result from isBoundary() for " + i + ": expected true, got false"); + fail("Wrong result from isBoundary() for " + i + ": expected true, got false"); ++p; } else { if (isB) - errln("Wrong result from isBoundary() for " + i + ": expected false, got true"); + fail("Wrong result from isBoundary() for " + i + ": expected false, got true"); } } } private void doMultipleSelectionTest(BreakIterator iterator, String testText) { - logln("Multiple selection test..."); + System.out.println("Multiple selection test..."); BreakIterator testIterator = (BreakIterator)iterator.clone(); int offset = iterator.first(); int testOffset; @@ -314,9 +303,9 @@ do { testOffset = testIterator.first(); testOffset = testIterator.next(count); - logln("next(" + count + ") -> " + testOffset); + System.out.println("next(" + count + ") -> " + testOffset); if (offset != testOffset) - errln("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); + fail("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); if (offset != BreakIterator.DONE) { count++; @@ -331,9 +320,9 @@ do { testOffset = testIterator.last(); testOffset = testIterator.next(count); - logln("next(" + count + ") -> " + testOffset); + System.out.println("next(" + count + ") -> " + testOffset); if (offset != testOffset) - errln("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); + fail("next(n) and next() not returning consistent results: for step " + count + ", next(n) returned " + testOffset + " and next() had " + offset); if (offset != BreakIterator.DONE) { count--; @@ -379,7 +368,7 @@ seen2 = true; } if (!seen2) { - errln("No break between U+" + Integer.toHexString((int)(work.charAt(1))) + fail("No break between U+" + Integer.toHexString((int)(work.charAt(1))) + " and U+" + Integer.toHexString((int)(work.charAt(2)))); errorCount++; if (errorCount >= 75) @@ -403,7 +392,7 @@ tb.setText(work.toString()); for (int k = tb.first(); k != BreakIterator.DONE; k = tb.next()) if (k == 2) { - errln("Break between CR and LF in string U+" + Integer.toHexString( + fail("Break between CR and LF in string U+" + Integer.toHexString( (int)(work.charAt(0))) + ", U+d U+a U+" + Integer.toHexString( (int)(work.charAt(3)))); errorCount++; @@ -441,7 +430,7 @@ tb.setText(work.toString()); for (int k = tb.first(); k != BreakIterator.DONE; k = tb.next()) if (k == 2) { - errln("Break between U+" + Integer.toHexString((int)(work.charAt(1))) + fail("Break between U+" + Integer.toHexString((int)(work.charAt(1))) + " and U+" + Integer.toHexString((int)(work.charAt(2)))); errorCount++; if (errorCount >= 75) @@ -466,13 +455,14 @@ out.append(temp); } } - logln(out.toString()); + System.out.println(out.toString()); } //========================================================================= // tests //========================================================================= + @Test public void TestWordBreak() { Vector wordSelectionData = new Vector(); @@ -556,6 +546,7 @@ generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4097779() { Vector wordSelectionData = new Vector(); @@ -565,6 +556,7 @@ generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4098467Words() { Vector wordSelectionData = new Vector(); @@ -594,6 +586,7 @@ generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestBug4117554Words() { Vector wordSelectionData = new Vector(); @@ -606,6 +599,7 @@ generalIteratorTest(wordBreak, wordSelectionData); } + @Test public void TestSentenceBreak() { Vector sentenceSelectionData = new Vector(); @@ -641,6 +635,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4113835() { Vector sentenceSelectionData = new Vector(); @@ -650,6 +645,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4111338() { Vector sentenceSelectionData = new Vector(); @@ -669,6 +665,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4117554Sentences() { Vector sentenceSelectionData = new Vector(); @@ -691,6 +688,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4158381() { Vector sentenceSelectionData = new Vector(); @@ -708,6 +706,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4143071() { Vector sentenceSelectionData = new Vector(); @@ -719,6 +718,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4152416() { Vector sentenceSelectionData = new Vector(); @@ -731,6 +731,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4152117() { Vector sentenceSelectionData = new Vector(); @@ -749,6 +750,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug8264765() { Vector sentenceSelectionData = new Vector(); @@ -760,6 +762,7 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestLineBreak() { Vector lineSelectionData = new Vector(); @@ -796,6 +799,7 @@ generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4068133() { Vector lineSelectionData = new Vector(); @@ -812,6 +816,7 @@ generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4086052() { Vector lineSelectionData = new Vector(); @@ -821,6 +826,7 @@ generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4097920() { Vector lineSelectionData = new Vector(); @@ -833,6 +839,7 @@ generalIteratorTest(lineBreak, lineSelectionData); } /* + @Test public void TestBug4035266() { Vector lineSelectionData = new Vector(); @@ -846,6 +853,7 @@ generalIteratorTest(lineBreak, lineSelectionData); } */ + @Test public void TestBug4098467Lines() { Vector lineSelectionData = new Vector(); @@ -871,13 +879,14 @@ lineSelectionData.addElement("\u110c\u1161\u11bc\u1105\u1169\u1100\u116d\u1112\u116c"); if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4117554Lines() { Vector lineSelectionData = new Vector(); @@ -889,9 +898,10 @@ generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4217703() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -918,6 +928,7 @@ private static final String circumflexA = "a\u0302"; private static final String tildeE = "e\u0303"; + @Test public void TestCharacterBreak() { Vector characterSelectionData = new Vector(); @@ -949,6 +960,7 @@ generalIteratorTest(characterBreak, characterSelectionData); } + @Test public void TestBug4098467Characters() { Vector characterSelectionData = new Vector(); @@ -989,6 +1001,7 @@ generalIteratorTest(characterBreak, characterSelectionData); } + @Test public void TestBug4153072() { BreakIterator iter = BreakIterator.getWordInstance(); String str = "...Hello, World!..."; @@ -1002,17 +1015,18 @@ try { dummy = iter.isBoundary(index); if (index < begin) - errln("Didn't get exception with offset = " + index + + fail("Didn't get exception with offset = " + index + " and begin index = " + begin); } catch (IllegalArgumentException e) { if (index >= begin) - errln("Got exception with offset = " + index + + fail("Got exception with offset = " + index + " and begin index = " + begin); } } } + @Test public void TestBug4146175Sentences() { Vector sentenceSelectionData = new Vector(); @@ -1028,9 +1042,10 @@ generalIteratorTest(sentenceBreak, sentenceSelectionData); } + @Test public void TestBug4146175Lines() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1043,9 +1058,10 @@ generalIteratorTest(lineBreak, lineSelectionData); } + @Test public void TestBug4214367() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1067,16 +1083,18 @@ + "\u2001\u2002\u200c\u200d\u200e\u200f\u2010\u2011\u2012\u2028\u2029\u202a\u203e\u203f" + "\u2040\u20dd\u20de\u20df\u20e0\u2160\u2161\u2162\u2163\u2164"; + @Test public void TestSentenceInvariants() { BreakIterator e = BreakIterator.getSentenceInstance(); doOtherInvariantTest(e, cannedTestChars + ".,\u3001\u3002\u3041\u3042\u3043\ufeff"); } + @Test public void TestWordInvariants() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1087,10 +1105,11 @@ + "\u30a3\u4e00\u4e01\u4e02"); } + @Test public void TestLineInvariants() { if (Locale.getDefault().getLanguage().equals("th")) { - logln("This test is skipped in th locale."); + System.out.println("This test is skipped in th locale."); return; } @@ -1139,7 +1158,7 @@ work.charAt(l) == '\ufeff')) { continue; } - errln("Got break between U+" + Integer.toHexString((int) + fail("Got break between U+" + Integer.toHexString((int) (work.charAt(l - 1))) + " and U+" + Integer.toHexString( (int)(work.charAt(l)))); errorCount++; @@ -1192,7 +1211,7 @@ if (l == 2) saw2 = true; if (!saw2) { - errln("Didn't get break between U+" + Integer.toHexString((int) + fail("Didn't get break between U+" + Integer.toHexString((int) (work.charAt(1))) + " and U+" + Integer.toHexString( (int)(work.charAt(2)))); errorCount++; @@ -1205,6 +1224,7 @@ */ } + @Test public void TestCharacterInvariants() { BreakIterator e = BreakIterator.getCharacterInstance(); @@ -1214,6 +1234,7 @@ + "\u11a9\u11aa"); } + @Test public void TestEmptyString() { String text = ""; @@ -1223,12 +1244,13 @@ generalIteratorTest(lineBreak, x); } + @Test public void TestGetAvailableLocales() { Locale[] locList = BreakIterator.getAvailableLocales(); if (locList.length == 0) - errln("getAvailableLocales() returned an empty list!"); + fail("getAvailableLocales() returned an empty list!"); // I have no idea how to test this function... } @@ -1236,6 +1258,7 @@ /** * Bug 4095322 */ + @Test public void TestJapaneseLineBreak() { StringBuffer testString = new StringBuffer("\u4e00x\u4e8c"); @@ -1284,18 +1307,18 @@ iter.setText(testString.toString()); int j = iter.first(); if (j != 0) { - errln("ja line break failure: failed to start at 0 and bounced at " + j); + fail("ja line break failure: failed to start at 0 and bounced at " + j); } j = iter.next(); if (j != 1) { - errln("ja line break failure: failed to stop before '" + fail("ja line break failure: failed to stop before '" + precedingChars.charAt(i) + "' (\\u" + Integer.toString(precedingChars.charAt(i), 16) + ") at 1 and bounded at " + j); } j = iter.next(); if (j != 3) { - errln("ja line break failure: failed to skip position after '" + fail("ja line break failure: failed to skip position after '" + precedingChars.charAt(i) + "' (\\u" + Integer.toString(precedingChars.charAt(i), 16) + ") at 3 and bounded at " + j); @@ -1307,18 +1330,18 @@ iter.setText(testString.toString()); int j = iter.first(); if (j != 0) { - errln("ja line break failure: failed to start at 0 and bounded at " + j); + fail("ja line break failure: failed to start at 0 and bounded at " + j); } j = iter.next(); if (j != 2) { - errln("ja line break failure: failed to skip position before '" + fail("ja line break failure: failed to skip position before '" + followingChars.charAt(i) + "' (\\u" + Integer.toString(followingChars.charAt(i), 16) + ") at 2 and bounded at " + j); } j = iter.next(); if (j != 3) { - errln("ja line break failure: failed to stop after '" + fail("ja line break failure: failed to stop after '" + followingChars.charAt(i) + "' (\\u" + Integer.toString(followingChars.charAt(i), 16) + ") at 3 and bounded at " + j); @@ -1329,6 +1352,7 @@ /** * Bug 4638433 */ + @Test public void TestLineBreakBasedOnUnicode3_0_0() { BreakIterator iter; @@ -1342,7 +1366,7 @@ i = iter.first(); i = iter.next(); if (i != 5) { - errln("Word break failure: failed to stop at 5 and bounded at " + i); + fail("Word break failure: failed to stop at 5 and bounded at " + i); } @@ -1355,7 +1379,7 @@ i = iter.first(); i = iter.next(); if (i != 3) { - errln("Line break failure: failed to skip before \\u301F(Pe) at 3 and bounded at " + i); + fail("Line break failure: failed to skip before \\u301F(Pe) at 3 and bounded at " + i); } /* Mongolian @@ -1365,7 +1389,7 @@ i = iter.first(); i = iter.next(); if (i != 2) { - errln("Mongolian line break failure: failed to skip position before \\u1806(Pd) at 2 and bounded at " + i); + fail("Mongolian line break failure: failed to skip position before \\u1806(Pd) at 2 and bounded at " + i); } /* Khmer which have @@ -1375,11 +1399,11 @@ i = iter.first(); i = iter.next(); if (i != 1) { - errln("Khmer line break failure: failed to stop before \\u17DB(Sc) at 1 and bounded at " + i); + fail("Khmer line break failure: failed to stop before \\u17DB(Sc) at 1 and bounded at " + i); } i = iter.next(); if (i != 3) { - errln("Khmer line break failure: failed to skip position after \\u17DB(Sc) at 3 and bounded at " + i); + fail("Khmer line break failure: failed to skip position after \\u17DB(Sc) at 3 and bounded at " + i); } /* Ogham which have @@ -1389,7 +1413,7 @@ i = iter.first(); i = iter.next(); if (i != 2) { - errln("Ogham line break failure: failed to skip postion before \\u1680(Zs) at 2 and bounded at " + i); + fail("Ogham line break failure: failed to skip postion before \\u1680(Zs) at 2 and bounded at " + i); } @@ -1406,17 +1430,18 @@ i = iter.first(); i = iter.next(); if (i != 1) { - errln("Thai line break failure: failed to stop before \\u201C(Pi) at 1 and bounded at " + i); + fail("Thai line break failure: failed to stop before \\u201C(Pi) at 1 and bounded at " + i); } i = iter.next(); if (i != 4) { - errln("Thai line break failure: failed to stop after \\u201D(Pf) at 4 and bounded at " + i); + fail("Thai line break failure: failed to stop after \\u201D(Pf) at 4 and bounded at " + i); } } /** * Bug 4068137 */ + @Test public void TestEndBehavior() { String testString = "boo."; @@ -1424,11 +1449,11 @@ wb.setText(testString); if (wb.first() != 0) - errln("Didn't get break at beginning of string."); + fail("Didn't get break at beginning of string."); if (wb.next() != 3) - errln("Didn't get break before period in \"boo.\""); + fail("Didn't get break before period in \"boo.\""); if (wb.current() != 4 && wb.next() != 4) - errln("Didn't get break at end of string."); + fail("Didn't get break at end of string."); } // [serialization test has been removed pursuant to bug #4152965] @@ -1436,6 +1461,7 @@ /** * Bug 4450804 */ + @Test public void TestLineBreakContractions() { Vector expected = new Vector(); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/BreakIterator/Bug4533872.java openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/Bug4533872.java --- openjdk-17-17.0.14+7/test/jdk/java/text/BreakIterator/Bug4533872.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/BreakIterator/Bug4533872.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,21 +21,21 @@ * questions. */ -/** +/* * @test * @bug 4533872 4640853 - * @library /java/text/testlib * @summary Unit tests for supplementary character support (JSR-204) and Unicode 4.0 support + * @run junit Bug4533872 */ import java.text.BreakIterator; import java.util.Locale; -public class Bug4533872 extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new Bug4533872().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4533872 { static final String[] given = { /* Lu Nd Lu Ll */ @@ -62,6 +62,7 @@ /* * Test for next(int n) */ + @Test void TestNext() { iter = BreakIterator.getWordInstance(Locale.US); @@ -73,7 +74,7 @@ end = iter.next(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachForward() expected:<" + + fail("Word break failure: printEachForward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -84,6 +85,7 @@ /* * Test for isBoundary(int n) */ + @Test void TestIsBoundary() { iter = BreakIterator.getWordInstance(Locale.US); @@ -95,7 +97,7 @@ while (end < given[i].length()) { if (!iter.isBoundary(end)) { - errln("Word break failure: isBoundary() This should be a boundary. Index=" + + fail("Word break failure: isBoundary() This should be a boundary. Index=" + end + " for " + given[i]); } end = iter.next(); @@ -112,6 +114,7 @@ /* * Test mainly for next() and current() */ + @Test void TestPrintEachForward() { iter = BreakIterator.getWordInstance(Locale.US); @@ -122,7 +125,7 @@ // Check current()'s return value - should be same as first()'s. current = iter.current(); if (start != current) { - errln("Word break failure: printEachForward() Unexpected current value: current()=" + + fail("Word break failure: printEachForward() Unexpected current value: current()=" + current + ", expected(=first())=" + start); } @@ -134,12 +137,12 @@ // Check current()'s return value - should be same as next()'s. current = iter.current(); if (end != current) { - errln("Word break failure: printEachForward() Unexpected current value: current()=" + + fail("Word break failure: printEachForward() Unexpected current value: current()=" + current + ", expected(=next())=" + end); } if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachForward() expected:<" + + fail("Word break failure: printEachForward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -151,6 +154,7 @@ /* * Test mainly for previous() and current() */ + @Test void TestPrintEachBackward() { iter = BreakIterator.getWordInstance(Locale.US); @@ -161,7 +165,7 @@ // Check current()'s return value - should be same as last()'s. current = iter.current(); if (end != current) { - errln("Word break failure: printEachBackward() Unexpected current value: current()=" + + fail("Word break failure: printEachBackward() Unexpected current value: current()=" + current + ", expected(=last())=" + end); } @@ -173,12 +177,12 @@ // Check current()'s return value - should be same as previous()'s. current = iter.current(); if (start != current) { - errln("Word break failure: printEachBackward() Unexpected current value: current()=" + + fail("Word break failure: printEachBackward() Unexpected current value: current()=" + current + ", expected(=previous())=" + start); } if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printEachBackward() expected:<" + + fail("Word break failure: printEachBackward() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -190,6 +194,7 @@ /* * Test mainly for following() and previous() */ + @Test void TestPrintAt_1() { iter = BreakIterator.getWordInstance(Locale.US); @@ -207,7 +212,7 @@ start = iter.previous(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printAt_1() expected:<" + + fail("Word break failure: printAt_1() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -219,6 +224,7 @@ /* * Test mainly for preceding() and next() */ + @Test void TestPrintAt_2() { iter = BreakIterator.getWordInstance(Locale.US); @@ -234,7 +240,7 @@ // Check preceding(0)'s return value - should equals BreakIterator.DONE. if (iter.preceding(0) != BreakIterator.DONE) { - errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + + fail("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + iter.preceding(0)); } @@ -243,7 +249,7 @@ end = iter.next(); if (!expected[i][j].equals(given[i].substring(start, end))) { - errln("Word break failure: printAt_2() expected:<" + + fail("Word break failure: printAt_2() expected:<" + expected[i][j] + ">, got:<" + given[i].substring(start, end) + "> start=" + start + " end=" + end); @@ -254,7 +260,7 @@ end = iter.last(); start = iter.next(); if (start != BreakIterator.DONE) { - errln("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + start); + fail("Word break failure: printAt_2() expected:-1(BreakIterator.DONE), got:" + start); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java openjdk-17-17.0.15+6/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/CharacterIterator/CharacterIteratorTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test for Character Iterator + * @run junit CharacterIteratorTest */ /* @@ -65,14 +65,15 @@ import java.text.*; -public class CharacterIteratorTest extends IntlTest { - public static void main(String[] args) throws Exception { - new CharacterIteratorTest().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; +public class CharacterIteratorTest { public CharacterIteratorTest() { } + @Test public void TestConstructionAndEquality() { String testText = "Now is the time for all good men to come to the aid of their country."; String testText2 = "Don't bother using this string."; @@ -84,49 +85,50 @@ CharacterIterator test5 = (CharacterIterator)test1.clone(); if (test1.equals(test2) || test1.equals(test3) || test1.equals(test4)) - errln("Construation or equals() failed: Two unequal iterators tested equal"); + fail("Construation or equals() failed: Two unequal iterators tested equal"); if (!test1.equals(test5)) - errln("clone() or equals() failed: Two clones tested unequal"); + fail("clone() or equals() failed: Two clones tested unequal"); if (test1.hashCode() == test2.hashCode() || test1.hashCode() == test3.hashCode() || test1.hashCode() == test4.hashCode()) - errln("hash() failed: different objects have same hash code"); + fail("hash() failed: different objects have same hash code"); if (test1.hashCode() != test5.hashCode()) - errln("hash() failed: identical objects have different hash codes"); + fail("hash() failed: identical objects have different hash codes"); test1.setIndex(5); if (!test1.equals(test2) || test1.equals(test5)) - errln("setIndex() failed"); + fail("setIndex() failed"); } + @Test public void TestIteration() { String text = "Now is the time for all good men to come to the aid of their country."; CharacterIterator iter = new StringCharacterIterator(text, 5); if (iter.current() != text.charAt(5)) - errln("Iterator didn't start out in the right place."); + fail("Iterator didn't start out in the right place."); char c = iter.first(); int i = 0; if (iter.getBeginIndex() != 0 || iter.getEndIndex() != text.length()) - errln("getBeginIndex() or getEndIndex() failed"); + fail("getBeginIndex() or getEndIndex() failed"); - logln("Testing forward iteration..."); + System.out.println("Testing forward iteration..."); do { if (c == CharacterIterator.DONE && i != text.length()) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.next(); @@ -137,18 +139,18 @@ c = iter.last(); i = text.length() - 1; - logln("Testing backward iteration..."); + System.out.println("Testing backward iteration..."); do { if (c == CharacterIterator.DONE && i >= 0) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.previous(); @@ -158,26 +160,26 @@ iter = new StringCharacterIterator(text, 5, 15, 10); if (iter.getBeginIndex() != 5 || iter.getEndIndex() != 15) - errln("creation of a restricted-range iterator failed"); + fail("creation of a restricted-range iterator failed"); if (iter.getIndex() != 10 || iter.current() != text.charAt(10)) - errln("starting the iterator in the middle didn't work"); + fail("starting the iterator in the middle didn't work"); c = iter.first(); i = 5; - logln("Testing forward iteration over a range..."); + System.out.println("Testing forward iteration over a range..."); do { if (c == CharacterIterator.DONE && i != 15) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.next(); @@ -188,18 +190,18 @@ c = iter.last(); i = 14; - logln("Testing backward iteration over a range..."); + System.out.println("Testing backward iteration over a range..."); do { if (c == CharacterIterator.DONE && i >= 5) - errln("Iterator reached end prematurely"); + fail("Iterator reached end prematurely"); else if (c != text.charAt(i)) - errln("Character mismatch at position " + i + ", iterator has " + c + + fail("Character mismatch at position " + i + ", iterator has " + c + ", string has " + text.charAt(c)); if (iter.current() != c) - errln("current() isn't working right"); + fail("current() isn't working right"); if (iter.getIndex() != i) - errln("getIndex() isn't working right"); + fail("getIndex() isn't working right"); if (c != CharacterIterator.DONE) { c = iter.previous(); @@ -211,6 +213,7 @@ /** * @bug 4082050 4078261 4078255 */ + @Test public void TestPathologicalCases() { String text = "This is only a test."; @@ -227,7 +230,7 @@ || iter.previous() != CharacterIterator.DONE || iter.current() != CharacterIterator.DONE || iter.getIndex() != 5) - errln("Got something other than DONE when performing operations on an empty StringCharacterIterator"); + fail("Got something other than DONE when performing operations on an empty StringCharacterIterator"); */ CharacterIterator iter = null; @@ -242,7 +245,7 @@ gotException = true; } if (!gotException) - errln("StringCharacterIterator didn't throw an exception when given an invalid substring range."); + fail("StringCharacterIterator didn't throw an exception when given an invalid substring range."); // test for bug #4078255 (getting wrong value from next() when we're at the end // of the string) @@ -253,17 +256,17 @@ iter.last(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex - 1) - errln("last() failed: expected " + (expectedIndex - 1) + ", got " + actualIndex); + fail("last() failed: expected " + (expectedIndex - 1) + ", got " + actualIndex); iter.next(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex) - errln("next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); + fail("next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); iter.next(); actualIndex = iter.getIndex(); if (actualIndex != expectedIndex) - errln("second next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); + fail("second next() after last() failed: expected " + expectedIndex + ", got " + actualIndex); } /* @@ -271,6 +274,7 @@ * #4123771 is actually a duplicate of bug #4051073, which was fixed some time ago, but * no one ever added a regression test for it. */ + @Test public void TestBug4123771() { String text = "Some string for testing"; StringCharacterIterator iter = new StringCharacterIterator(text); @@ -283,7 +287,7 @@ System.out.println(" position: " + index); System.out.println(" getEndIndex(): " + iter.getEndIndex()); System.out.println(" text.length(): " + text.length()); - errln(""); // re-throw the exception through our test framework + fail(""); // re-throw the exception through our test framework } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/APITest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/APITest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/APITest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/APITest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,12 +22,6 @@ */ /* - * @test - * @library /java/text/testlib - * @summary test Collation API - * @modules jdk.localedata - */ -/* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved (C) Copyright IBM Corp. 1996 - All Rights Reserved @@ -39,128 +33,137 @@ Taligent is a registered trademark of Taligent, Inc. */ +/* + * @test + * @library /java/text/testlib + * @summary test Collation API + * @modules jdk.localedata + * @run junit APITest + */ + import java.util.Locale; import java.text.Collator; import java.text.RuleBasedCollator; import java.text.CollationKey; import java.text.CollationElementIterator; -public class APITest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new APITest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class APITest { final void doAssert(boolean condition, String message) { if (!condition) { - err("ERROR: "); - errln(message); + fail("ERROR: " + message); } } + @Test public final void TestProperty( ) { Collator col = null; try { col = Collator.getInstance(Locale.ROOT); - logln("The property tests begin : "); - logln("Test ctors : "); + System.out.println("The property tests begin : "); + System.out.println("Test ctors : "); doAssert(col.compare("ab", "abc") < 0, "ab < abc comparison failed"); doAssert(col.compare("ab", "AB") < 0, "ab < AB comparison failed"); doAssert(col.compare("black-bird", "blackbird") > 0, "black-bird > blackbird comparison failed"); doAssert(col.compare("black bird", "black-bird") < 0, "black bird < black-bird comparison failed"); doAssert(col.compare("Hello", "hello") > 0, "Hello > hello comparison failed"); - logln("Test ctors ends."); - logln("testing Collator.getStrength() method ..."); + System.out.println("Test ctors ends."); + System.out.println("testing Collator.getStrength() method ..."); doAssert(col.getStrength() == Collator.TERTIARY, "collation object has the wrong strength"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); - logln("testing Collator.setStrength() method ..."); + System.out.println("testing Collator.setStrength() method ..."); col.setStrength(Collator.SECONDARY); doAssert(col.getStrength() != Collator.TERTIARY, "collation object's strength is secondary difference"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); doAssert(col.getStrength() == Collator.SECONDARY, "collation object has the wrong strength"); - logln("testing Collator.setDecomposition() method ..."); + System.out.println("testing Collator.setDecomposition() method ..."); col.setDecomposition(Collator.NO_DECOMPOSITION); doAssert(col.getDecomposition() != Collator.FULL_DECOMPOSITION, "collation object's strength is secondary difference"); doAssert(col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION, "collation object's strength is primary difference"); doAssert(col.getDecomposition() == Collator.NO_DECOMPOSITION, "collation object has the wrong strength"); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default Collator creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default Collator creation failed."); } - logln("Default collation property test ended."); - logln("Collator.getRules() testing ..."); + System.out.println("Default collation property test ended."); + System.out.println("Collator.getRules() testing ..."); doAssert(((RuleBasedCollator)col).getRules().length() != 0, "getRules() result incorrect" ); - logln("getRules tests end."); + System.out.println("getRules tests end."); try { col = Collator.getInstance(Locale.FRENCH); col.setStrength(Collator.PRIMARY); - logln("testing Collator.getStrength() method again ..."); + System.out.println("testing Collator.getStrength() method again ..."); doAssert(col.getStrength() != Collator.TERTIARY, "collation object has the wrong strength"); doAssert(col.getStrength() == Collator.PRIMARY, "collation object's strength is not primary difference"); - logln("testing French Collator.setStrength() method ..."); + System.out.println("testing French Collator.setStrength() method ..."); col.setStrength(Collator.TERTIARY); doAssert(col.getStrength() == Collator.TERTIARY, "collation object's strength is not tertiary difference"); doAssert(col.getStrength() != Collator.PRIMARY, "collation object's strength is primary difference"); doAssert(col.getStrength() != Collator.SECONDARY, "collation object's strength is secondary difference"); } catch (Exception bar) { - errln("Error : " + bar.getMessage()); - errln("Creating French collation failed."); + fail("Error : " + bar.getMessage() + + "\n Creating French collation failed."); } - logln("Create junk collation: "); + System.out.println("Create junk collation: "); Locale abcd = new Locale("ab", "CD", ""); Collator junk = null; try { junk = Collator.getInstance(abcd); } catch (Exception err) { - errln("Error : " + err.getMessage()); - errln("Junk collation creation failed, should at least return the collator for the base bundle."); + fail("Error : " + err.getMessage() + + "\n Junk collation creation failed, should at least return the collator for the base bundle."); } try { col = Collator.getInstance(Locale.ROOT); doAssert(col.equals(junk), "The base bundle's collation should be returned."); } catch (Exception exc) { - errln("Error : " + exc.getMessage()); - errln("Default collation comparison, caching not working."); + fail("Error : " + exc.getMessage() + + "\n Default collation comparison, caching not working."); } - logln("Collator property test ended."); + System.out.println("Collator property test ended."); } + @Test public final void TestHashCode( ) { - logln("hashCode tests begin."); + System.out.println("hashCode tests begin."); Collator col1 = null; try { col1 = Collator.getInstance(Locale.ROOT); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } Collator col2 = null; Locale dk = new Locale("da", "DK", ""); try { col2 = Collator.getInstance(dk); } catch (Exception bar) { - errln("Error : " + bar.getMessage()); - errln("Danish collation creation failed."); + fail("Error : " + bar.getMessage() + + "\n Danish collation creation failed."); return; } Collator col3 = null; try { col3 = Collator.getInstance(Locale.ROOT); } catch (Exception err) { - errln("Error : " + err.getMessage()); - errln("2nd default collation creation failed."); + fail("Error : " + err.getMessage() + + "\n 2nd default collation creation failed."); } - logln("Collator.hashCode() testing ..."); + System.out.println("Collator.hashCode() testing ..."); if (col1 != null) { doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect"); @@ -169,28 +172,29 @@ } } - logln("hashCode tests end."); + System.out.println("hashCode tests end."); } //---------------------------------------------------------------------------- // ctor -- Tests the constructor methods // + @Test public final void TestCollationKey( ) { - logln("testing CollationKey begins..."); + System.out.println("testing CollationKey begins..."); Collator col = null; try { col = Collator.getInstance(Locale.ROOT); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } if (col == null) { return; } String test1 = "Abcda", test2 = "abcda"; - logln("Use tertiary comparison level testing ...."); + System.out.println("Use tertiary comparison level testing ...."); CollationKey sortk1 = col.getCollationKey(test1); CollationKey sortk2 = col.getCollationKey(test2); doAssert(sortk1.compareTo(sortk2) > 0, @@ -209,20 +213,21 @@ byte byteArray1[] = sortk1.toByteArray(); byte byteArray2[] = sortk2.toByteArray(); doAssert(byteArray1 != null && byteArray2 != null, "CollationKey.toByteArray failed."); - logln("testing sortkey ends..."); + System.out.println("testing sortkey ends..."); } //---------------------------------------------------------------------------- // ctor -- Tests the constructor methods // + @Test public final void TestElemIter( ) { - logln("testing sortkey begins..."); + System.out.println("testing sortkey begins..."); Collator col = null; try { col = Collator.getInstance(); } catch (Exception foo) { - errln("Error : " + foo.getMessage()); - errln("Default collation creation failed."); + fail("Error : " + foo.getMessage() + + "\n Default collation creation failed."); } RuleBasedCollator rbCol; if (col instanceof RuleBasedCollator) { @@ -232,7 +237,7 @@ } String testString1 = "XFILE What subset of all possible test cases has the highest probability of detecting the most errors?"; String testString2 = "Xf ile What subset of all possible test cases has the lowest probability of detecting the least errors?"; - logln("Constructors and comparison testing...."); + System.out.println("Constructors and comparison testing...."); CollationElementIterator iterator1 = rbCol.getCollationElementIterator(testString1); CollationElementIterator iterator2 = rbCol.getCollationElementIterator(testString1); CollationElementIterator iterator3 = rbCol.getCollationElementIterator(testString2); @@ -303,17 +308,18 @@ != CollationElementIterator.secondaryOrder(order3), "The secondary orders should be different"); doAssert(order1 != CollationElementIterator.NULLORDER, "Unexpected end of iterator reached"); - logln("testing CollationElementIterator ends..."); + System.out.println("testing CollationElementIterator ends..."); } + @Test public final void TestGetAll() { Locale[] list = Collator.getAvailableLocales(); for (int i = 0; i < list.length; ++i) { - log("Locale name: "); - log(list[i].toString()); - log(" , the display name is : "); - logln(list[i].getDisplayName()); + System.out.println("Locale name: "); + System.out.println(list[i].toString()); + System.out.println(" , the display name is : "); + System.out.println(list[i].getDisplayName()); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Bug6271411.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Bug6271411.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Bug6271411.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Bug6271411.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,20 @@ /* * @test * @bug 6271411 - * @library /java/text/testlib * @summary Confirm that three JCK testcases for CollationElementIterator pass. + * @run junit Bug6271411 */ import java.text.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* * Based on JCK-runtime-15/tests/api/java_text/CollationElementIterator/ColltnElmtIterTests.java. */ -public class Bug6271411 extends IntlTest { - - public static void main(String argv[]) throws Exception { - Bug6271411 test = new Bug6271411(); - test.run(argv); - } +public class Bug6271411 { /* * Rule for RuleBasedCollator @@ -58,6 +57,7 @@ * (not IndexOutOfBoundsException) if the given offset is invalid. * Use CollationElementIterator.setText(String). */ + @Test public void Test_CollationElementIterator0007() throws Exception { int[] offsets = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, -10000, -2, -1, @@ -90,7 +90,7 @@ } if (err) { - errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); + fail("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); } } @@ -99,6 +99,7 @@ * IllegalArgumentException if the given offset is invalid. * Use CollationElementIterator.setText(CharacterIterator). */ + @Test public void Test_CollationElementIterator0010() throws Exception { String prefix = "xyz abc"; String suffix = "1234567890"; @@ -144,7 +145,7 @@ } if (err) { - errln("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); + fail("CollationElementIterator.setOffset() didn't throw an expected IllegalArguemntException."); } } @@ -153,6 +154,7 @@ * an offset as expected. * Use CollationElementIterator.setText(CharacterIterator). */ + @Test public void Test_CollationElementIterator0011() throws Exception { String prefix = "xyz abc"; String suffix = "1234567890"; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/CollatorTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/CollatorTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/CollatorTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/CollatorTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,141 +0,0 @@ -/* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * CollatorTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public abstract class CollatorTest extends IntlTest { - - //------------------------------------------------------------------------ - // These methods are utilities specific to the Collation tests.. - //------------------------------------------------------------------------ - - protected void assertEqual(CollationElementIterator i1, CollationElementIterator i2) { - int c1, c2, count = 0; - do { - c1 = i1.next(); - c2 = i2.next(); - if (c1 != c2) { - errln(" " + count + ": " + c1 + " != " + c2); - break; - } - count++; - } while (c1 != CollationElementIterator.NULLORDER); - } - - // Replace nonprintable characters with unicode escapes - static protected String prettify(String str) { - StringBuffer result = new StringBuffer(); - - String zero = "0000"; - - for (int i = 0; i < str.length(); i++) { - char ch = str.charAt(i); - if (ch < 0x09 || (ch > 0x0A && ch < 0x20)|| (ch > 0x7E && ch < 0xA0) || ch > 0x100) { - String hex = Integer.toString((int)ch,16); - - result.append("\\u" + zero.substring(0, 4 - hex.length()) + hex); - } else { - result.append(ch); - } - } - return result.toString(); - } - - // Produce a printable representation of a CollationKey - static protected String prettify(CollationKey key) { - StringBuffer result = new StringBuffer(); - byte[] bytes = key.toByteArray(); - - for (int i = 0; i < bytes.length; i += 2) { - int val = (bytes[i] << 8) + bytes[i+1]; - result.append(Integer.toString(val, 16) + " "); - } - return result.toString(); - } - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected void doTest(Collator col, int strength, - String[] source, String[] target, int[] result) { - if (source.length != target.length) { - errln("Data size mismatch: source = " + - source.length + ", target = " + target.length); - - return; // Return if "-nothrow" is specified. - } - if (source.length != result.length) { - errln("Data size mismatch: source & target = " + - source.length + ", result = " + result.length); - - return; // Return if "-nothrow" is specified. - } - - col.setStrength(strength); - for (int i = 0; i < source.length ; i++) { - doTest(col, source[i], target[i], result[i]); - } - } - - protected void doTest(Collator col, - String source, String target, int result) { - char relation = '='; - if (result <= -1) { - relation = '<'; - } else if (result >= 1) { - relation = '>'; - } - - int compareResult = col.compare(source, target); - CollationKey sortKey1 = col.getCollationKey(source); - CollationKey sortKey2 = col.getCollationKey(target); - int keyResult = sortKey1.compareTo(sortKey2); - if (compareResult != keyResult) { - errln("Compare and Collation Key results are different! Source = " + - source + " Target = " + target); - } - if (keyResult != result) { - errln("Collation Test failed! Source = " + source + " Target = " + - target + " result should be " + relation); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/DanishTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DanishTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/DanishTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DanishTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @library /java/text/testlib * @summary test Danish Collation * @modules jdk.localedata + * @run junit DanishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -43,12 +44,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class DanishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DanishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class DanishTest { /* * Data for TestPrimary() @@ -196,18 +197,20 @@ "\u00F6BERG" // o-diaeresis }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/DummyTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DummyTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/DummyTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/DummyTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,16 @@ * @test * @library /java/text/testlib * @summary test Dummy Collation + * @run junit DummyTest */ import java.text.Collator; import java.text.RuleBasedCollator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved (C) Copyright IBM Corp. 1996 - All Rights Reserved @@ -42,11 +47,7 @@ Taligent is a registered trademark of Taligent, Inc. */ -public class DummyTest extends CollatorTest { - - public static void main(String[] args) throws Exception { - new DummyTest().run(args); - } +public class DummyTest { private static final String DEFAULTRULES = "='\u200B'=\u200C=\u200D=\u200E=\u200F" @@ -382,25 +383,28 @@ "z" }; + @Test public void TestPrimary() { - doTest(getCollator(), Collator.PRIMARY, + TestUtils.doCollatorTest(getCollator(), Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestSecondary() { - doTest(getCollator(), Collator.SECONDARY, + TestUtils.doCollatorTest(getCollator(), Collator.SECONDARY, secondarySourceData, secondaryTargetData, secondaryResults); } + @Test public void TestTertiary() { Collator col = getCollator(); - doTest(col, Collator.TERTIARY, + TestUtils.doCollatorTest(col, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(col, testData[i], testData[j], -1); + TestUtils.doCollatorTest(col, testData[i], testData[j], -1); } } } @@ -412,7 +416,7 @@ myCollation = new RuleBasedCollator (DEFAULTRULES + "& C < ch, cH, Ch, CH & Five, 5 & Four, 4 & one, 1 & Ampersand; '&' & Two, 2 "); } catch (Exception foo) { - errln("Collator creation failed."); + fail("Collator creation failed."); myCollation = (RuleBasedCollator)Collator.getInstance(); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/EnglishTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/EnglishTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/EnglishTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/EnglishTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,16 @@ * @test * @library /java/text/testlib * @summary test English Collation + * @run junit EnglishTest */ import java.util.Locale; import java.text.Collator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved (C) Copyright IBM Corp. 1996 - All Rights Reserved @@ -42,11 +47,7 @@ Taligent is a registered trademark of Taligent, Inc. */ -public class EnglishTest extends CollatorTest { - - public static void main(String[] args) throws Exception { - new EnglishTest().run(args); - } +public class EnglishTest { /* * Data for TestPrimary() @@ -201,23 +202,26 @@ "x" }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestSecondary() { - doTest(myCollation, Collator.SECONDARY, + TestUtils.doCollatorTest(myCollation, Collator.SECONDARY, secondarySourceData, secondaryTargetData, secondaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/FinnishTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FinnishTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/FinnishTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FinnishTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Finnish Collation * @modules jdk.localedata + * @run junit FinnishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class FinnishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new FinnishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class FinnishTest { /* * Data for TestPrimary() @@ -85,13 +86,15 @@ 1, -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/FrenchTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FrenchTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/FrenchTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/FrenchTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test French Collation * @modules jdk.localedata + * @run junit FrenchTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class FrenchTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new FrenchTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class FrenchTest { private static final String[] tertiarySourceData = { "abc", @@ -86,13 +87,14 @@ "x" }; + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); for (int i = 0; i < testData.length-1; i++) { for (int j = i+1; j < testData.length; j++) { - doTest(myCollation, testData[i], testData[j], -1); + TestUtils.doCollatorTest(myCollation, testData[i], testData[j], -1); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/G7Test.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/G7Test.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/G7Test.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/G7Test.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test G7 Collation * @modules jdk.localedata + * @run junit G7Test */ /* * @@ -54,13 +55,13 @@ import java.text.RuleBasedCollator; import java.util.Locale; -// G7 test program for printing out test results +import org.junit.jupiter.api.Test; -public class G7Test extends CollatorTest { +import static org.junit.jupiter.api.Assertions.fail; - public static void main(String[] args) throws Exception { - new G7Test().run(args); - } +// G7 test program for printing out test results + +public class G7Test { private static final String testCases[] = { "black-birds", // 0 @@ -158,6 +159,7 @@ 2, 3, 4, 5, 20, 6, 8, 10, 7, 29 }; + @Test public void TestG7Data() { for (int i = 0; i < locales.length; i++) { Collator myCollation= null; @@ -167,14 +169,14 @@ myCollation = Collator.getInstance(locales[i]); tblColl1 = new RuleBasedCollator(((RuleBasedCollator)myCollation).getRules()); } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + " Locale : " + locales[i].getDisplayName() + " getRules failed\n"); continue; } for (int j = 0; j < FIXEDTESTSET; j++) { for (int n = j+1; n < FIXEDTESTSET; n++) { - doTest(tblColl1, testCases[G7Results[i][j]], + TestUtils.doCollatorTest(tblColl1, testCases[G7Results[i][j]], testCases[G7Results[i][n]], -1); } } @@ -185,6 +187,7 @@ /* * Demo Test 1 : Create a new table collation with rules "& Z < p, P" */ + @Test public void TestDemoTest1() { int j = 0; final Collator myCollation = Collator.getInstance(Locale.US); @@ -196,13 +199,13 @@ tblColl = new RuleBasedCollator(newRules); for (j = 0; j < FIXEDTESTSET; j++) { for (int n = j+1; n < FIXEDTESTSET; n++) { - doTest(tblColl, testCases[Test1Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test1Results[j]], testCases[Test1Results[n]], -1); } } tblColl = null; } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 1 Table Collation object creation failed."); } } @@ -211,6 +214,7 @@ * Demo Test 2 : Create a new table collation with rules * "& C < ch , cH, Ch, CH" */ + @Test public void TestDemoTest2() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -220,12 +224,12 @@ RuleBasedCollator tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test2Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test2Results[j]], testCases[Test2Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 2 Table Collation object creation failed.\n"); } } @@ -234,6 +238,7 @@ * Demo Test 3 : Create a new table collation with rules * "& Question'-'mark ; '?' & Hash'-'mark ; '#' & Ampersand ; '&'" */ + @Test public void TestDemoTest3() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -244,12 +249,12 @@ tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test3Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test3Results[j]], testCases[Test3Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 3 Table Collation object creation failed."); } } @@ -258,6 +263,7 @@ * Demo Test 4 : Create a new table collation with rules * " & aa ; a'-' & ee ; e'-' & ii ; i'-' & oo ; o'-' & uu ; u'-' " */ + @Test public void TestDemoTest4() { final Collator myCollation = Collator.getInstance(Locale.US); final String defRules = ((RuleBasedCollator)myCollation).getRules(); @@ -268,12 +274,12 @@ tblColl = new RuleBasedCollator(newRules); for (int j = 0; j < TOTALTESTSET; j++) { for (int n = j+1; n < TOTALTESTSET; n++) { - doTest(tblColl, testCases[Test4Results[j]], + TestUtils.doCollatorTest(tblColl, testCases[Test4Results[j]], testCases[Test4Results[n]], -1); } } } catch (Exception foo) { - errln("Exception: " + foo.getMessage() + + fail("Exception: " + foo.getMessage() + "\nDemo Test 4 Table Collation object creation failed."); } tblColl = null; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/GermanTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/GermanTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/GermanTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/GermanTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test German Collation + * @run junit GermanTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -41,12 +42,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class GermanTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new GermanTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class GermanTest { /* * Shared data for TestPrimary() and TestTertiary() @@ -97,13 +98,15 @@ -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, testSourceData, testTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, testSourceData, testTargetData, tertiaryResults); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/IteratorTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/IteratorTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/IteratorTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/IteratorTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 4062985 4108758 4108762 4157299 * @library /java/text/testlib * @summary Test CollationElementIterator, particularly the new methods in 1.2 + * @run junit IteratorTest */ /* * (C) Copyright IBM Corp. 1998 - All Rights Reserved @@ -40,22 +41,23 @@ import java.util.Locale; import java.text.*; -public class IteratorTest extends CollatorTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class IteratorTest { // TODO: // - Test previous() with contracting character sequences, which don't work // at the moment. // - Test edge cases on setOffset(), e.g. offset > length, etc. // - public static void main(String[] args) throws Exception { - new IteratorTest().run(args); - } - /** * Test for CollationElementIterator.previous() * * @bug 4108758 - Make sure it works with contracting characters * */ + @Test public void TestPrevious() throws ParseException { // A basic test to see if it's working at all backAndForth(en_us.getCollationElementIterator(test1)); @@ -82,6 +84,7 @@ /** * Test for getOffset() and setOffset() */ + @Test public void TestOffset() { CollationElementIterator iter = en_us.getCollationElementIterator(test1); @@ -96,7 +99,7 @@ // Now set the offset back to the beginning and see if it works iter.setOffset(0); - assertEqual(iter, en_us.getCollationElementIterator(test1)); + TestUtils.compareCollationElementIters(iter, en_us.getCollationElementIterator(test1)); // TODO: try iterating halfway through a messy string. } @@ -104,6 +107,7 @@ /** * Test for setText() */ + @Test public void TestSetText() { CollationElementIterator iter1 = en_us.getCollationElementIterator(test1); CollationElementIterator iter2 = en_us.getCollationElementIterator(test2); @@ -117,12 +121,13 @@ // Now set it to point to the same string as the first iterator iter2.setText(test1); - assertEqual(iter1, iter2); + TestUtils.compareCollationElementIters(iter1, iter2); } /** @bug 4108762 * Test for getMaxExpansion() */ + @Test public void TestMaxExpansion() throws ParseException { // Try a simple one first: // The only expansion ends with 'e' and has length 2 @@ -151,6 +156,7 @@ /* * @bug 4157299 */ + @Test public void TestClearBuffers() throws ParseException { RuleBasedCollator c = new RuleBasedCollator("< a < b < c & ab = d"); CollationElementIterator i = c.getCollationElementIterator("abcd"); @@ -160,7 +166,7 @@ i.setOffset(0); // go back to the beginning int e = i.next(); // and get this one again if (e != e0) { - errln("got " + Integer.toString(e, 16) + ", expected " + + fail("got " + Integer.toString(e, 16) + ", expected " + Integer.toString(e0, 16)); } } @@ -179,26 +185,26 @@ while ((o = iter.previous()) != CollationElementIterator.NULLORDER) { if (o != orders[--index]) { - errln("Mismatch at index " + index + ": " + fail("Mismatch at index " + index + ": " + orders[index] + " vs " + o); break; } } if (index != 0) { - errln("Didn't get back to beginning - index is " + index); + fail("Didn't get back to beginning - index is " + index); iter.reset(); - err("next: "); + fail("next: "); while ((o = iter.next()) != NULLORDER) { - err( Integer.toHexString(o) + " "); + fail( Integer.toHexString(o) + " "); } - errln(""); + fail(""); - err("prev: "); + fail("prev: "); while ((o = iter.previous()) != NULLORDER) { - err( Integer.toHexString(o) + " "); + fail( Integer.toHexString(o) + " "); } - errln(""); + fail(""); } } @@ -226,7 +232,7 @@ if (order == NULLORDER || iter.next() != NULLORDER) { iter.reset(); - errln("verifyExpansion: '" + tests[i][0] + + fail("verifyExpansion: '" + tests[i][0] + "' has multiple orders:" + orderString(iter)); } @@ -234,7 +240,7 @@ int expect = new Integer(tests[i][1]).intValue(); if (expansion != expect) { - errln("expansion for '" + tests[i][0] + "' is wrong: " + + fail("expansion for '" + tests[i][0] + "' is wrong: " + "expected " + expect + ", got " + expansion); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/MonkeyTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/MonkeyTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/MonkeyTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/MonkeyTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test Collation, Monkey style + * @run junit MonkeyTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -47,31 +48,32 @@ import java.text.RuleBasedCollator; import java.text.CollationKey; -public class MonkeyTest extends CollatorTest -{ - public static void main(String[] args) throws Exception { - new MonkeyTest().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class MonkeyTest +{ public void report(String s, String t, int result, int revResult) { if (result == -1) { if (revResult != 1) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } else if (result == 1) { if (revResult != -1) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } else if (result == 0) { if (revResult != 0) - errln(" --> Test Failed"); + fail(" --> Test Failed"); } } + @Test public void TestCollationKey() { String source = "-abcdefghijklmnopqrstuvwxyz#&^$@"; @@ -105,16 +107,17 @@ CollationKey2 = myCollator.getCollationKey(addOne); result = CollationKey1.compareTo(CollationKey2); if (result != -1) - errln("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed."); + fail("CollationKey(" + subs + ")" + ".LT." + "CollationKey(" + addOne + ") Failed."); result = CollationKey2.compareTo(CollationKey1); if (result != 1) - errln("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed."); + fail("CollationKey(" + addOne + ")" + ".GT." + "CollationKey(" + subs + ") Failed."); } private static int checkValue(int value) { value *= (value > 0) ? 1 : -1; return value; } + @Test public void TestCompare() { String source = "-abcdefghijklmnopqrstuvwxyz#&^$@"; @@ -140,10 +143,10 @@ String addOne = subs + "\uE000"; result = myCollator.compare(subs, addOne); if (result != -1) - errln("Test : " + subs + " .LT. " + addOne + " Failed."); + fail("Test : " + subs + " .LT. " + addOne + " Failed."); result = myCollator.compare(addOne, subs); if (result != 1) - errln("Test : " + addOne + " .GE. " + subs + " Failed."); + fail("Test : " + addOne + " .GE. " + subs + " Failed."); } private static Collator myCollator = Collator.getInstance(); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Regression.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Regression.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Regression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Regression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,6 +30,7 @@ * @library /java/text/testlib * @summary Regression tests for Collation and associated classes * @modules jdk.localedata + * @run junit Regression */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -47,15 +48,16 @@ import java.util.Locale; import java.util.Vector; +import org.junit.jupiter.api.Test; -public class Regression extends CollatorTest { +import static org.junit.jupiter.api.Assertions.fail; - public static void main(String[] args) throws Exception { - new Regression().run(args); - } + +public class Regression { // CollationElementIterator.reset() doesn't work // + @Test public void Test4048446() { CollationElementIterator i1 = en_us.getCollationElementIterator(test1); CollationElementIterator i2 = en_us.getCollationElementIterator(test1); @@ -64,12 +66,13 @@ } i1.reset(); - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // Collator -> rules -> Collator round-trip broken for expanding characters // + @Test public void Test4051866() throws ParseException { // Build a collator containing expanding characters RuleBasedCollator c1 = new RuleBasedCollator("< o " @@ -84,15 +87,16 @@ // Make sure they're the same if (!c1.getRules().equals(c2.getRules())) { - errln("Rules are not equal"); + fail("Rules are not equal"); } } // Collator thinks "black-bird" == "black" // + @Test public void Test4053636() { if (en_us.equals("black-bird","black")) { - errln("black-bird == black"); + fail("black-bird == black"); } } @@ -100,6 +104,7 @@ // CollationElementIterator will not work correctly if the associated // Collator object's mode is changed // + @Test public void Test4054238() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); @@ -111,18 +116,19 @@ // At this point, BOTH iterators should use NO_DECOMPOSITION, since the // collator itself is in that mode - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // Collator.IDENTICAL documented but not implemented // + @Test public void Test4054734() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); try { c.setStrength(Collator.IDENTICAL); } catch (Exception e) { - errln("Caught " + e.toString() + " setting Collator.IDENTICAL"); + fail("Caught " + e.toString() + " setting Collator.IDENTICAL"); } String[] decomp = { @@ -143,6 +149,7 @@ // Full Decomposition mode not implemented // + @Test public void Test4054736() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setDecomposition(Collator.FULL_DECOMPOSITION); @@ -156,6 +163,7 @@ // Collator.getInstance() causes an ArrayIndexOutofBoundsException for Korean // + @Test public void Test4058613() { // Creating a default collator doesn't work when Korean is the default // locale @@ -169,7 +177,7 @@ // Since the fix to this bug was to turn of decomposition for Korean collators, // ensure that's what we got if (c.getDecomposition() != Collator.NO_DECOMPOSITION) { - errln("Decomposition is not set to NO_DECOMPOSITION"); + fail("Decomposition is not set to NO_DECOMPOSITION"); } } finally { @@ -180,28 +188,30 @@ // RuleBasedCollator.getRules does not return the exact pattern as input // for expanding character sequences // + @Test public void Test4059820() { RuleBasedCollator c = null; try { c = new RuleBasedCollator("< a < b , c/a < d < z"); } catch (ParseException e) { - errln("Exception building collator: " + e.toString()); + fail("Exception building collator: " + e.toString()); return; } if ( c.getRules().indexOf("c/a") == -1) { - errln("returned rules do not contain 'c/a'"); + fail("returned rules do not contain 'c/a'"); } } // MergeCollation::fixEntry broken for "& H < \u0131, \u0130, i, I" // + @Test public void Test4060154() { RuleBasedCollator c = null; try { c = new RuleBasedCollator("< g, G < h, H < i, I < j, J" + " & H < \u0131, \u0130, i, I" ); } catch (ParseException e) { - errln("Exception building collator: " + e.toString()); + fail("Exception building collator: " + e.toString()); return; } c.setDecomposition(Collator.CANONICAL_DECOMPOSITION); @@ -227,6 +237,7 @@ // Secondary/Tertiary comparison incorrect in French Secondary // + @Test public void Test4062418() throws ParseException { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance(Locale.FRANCE); c.setStrength(Collator.SECONDARY); @@ -240,9 +251,10 @@ // Collator.compare() method broken if either string contains spaces // + @Test public void Test4065540() { if (en_us.compare("abcd e", "abcd f") == 0) { - errln("'abcd e' == 'abcd f'"); + fail("'abcd e' == 'abcd f'"); } } @@ -250,6 +262,7 @@ // correct result. For example, // u1EB1 -> \u0103 + \u0300 -> a + \u0306 + \u0300. // + @Test public void Test4066189() { String test1 = "\u1EB1"; String test2 = "a\u0306\u0300"; @@ -262,11 +275,12 @@ c2.setDecomposition(Collator.NO_DECOMPOSITION); CollationElementIterator i2 = en_us.getCollationElementIterator(test2); - assertEqual(i1, i2); + TestUtils.compareCollationElementIters(i1, i2); } // French secondary collation checking at the end of compare iteration fails // + @Test public void Test4066696() { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance(Locale.FRANCE); c.setStrength(Collator.SECONDARY); @@ -281,6 +295,7 @@ // Bad canonicalization of same-class combining characters // + @Test public void Test4076676() { // These combining characters are all in the same class, so they should not // be reordered, and they should compare as unequal. @@ -291,38 +306,41 @@ c.setStrength(Collator.TERTIARY); if (c.compare(s1,s2) == 0) { - errln("Same-class combining chars were reordered"); + fail("Same-class combining chars were reordered"); } } // RuleBasedCollator.equals(null) throws NullPointerException // + @Test public void Test4079231() { try { if (en_us.equals(null)) { - errln("en_us.equals(null) returned true"); + fail("en_us.equals(null) returned true"); } } catch (Exception e) { - errln("en_us.equals(null) threw " + e.toString()); + fail("en_us.equals(null) threw " + e.toString()); } } // RuleBasedCollator breaks on "< a < bb" rule // + @Test public void Test4078588() throws ParseException { RuleBasedCollator rbc=new RuleBasedCollator("< a < bb"); int result = rbc.compare("a","bb"); if (result != -1) { - errln("Compare(a,bb) returned " + result + "; expected -1"); + fail("Compare(a,bb) returned " + result + "; expected -1"); } } // Combining characters in different classes not reordered properly. // + @Test public void Test4081866() throws ParseException { // These combining characters are all in different classes, // so they should be reordered and the strings should compare as equal. @@ -338,12 +356,13 @@ c.setDecomposition(Collator.CANONICAL_DECOMPOSITION); if (c.compare(s1,s2) != 0) { - errln("Combining chars were not reordered"); + fail("Combining chars were not reordered"); } } // string comparison errors in Scandinavian collators // + @Test public void Test4087241() { RuleBasedCollator c = (RuleBasedCollator) Collator.getInstance( new Locale("da", "DK")); @@ -360,6 +379,7 @@ // CollationKey takes ignorable strings into account when it shouldn't // + @Test public void Test4087243() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -374,6 +394,7 @@ // Mu/micro conflict // Micro symbol and greek lowercase letter Mu should sort identically // + @Test public void Test4092260() { Collator c = Collator.getInstance(new Locale("el", "")); @@ -401,6 +422,7 @@ compareArray(c, tests); } + @Test public void Test4101940() { try { RuleBasedCollator c = new RuleBasedCollator("< a < b"); @@ -408,16 +430,17 @@ i.reset(); if (i.next() != i.NULLORDER) { - errln("next did not return NULLORDER"); + fail("next did not return NULLORDER"); } } catch (Exception e) { - errln("Caught " + e ); + fail("Caught " + e ); } } // Collator.compare not handling spaces properly // + @Test public void Test4103436() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -432,6 +455,7 @@ // Collation not Unicode conformant with Hangul syllables // + @Test public void Test4114076() { RuleBasedCollator c = (RuleBasedCollator) en_us.clone(); c.setStrength(Collator.TERTIARY); @@ -457,18 +481,20 @@ // Collator.getCollationKey was hanging on certain character sequences // + @Test public void Test4124632() throws Exception { Collator coll = Collator.getInstance(Locale.JAPAN); try { coll.getCollationKey("A\u0308bc"); } catch (OutOfMemoryError e) { - errln("Ran out of memory -- probably an infinite loop"); + fail("Ran out of memory -- probably an infinite loop"); } } // sort order of french words with multiple accents has errors // + @Test public void Test4132736() { Collator c = Collator.getInstance(Locale.FRANCE); @@ -481,6 +507,7 @@ // The sorting using java.text.CollationKey is not in the exact order // + @Test public void Test4133509() { String[] test1 = { "Exception", "<", "ExceptionInInitializerError", @@ -492,6 +519,7 @@ // Collation with decomposition off doesn't work for Europe // + @Test public void Test4114077() { // Ensure that we get the same results with decomposition off // as we do with it on.... @@ -519,6 +547,7 @@ // Support for Swedish gone in 1.1.6 (Can't create Swedish collator) // + @Test public void Test4141640() { // // Rather than just creating a Swedish collator, we might as well @@ -531,7 +560,7 @@ try { Collator c = Collator.getInstance(locales[i]); } catch (Exception e) { - errln("Caught " + e + " creating collator for " + locales[i]); + fail("Caught " + e + " creating collator for " + locales[i]); } } } @@ -539,6 +568,7 @@ // getCollationKey throws exception for spanish text // Cannot reproduce this bug on 1.2, however it DOES fail on 1.1.6 // + @Test public void Test4139572() { // // Code pasted straight from the bug report @@ -553,6 +583,7 @@ // RuleBasedCollator doesn't use getCollationElementIterator internally // + @Test public void Test4146160() throws ParseException { // // Use a custom collator class whose getCollationElementIterator @@ -561,13 +592,13 @@ My4146160Collator.count = 0; new My4146160Collator().getCollationKey("1"); if (My4146160Collator.count < 1) { - errln("getCollationElementIterator not called"); + fail("getCollationElementIterator not called"); } My4146160Collator.count = 0; new My4146160Collator().compare("1", "2"); if (My4146160Collator.count < 1) { - errln("getCollationElementIterator not called"); + fail("getCollationElementIterator not called"); } } @@ -592,6 +623,7 @@ // CollationElementIterator.previous broken for expanding char sequences // + @Test public void Test4179686() throws ParseException { // Create a collator with a few expanding character sequences in it.... @@ -617,7 +649,7 @@ int expect = ((Integer)elements.elementAt(index)).intValue(); if (elem != expect) { - errln("Mismatch at index " + index + fail("Mismatch at index " + index + ": got " + Integer.toString(elem,16) + ", expected " + Integer.toString(expect,16)); } @@ -625,6 +657,7 @@ } } + @Test public void Test4244884() throws ParseException { RuleBasedCollator coll = (RuleBasedCollator)Collator.getInstance(Locale.US); coll = new RuleBasedCollator(coll.getRules() @@ -644,13 +677,14 @@ for (int i = 1; i < testStrings.length; i++) { if (coll.compare(testStrings[i - 1], testStrings[i]) >= 0) { - errln("error: \"" + testStrings[i - 1] + fail("error: \"" + testStrings[i - 1] + "\" is greater than or equal to \"" + testStrings[i] + "\"."); } } } + @Test public void Test4179216() throws ParseException { // you can position a CollationElementIterator in the middle of // a contracting character sequence, yielding a bogus collation @@ -673,7 +707,7 @@ int elt5 = CollationElementIterator.primaryOrder(iter.next()); if (elt4 != elt0 || elt5 != elt0) - errln("The collation elements at positions 0 (" + elt0 + "), 4 (" + fail("The collation elements at positions 0 (" + elt0 + "), 4 (" + elt4 + "), and 5 (" + elt5 + ") don't match."); // test that the "cat" combination works properly @@ -697,7 +731,7 @@ if (elt14 != elt15 || elt14 != elt16 || elt14 != elt17 || elt14 != elt18 || elt14 != elt19) - errln("\"cat\" elements don't match: elt14 = " + elt14 + ", elt15 = " + fail("\"cat\" elements don't match: elt14 = " + elt14 + ", elt15 = " + elt15 + ", elt16 = " + elt16 + ", elt17 = " + elt17 + ", elt18 = " + elt18 + ", elt19 = " + elt19); @@ -735,14 +769,15 @@ } for (int i = 0; i < nextElements.length; i++) { if (nextElements[i].equals(setOffsetElements[i])) { - logln(nextElements[i]); + System.out.println(nextElements[i]); } else { - errln("Error: next() yielded " + nextElements[i] + ", but setOffset() yielded " + fail("Error: next() yielded " + nextElements[i] + ", but setOffset() yielded " + setOffsetElements[i]); } } } + @Test public void Test4216006() throws Exception { // rule parser barfs on "<\u00e0=a\u0300", and on other cases // where the same token (after normalization) appears twice in a row @@ -769,6 +804,7 @@ compareArray(collator, tests); } + @Test public void Test4171974() { // test French accent ordering more thoroughly String[] frenchList = { @@ -800,10 +836,10 @@ }; Collator french = Collator.getInstance(Locale.FRENCH); - logln("Testing French order..."); + System.out.println("Testing French order..."); checkListOrder(frenchList, french); - logln("Testing French order without decomposition..."); + System.out.println("Testing French order without decomposition..."); french.setDecomposition(Collator.NO_DECOMPOSITION); checkListOrder(frenchList, french); @@ -836,10 +872,10 @@ }; Collator english = Collator.getInstance(Locale.ENGLISH); - logln("Testing English order..."); + System.out.println("Testing English order..."); checkListOrder(englishList, english); - logln("Testing English order without decomposition..."); + System.out.println("Testing English order without decomposition..."); english.setDecomposition(Collator.NO_DECOMPOSITION); checkListOrder(englishList, english); } @@ -849,35 +885,36 @@ // passed-in list is already sorted into ascending order for (int i = 0; i < sortedList.length - 1; i++) { if (c.compare(sortedList[i], sortedList[i + 1]) >= 0) { - errln("List out of order at element #" + i + ": " - + prettify(sortedList[i]) + " >= " - + prettify(sortedList[i + 1])); + fail("List out of order at element #" + i + ": " + + TestUtils.prettify(sortedList[i]) + " >= " + + TestUtils.prettify(sortedList[i + 1])); } } } // CollationElementIterator set doesn't work propertly with next/prev + @Test public void Test4663220() { RuleBasedCollator collator = (RuleBasedCollator)Collator.getInstance(Locale.US); CharacterIterator stringIter = new StringCharacterIterator("fox"); CollationElementIterator iter = collator.getCollationElementIterator(stringIter); int[] elements_next = new int[3]; - logln("calling next:"); + System.out.println("calling next:"); for (int i = 0; i < 3; ++i) { - logln("[" + i + "] " + (elements_next[i] = iter.next())); + System.out.println("[" + i + "] " + (elements_next[i] = iter.next())); } int[] elements_fwd = new int[3]; - logln("calling set/next:"); + System.out.println("calling set/next:"); for (int i = 0; i < 3; ++i) { iter.setOffset(i); - logln("[" + i + "] " + (elements_fwd[i] = iter.next())); + System.out.println("[" + i + "] " + (elements_fwd[i] = iter.next())); } for (int i = 0; i < 3; ++i) { if (elements_next[i] != elements_fwd[i]) { - errln("mismatch at position " + i + + fail("mismatch at position " + i + ": " + elements_next[i] + " != " + elements_fwd[i]); } @@ -904,8 +941,8 @@ int result = c.compare(tests[i], tests[i+2]); if (sign(result) != sign(expect)) { - errln( i/3 + ": compare(" + prettify(tests[i]) - + " , " + prettify(tests[i+2]) + fail( i/3 + ": compare(" + TestUtils.prettify(tests[i]) + + " , " + TestUtils.prettify(tests[i+2]) + ") got " + result + "; expected " + expect); } else @@ -916,11 +953,11 @@ result = k1.compareTo(k2); if (sign(result) != sign(expect)) { - errln( i/3 + ": key(" + prettify(tests[i]) - + ").compareTo(key(" + prettify(tests[i+2]) + fail( i/3 + ": key(" + TestUtils.prettify(tests[i]) + + ").compareTo(key(" + TestUtils.prettify(tests[i+2]) + ")) got " + result + "; expected " + expect); - errln(" " + prettify(k1) + " vs. " + prettify(k2)); + fail(" " + TestUtils.prettifyCKey(k1) + " vs. " + TestUtils.prettifyCKey(k2)); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/SpanishTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SpanishTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/SpanishTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SpanishTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,6 +25,7 @@ * @test * @library /java/text/testlib * @summary test Spanish Collation + * @run junit SpanishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -41,12 +42,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class SpanishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new SpanishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class SpanishTest { /* * TestPrimary() @@ -92,13 +93,15 @@ -1, -1, 1, -1, -1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/SurrogatesTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SurrogatesTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/SurrogatesTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/SurrogatesTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,17 +25,18 @@ * @test * @library /java/text/testlib * @summary test Supplementary Character Collation + * @run junit SurrogatesTest */ import java.text.Collator; import java.text.RuleBasedCollator; -// Quick dummy program for printing out test results -public class SurrogatesTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new SurrogatesTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class SurrogatesTest { /* * Data for TestPrimary() @@ -83,13 +84,15 @@ -1, 1, 1, 1, -1, -1, -1, -1, 1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } @@ -108,7 +111,7 @@ + "&\ud800\udc0a < x, X" + "&A < \ud800\udc04\ud800\udc05"); } catch (Exception e) { - errln("Failed to create new RulebasedCollator object"); + fail("Failed to create new RulebasedCollator object"); return null; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Test4401726.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Test4401726.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/Test4401726.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/Test4401726.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @author John O'Conner * @library /java/text/testlib * @summary Regression tests for Collation and associated classes + * @run junit Test4401726 */ @@ -34,12 +35,13 @@ import java.util.Locale; import java.util.Vector; -public class Test4401726 extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new Test4401726().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; +public class Test4401726 { + + @Test public void TestSetOffSet() { int[] expected = {0, -1, 65536}; @@ -60,7 +62,7 @@ actual[2] = iterator.next(); if (compareArray(expected, actual) == false) { - errln("Failed."); + fail("Failed."); } str = "a"; @@ -72,11 +74,11 @@ actual[2] = iterator.next(); if (compareArray(expected, actual) == false) { - errln("Failed."); + fail("Failed."); } } catch (ParseException e) { - errln("Unexpected ParseException: " + e); + fail("Unexpected ParseException: " + e); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/ThaiTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/ThaiTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/ThaiTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/ThaiTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Thai Collation * @modules jdk.localedata + * @run junit ThaiTest */ /* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. @@ -39,11 +40,11 @@ import java.text.Collator; import java.text.RuleBasedCollator; -public class ThaiTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new ThaiTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class ThaiTest { /* * Data for TestPrimary() @@ -148,8 +149,9 @@ 0, 0, 0 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/TurkishTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/TurkishTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/TurkishTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/TurkishTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @library /java/text/testlib * @summary test Turkish Collation * @modules jdk.localedata + * @run junit TurkishTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,12 +43,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class TurkishTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TurkishTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class TurkishTest { /* * Data for TestPrimary() @@ -105,13 +106,15 @@ -1, -1, -1, -1, 1, -1, -1, 1, -1, -1 }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, primarySourceData, primaryTargetData, primaryResults); } + @Test public void TestTertiary() { - doTest(myCollation, Collator.TERTIARY, + TestUtils.doCollatorTest(myCollation, Collator.TERTIARY, tertiarySourceData, tertiaryTargetData, tertiaryResults); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Collator/VietnameseTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Collator/VietnameseTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Collator/VietnameseTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Collator/VietnameseTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ * @library /java/text/testlib * @summary test Vietnamese Collation * @modules jdk.localedata + * @run junit VietnameseTest */ /* @@ -44,12 +45,12 @@ import java.util.Locale; import java.text.Collator; -// Quick dummy program for printing out test results -public class VietnameseTest extends CollatorTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new VietnameseTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +// Quick dummy program for printing out test results +public class VietnameseTest { private final static String testPS[] = { "a", @@ -346,17 +347,19 @@ "Z" }; + @Test public void TestPrimary() { - doTest(myCollation, Collator.PRIMARY, testPS, testPT, testPR); + TestUtils.doCollatorTest(myCollation, Collator.PRIMARY, testPS, testPT, testPR); } + @Test public void TestTertiary() { int testLength = testT.length; myCollation.setStrength(Collator.TERTIARY); for (int i = 0; i < testLength - 1; i++) { for (int j = i+1; j < testLength; j++) { - doTest(myCollation, testT[i], testT[j], -1); + TestUtils.doCollatorTest(myCollation, testT[i], testT[j], -1); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4185732Test.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,14 +22,6 @@ */ /* - * @test - * @bug 4185732 - * @library /java/text/testlib - * @build Bug4185732Test IntlTest HexDumpReader - * @run main Bug4185732Test - * @summary test that ChoiceFormat invariants are preserved across serialization - */ -/* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this @@ -63,58 +55,50 @@ * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ -import java.util.*; -import java.io.*; +/* + * @test + * @bug 4185732 + * @library /java/text/testlib + * @build HexDumpReader + * @summary Test that ChoiceFormat invariants are preserved across serialization. + * This test depends on Bug4185732.ser.txt and will fail otherwise. + * @run junit Bug4185732Test + */ + +import java.io.InvalidObjectException; +import java.io.ObjectInputStream; import java.text.ChoiceFormat; -/** - * A Locale can never contains language codes of he, yi or id. - */ -public class Bug4185732Test extends IntlTest { - public static void main(String[] args) throws Exception { - if (args.length == 1 && args[0].equals("prepTest")) { - prepTest(); - } else { - new Bug4185732Test().run(args); - } - } +import org.junit.jupiter.api.Test; - public void testIt() throws Exception { +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4185732Test { + + /* + * The ChoiceFormat class requires that its choiceFormats and choiceLimits + * arrays have the same length. This test ensures that the invariant is enforced + * during the readObject() call. + */ + @Test + public void choiceFormatSerializationInvariantsTest() { try { + // A serialized ChoiceFormat with unequal formats and limits final ObjectInputStream in = new ObjectInputStream(HexDumpReader.getStreamFromHexDump("Bug4185732.ser.txt")); final ChoiceFormat loc = (ChoiceFormat)in.readObject(); if (loc.getFormats().length != loc.getLimits().length) { - errln("ChoiceFormat did not properly check stream"); + fail("ChoiceFormat did not properly check stream"); } else { - //for some reason, the data file was VALID. This test - //requires a corrupt data file the format and limit - //arrays are of different length. - errln("Test data file was not properly created"); + // for some reason, the data file was VALID. This test + // requires a corrupt data file the format and limit + // arrays are of different length. + fail("Test data file was not properly created"); } - } catch (InvalidObjectException e) { - //this is what we want to have happen - } catch (Exception e) { - errln(e.toString()); - } - } - - /** - * Create a data file for this test. The data file must be corrupted by hand. - */ - private static void prepTest() { - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("Bug4185732.ser")); - final double[] limits = {1,2,3,4,5,6,7}; - final String[] formats = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; - final ChoiceFormat fmt = new ChoiceFormat(limits, formats); - out.writeObject(fmt); - out.close(); - System.out.println("You must invalidate the output file before running the test"); - System.out.println("by modifying the length of one of the array"); - } catch (Exception e) { - System.out.println(e); + } catch (InvalidObjectException expectedException) { + // Expecting an IOE + } catch (Exception wrongException) { + fail("Expected an InvalidObjectException, instead got: " + wrongException); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug4387255.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4387255.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug4387255.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug4387255.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,16 +21,25 @@ * questions. */ -/** +/* * @test * @bug 4387255 * @summary Verifies that ChoiceFormat can handle large numbers of choices + * (previously capped at 30). + * @run junit Bug4387255 */ import java.text.ChoiceFormat; -public class Bug4387255 { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.params.provider.Arguments.arguments; +public class Bug4387255 { private static final double[] doubles = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, @@ -49,21 +58,39 @@ "|20#K|21#L|22#M|23#N|24#O|25#P|26#Q|27#R|28#S|29#T" + "|30#U|31#V|32#W|33#X|34#Y|35#Z"; - public static void main(String[] args) throws Exception { - ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings); - ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern); - if (!choiceFormat1.equals(choiceFormat2)) { - System.out.println("choiceFormat1: " + choiceFormat1.toPattern()); - System.out.println("choiceFormat2: " + choiceFormat2.toPattern()); - throw new RuntimeException(); - } + private static final ChoiceFormat choiceFormat1 = new ChoiceFormat(doubles, strings); + private static final ChoiceFormat choiceFormat2 = new ChoiceFormat(pattern); + // Ensure that both the large ChoiceFormats format each value properly + @ParameterizedTest + @MethodSource + public void largeChoicesTest(double db, String expectedString) { + String result = choiceFormat2.format(db); + assertEquals(expectedString, result, + "Wrong format result with: " + choiceFormat2); + } + + + /* + * Create arguments in form of : (double, string) + * Each string is the expected result of ChoiceFormat.format(double) + */ + private static Arguments[] largeChoicesTest() { + Arguments[] doublesAndStrings = new Arguments[doubles.length]; for (int i = 0; i < doubles.length; i++) { - String result = choiceFormat2.format(doubles[i]); - if (!result.equals(strings[i])) { - throw new RuntimeException("Wrong format result - expected " + - strings[i] + ", got " + result); - } + doublesAndStrings[i] = arguments(doubles[i], strings[i]); } + return doublesAndStrings; + } + + /* + * Check that creating a ChoiceFormat with limits and formats arrays + * equivalent to a string pattern are equal. (Checks that both constructors + * allow for a large number of choices and formats) + */ + @Test + public void patternEqualsArraysTest() { + assertEquals(choiceFormat1, choiceFormat2, "Pattern is equivalent to " + + "formats and limits, but ChoiceFormats are not equal"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug8001209.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug8001209.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/ChoiceFormat/Bug8001209.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/ChoiceFormat/Bug8001209.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,70 +21,90 @@ * questions. */ -/** +/* * @test * @bug 8001209 * @summary Confirm that the values set by setChoices() are not mutable. + * @run junit Bug8001209 */ -import java.text.*; -public class Bug8001209 { +import java.text.ChoiceFormat; +import java.text.ParsePosition; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - boolean err = false; +import static org.junit.jupiter.api.Assertions.assertEquals; - // Borrow an example in API doc - double[] limits = {1,2,3,4,5,6,7}; - String[] dayOfWeekNames = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; - ChoiceFormat form = new ChoiceFormat(limits, dayOfWeekNames); - ParsePosition status = new ParsePosition(0); +public class Bug8001209 { + + // Represents the expected output of formatting the ChoiceFormat + private static String expectedFormattedOutput; + private static ChoiceFormat cFmt; + private static ParsePosition status; + private static String[] originalSetterArray; + + // Build the original ChoiceFormat to test if it can be mutated + @BeforeAll + static void setUpChoiceFormatAndOutput() { + double[] limits = {1, 2, 3, 4, 5, 6, 7}; + originalSetterArray = new String[]{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + // Constructor calls setChoices + cFmt = new ChoiceFormat(limits, originalSetterArray); + status = new ParsePosition(0); + // Build the expected results of formatting with the original ChoiceFormat StringBuilder before = new StringBuilder(); for (double i = 1.0; i <= 7.0; ++i) { status.setIndex(0); - String s = form.format(i); + String s = cFmt.format(i); before.append(" "); before.append(s); - before.append(form.parse(form.format(i),status)); + before.append(cFmt.parse(cFmt.format(i), status)); } - String original = before.toString(); + expectedFormattedOutput = before.toString(); + } - double[] newLimits = form.getLimits(); - String[] newFormats = (String[])form.getFormats(); + /* + * Ensure that mutating the arrays returned by getChoices and getLimits does + * not affect the internal representation of the ChoiceFormat. + */ + @Test + public void immutableArraysFromGetters() { + // Modify the array returned by getFormats() -> newFormats + String[] newFormats = (String[]) cFmt.getFormats(); newFormats[6] = "Doyoubi"; StringBuilder after = new StringBuilder(); for (double i = 1.0; i <= 7.0; ++i) { status.setIndex(0); - String s = form.format(i); + String s = cFmt.format(i); after.append(" "); after.append(s); - after.append(form.parse(form.format(i),status)); - } - if (!original.equals(after.toString())) { - err = true; - System.err.println(" Expected:" + before - + "\n Got: " + after); + after.append(cFmt.parse(cFmt.format(i), status)); } + // Compare the expected results with the new formatted results + assertEquals(after.toString(), expectedFormattedOutput, + "Mutating array returned from getter changed internals of ChoiceFormat"); + } - dayOfWeekNames[6] = "Saturday"; - after = new StringBuilder(); + /* + * Ensure that mutating the arrays passed to setChoices/constructor does + * not affect the internal representation of the ChoiceFormat. + */ + @Test + public void immutableArraysFromSetter() { + // Modify the array passed to setFormats() -> dayOfWeekNames + originalSetterArray[6] = "Saturday"; + StringBuilder after = new StringBuilder(); for (double i = 1.0; i <= 7.0; ++i) { status.setIndex(0); - String s = form.format(i); + String s = cFmt.format(i); after.append(" "); after.append(s); - after.append(form.parse(form.format(i),status)); - } - if (!original.equals(after.toString())) { - err = true; - System.err.println(" Expected:" + before - + "\n Got: " + after); - } - - if (err) { - throw new RuntimeException("Failed."); - } else { - System.out.println("Passed."); + after.append(cFmt.parse(cFmt.format(i), status)); } + // Compare the expected results with the new formatted results + assertEquals(after.toString(), expectedFormattedOutput, + "Mutating array passed to setter changed internals of ChoiceFormat"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/Bug4322313.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/Bug4322313.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/Bug4322313.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/Bug4322313.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,17 +24,22 @@ /** * @test * @bug 4322313 4833268 6302990 6304305 - * @library /java/text/testlib * @summary Make sure that new implementation for * SimpleDateFormat.parse('z' or 'Z') and format('z' or 'Z') work correctly. + * @run junit Bug4322313 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug4322313 extends IntlTest { +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4322313 { + + @Test public void Test4322313() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -200,7 +205,7 @@ ", got:" + date.getTime() + ", " + date); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale) + ", " + formats[j] + "/\"" + valids[k][0] + "\"] expected:" + valids[k][1] + @@ -252,7 +257,7 @@ ", got:" + s + ", " + date); } else { /* - logln("\tFormat Okay [Locale=" + + System.out.println("\tFormat Okay [Locale=" + locale + ", " + formats[j] + "/\"" + valids[k][0] + "\"] expected:" + valids[k][2+j] + @@ -286,7 +291,7 @@ invalids[k][1] + ", got: " + offset); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale + ", " + formats[j] + "/\"" + invalids[k][0] + "\"] correct offset: " + offset); @@ -322,7 +327,7 @@ invalids[k][1] + ", got: " + offset); } else { /* - logln("\tParse Okay [Locale=" + + System.out.println("\tParse Okay [Locale=" + locale + ", " + formats[j] + "/\"" + invalids[k][0] + "\"] Expected exception occurred with an correct offset: " @@ -354,12 +359,9 @@ Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); if (err) { - errln("SimpleDateFormat.parse()/format() test failed"); + fail("SimpleDateFormat.parse()/format() test failed"); } } } - public static void main(String[] args) throws Exception { - new Bug4322313().run(args); - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRegression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,62 +25,64 @@ import java.util.*; import java.io.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @test * @bug 4029195 4052408 4056591 4059917 4060212 4061287 4065240 4071441 4073003 * 4089106 4100302 4101483 4103340 4103341 4104136 4104522 4106807 4108407 * 4134203 4138203 4148168 4151631 4151706 4153860 4162071 4182066 4209272 4210209 - * 4213086 4250359 4253490 4266432 4406615 4413980 8008577 + * 4213086 4250359 4253490 4266432 4406615 4413980 8008577 8305853 * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRegression */ -public class DateFormatRegression extends IntlTest { - - public static void main(String[] args) throws Exception { - new DateFormatRegression().run(args); - } +public class DateFormatRegression { + @Test public void Test4029195() { @SuppressWarnings("deprecation") Date today = new Date(); - logln("today: " + today); + System.out.println("today: " + today); SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateInstance(); - logln("pattern: " + sdf.toPattern()); - logln("today: " + sdf.format(today)); + System.out.println("pattern: " + sdf.toPattern()); + System.out.println("today: " + sdf.format(today)); sdf.applyPattern("G yyyy DDD"); String todayS = sdf.format(today); - logln("today: " + todayS); + System.out.println("today: " + todayS); try { today = sdf.parse(todayS); - logln("today date: " + today); + System.out.println("today date: " + today); } catch(Exception e) { - logln("Error reparsing date: " + e.getMessage()); + System.out.println("Error reparsing date: " + e.getMessage()); } try { String rt = sdf.format(sdf.parse(todayS)); - logln("round trip: " + rt); - if (!rt.equals(todayS)) errln("Fail: Want " + todayS + " Got " + rt); + System.out.println("round trip: " + rt); + if (!rt.equals(todayS)) fail("Fail: Want " + todayS + " Got " + rt); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4052408() { DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US); @SuppressWarnings("deprecation") Date date = new Date(97, Calendar.MAY, 3, 8, 55); String str; - logln(str = fmt.format(date)); + System.out.println(str = fmt.format(date)); if (!str.equals("5/3/97 8:55 AM")) - errln("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str); + fail("Fail: Test broken; Want 5/3/97 8:55 AM Got " + str); Map expected = new HashMap<>(); expected.put(DateFormat.MONTH_FIELD, "5"); expected.put(DateFormat.DATE_FIELD, "3"); @@ -117,33 +119,34 @@ char[] dst = new char[pos.getEndIndex() - pos.getBeginIndex()]; buf.getChars(pos.getBeginIndex(), pos.getEndIndex(), dst, 0); str = new String(dst); - log(i + ": " + fieldNames[i] + + System.out.println(i + ": " + fieldNames[i] + ", \"" + str + "\", " + pos.getBeginIndex() + ", " + pos.getEndIndex()); String exp = expected.get(i); if ((exp == null && str.length() == 0) || str.equals(exp)) - logln(" ok"); + System.out.println(" ok"); else { - logln(" expected " + exp); + System.out.println(" expected " + exp); pass = false; } } - if (!pass) errln("Fail: FieldPosition not set right by DateFormat"); + if (!pass) fail("Fail: FieldPosition not set right by DateFormat"); } /** * Verify the function of the [s|g]et2DigitYearStart() API. */ @SuppressWarnings("deprecation") + @Test public void Test4056591() { try { SimpleDateFormat fmt = new SimpleDateFormat("yyMMdd", Locale.US); Date start = new Date(1809-1900, Calendar.DECEMBER, 25); fmt.set2DigitYearStart(start); if (!fmt.get2DigitYearStart().equals(start)) - errln("get2DigitYearStart broken"); + fail("get2DigitYearStart broken"); Object[] DATA = { "091225", new Date(1809-1900, Calendar.DECEMBER, 25), "091224", new Date(1909-1900, Calendar.DECEMBER, 24), @@ -154,20 +157,21 @@ String s = (String) DATA[i]; Date exp = (Date) DATA[i+1]; Date got = fmt.parse(s); - logln(s + " -> " + got + "; exp " + exp); - if (!got.equals(exp)) errln("set2DigitYearStart broken"); + System.out.println(s + " -> " + got + "; exp " + exp); + if (!got.equals(exp)) fail("set2DigitYearStart broken"); } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4059917() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -185,54 +189,55 @@ void aux917( SimpleDateFormat fmt, String str ) { try { - logln( "==================" ); - logln( "testIt: pattern=" + fmt.toPattern() + + System.out.println( "==================" ); + System.out.println( "testIt: pattern=" + fmt.toPattern() + " string=" + str ); Object o; o = fmt.parseObject( str ); - logln( "Parsed object: " + o ); + System.out.println( "Parsed object: " + o ); String formatted = fmt.format( o ); - logln( "Formatted string: " + formatted ); - if (!formatted.equals(str)) errln("Fail: Want " + str + " Got " + formatted); + System.out.println( "Formatted string: " + formatted ); + if (!formatted.equals(str)) fail("Fail: Want " + str + " Got " + formatted); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4060212() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { String dateString = "1995-040.05:01:29"; - logln( "dateString= " + dateString ); - logln("Using yyyy-DDD.hh:mm:ss"); + System.out.println( "dateString= " + dateString ); + System.out.println("Using yyyy-DDD.hh:mm:ss"); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-DDD.hh:mm:ss"); ParsePosition pos = new ParsePosition(0); Date myDate = formatter.parse( dateString, pos ); String myString = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.LONG).format( myDate ); - logln( myString ); + System.out.println( myString ); Calendar cal = new GregorianCalendar(); cal.setTime(myDate); if (cal.get(Calendar.DAY_OF_YEAR) != 40) - errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + + fail("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40"); - logln("Using yyyy-ddd.hh:mm:ss"); + System.out.println("Using yyyy-ddd.hh:mm:ss"); formatter = new SimpleDateFormat("yyyy-ddd.hh:mm:ss"); pos = new ParsePosition(0); myDate = formatter.parse( dateString, pos ); myString = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.LONG).format( myDate ); - logln( myString ); + System.out.println( myString ); cal.setTime(myDate); if (cal.get(Calendar.DAY_OF_YEAR) != 40) - errln("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + + fail("Fail: Got " + cal.get(Calendar.DAY_OF_YEAR) + " Want 40"); } finally { @@ -240,24 +245,26 @@ } } + @Test public void Test4061287() { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { - logln(df.parse("35/01/1971").toString()); + System.out.println(df.parse("35/01/1971").toString()); } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } df.setLenient(false); boolean ok = false; try { - logln(df.parse("35/01/1971").toString()); + System.out.println(df.parse("35/01/1971").toString()); } catch (ParseException e) {ok=true;} - if (!ok) errln("Fail: Lenient not working"); + if (!ok) fail("Fail: Lenient not working"); } @SuppressWarnings("deprecation") + @Test public void Test4065240() { Date curDate; DateFormat shortdate, fulldate; @@ -276,13 +283,13 @@ format(curDate)); strFullDate = new String("The current date (long form) is " + fulldate.format(curDate)); - logln(strShortDate); - logln(strFullDate); + System.out.println(strShortDate); + System.out.println(strFullDate); // UPDATE THIS AS ZONE NAME RESOURCE FOR in de_DE is updated if (!strFullDate.endsWith("EST") && !strFullDate.endsWith("GMT-05:00")) { - errln("Fail: Want GMT-05:00"); + fail("Fail: Want GMT-05:00"); } } finally { @@ -301,6 +308,7 @@ Currently this bug breaks MessageFormat.toPattern */ @SuppressWarnings("deprecation") + @Test public void Test4071441() { DateFormat fmtA = DateFormat.getInstance(); DateFormat fmtB = DateFormat.getInstance(); @@ -311,15 +319,15 @@ calA.setTime(epoch); calB.setTime(epoch); if (!calA.equals(calB)) - errln("Fail: Can't complete test; Calendar instances unequal"); + fail("Fail: Can't complete test; Calendar instances unequal"); if (!fmtA.equals(fmtB)) - errln("Fail: DateFormat unequal when Calendars equal"); + fail("Fail: DateFormat unequal when Calendars equal"); calB.setTime(xmas); if (calA.equals(calB)) - errln("Fail: Can't complete test; Calendar instances equal"); + fail("Fail: Can't complete test; Calendar instances equal"); if (!fmtA.equals(fmtB)) - errln("Fail: DateFormat unequal when Calendars equivalent"); - logln("DateFormat.equals ok"); + fail("Fail: DateFormat unequal when Calendars equivalent"); + System.out.println("DateFormat.equals ok"); } /* The java.text.DateFormat.parse(String) method expects for the @@ -332,6 +340,7 @@ Please extend the parsing method(s) to handle strings with four-digit year values (probably also applicable to various other locales. */ + @Test public void Test4073003() { try { DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); @@ -342,32 +351,34 @@ String s = fmt.format(d); String ss = fmt.format(dd); if (!d.equals(dd)) - errln("Fail: " + d + " != " + dd); + fail("Fail: " + d + " != " + dd); if (!s.equals(ss)) - errln("Fail: " + s + " != " + ss); - logln("Ok: " + s + " " + d); + fail("Fail: " + s + " != " + ss); + System.out.println("Ok: " + s + " " + d); } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } + @Test public void Test4089106() { TimeZone def = TimeZone.getDefault(); try { - TimeZone z = new SimpleTimeZone((int)(1.25 * 3600000), "FAKEZONE"); - TimeZone.setDefault(z); + TimeZone customTz = TimeZone.getTimeZone("GMT-08:15"); + TimeZone.setDefault(customTz); SimpleDateFormat f = new SimpleDateFormat(); - if (!f.getTimeZone().equals(z)) - errln("Fail: SimpleTimeZone should use TimeZone.getDefault()"); + if (!f.getTimeZone().equals(customTz)) + fail("Fail: SimpleDateFormat should use TimeZone.getDefault()"); } finally { TimeZone.setDefault(def); } } + @Test public void Test4100302() { Locale[] locales = new Locale[] { Locale.CANADA, @@ -414,21 +425,21 @@ if (!format.equals(ois.readObject())) { pass = false; - logln("DateFormat instance for locale " + + System.out.println("DateFormat instance for locale " + locales[i] + " is incorrectly serialized/deserialized."); } else { - logln("DateFormat instance for locale " + + System.out.println("DateFormat instance for locale " + locales[i] + " is OKAY."); } } - if (!pass) errln("Fail: DateFormat serialization/equality bug"); + if (!pass) fail("Fail: DateFormat serialization/equality bug"); } catch (IOException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } catch (ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } @@ -437,6 +448,7 @@ * Test whether DataFormat can be serialized/deserialized correctly * even if invalid/customized TimeZone is used. */ + @Test public void Test4413980() { TimeZone savedTimeZone = TimeZone.getDefault(); try { @@ -465,23 +477,23 @@ if (!format.equals(ois.readObject())) { pass = false; - logln("DateFormat instance which uses TimeZone <" + + System.out.println("DateFormat instance which uses TimeZone <" + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("DateFormat instance which uses TimeZone <" + + System.out.println("DateFormat instance which uses TimeZone <" + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { - errln("Fail: DateFormat serialization/equality bug"); + fail("Fail: DateFormat serialization/equality bug"); } } catch (IOException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } catch (ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } finally { @@ -489,17 +501,18 @@ } } + @Test public void Test4101483() { SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US); FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD); @SuppressWarnings("deprecation") Date d= new Date(9234567890L); StringBuffer buf = new StringBuffer(""); - logln(sdf.format(d, buf, fp).toString()); - logln(d + " => " + buf); - logln("beginIndex = " + fp.getBeginIndex()); - logln("endIndex = " + fp.getEndIndex()); - if (fp.getBeginIndex() == fp.getEndIndex()) errln("Fail: Empty field"); + System.out.println(sdf.format(d, buf, fp).toString()); + System.out.println(d + " => " + buf); + System.out.println("beginIndex = " + fp.getBeginIndex()); + System.out.println("endIndex = " + fp.getEndIndex()); + if (fp.getBeginIndex() == fp.getEndIndex()) fail("Fail: Empty field"); } /** @@ -510,6 +523,7 @@ * NT; it would actually have failed on any non-US locale. Now it should * work on all locales. */ + @Test public void Test4103340() { // choose a date that is the FIRST of some month // and some arbitrary time @@ -519,30 +533,32 @@ String s = d.toString(); String s2 = df.format(d); - logln("Date="+s); - logln("DF="+s2); + System.out.println("Date="+s); + System.out.println("DF="+s2); if (s.indexOf(s2.substring(0,2)) == -1) - errln("Months should match"); + fail("Months should match"); } + @Test public void Test4103341() { TimeZone saveZone =TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("CST")); SimpleDateFormat simple = new SimpleDateFormat("MM/dd/yyyy HH:mm"); if (!simple.getTimeZone().equals(TimeZone.getDefault())) - errln("Fail: SimpleDateFormat not using default zone"); + fail("Fail: SimpleDateFormat not using default zone"); } finally { TimeZone.setDefault(saveZone); } } + @Test public void Test4104136() { SimpleDateFormat sdf = new SimpleDateFormat(); String pattern = "'time' hh:mm"; sdf.applyPattern(pattern); - logln("pattern: \"" + pattern + "\""); + System.out.println("pattern: \"" + pattern + "\""); @SuppressWarnings("deprecation") Object[] DATA = { @@ -557,14 +573,14 @@ ParsePosition pos = new ParsePosition(0); Date d = sdf.parse(text, pos); - logln(" text: \"" + text + "\""); - logln(" index: " + pos.getIndex()); - logln(" result: " + d); + System.out.println(" text: \"" + text + "\""); + System.out.println(" index: " + pos.getIndex()); + System.out.println(" result: " + d); if (pos.getIndex() != finish.getIndex()) - errln("Fail: Expected pos " + finish.getIndex()); + fail("Fail: Expected pos " + finish.getIndex()); if (!((d == null && exp == null) || d.equals(exp))) - errln("Fail: Expected result " + exp); + fail("Fail: Expected result " + exp); } } @@ -574,27 +590,29 @@ * StringIndexOutOfBoundsException during the second parse. However, * this is not seen. */ + @Test public void Test4104522() { SimpleDateFormat sdf = new SimpleDateFormat(); String pattern = "'time' hh:mm"; sdf.applyPattern(pattern); - logln("pattern: \"" + pattern + "\""); + System.out.println("pattern: \"" + pattern + "\""); // works correctly ParsePosition pp = new ParsePosition(0); String text = "time "; Date date = sdf.parse(text, pp); - logln(" text: \"" + text + "\"" + + System.out.println(" text: \"" + text + "\"" + " date: " + date); // works wrong pp = new ParsePosition(0); text = "time"; date = sdf.parse(text, pp); - logln(" text: \"" + text + "\"" + + System.out.println(" text: \"" + text + "\"" + " date: " + date); } + @Test public void Test4106807() { Date date; DateFormat df = DateFormat.getDateTimeInstance(); @@ -618,13 +636,13 @@ try { format.setTimeZone(gmt); date = format.parse(dateString); - logln(df.format(date)); + System.out.println(df.format(date)); gc.setTime(date); - logln("" + gc.get(Calendar.ZONE_OFFSET)); - logln(format.format(date)); + System.out.println("" + gc.get(Calendar.ZONE_OFFSET)); + System.out.println(format.format(date)); } catch (ParseException e) { - logln("No way Jose"); + System.out.println("No way Jose"); } } } @@ -632,12 +650,13 @@ /** * SimpleDateFormat won't parse "GMT" */ + @Test public void Test4134203() { String dateFormat = "MM/dd/yy HH:mm:ss zzz"; SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); ParsePosition p0 = new ParsePosition(0); Date d = fmt.parse("01/22/92 04:52:00 GMT", p0); - logln(d.toString()); + System.out.println(d.toString()); // In the failure case an exception is thrown by parse(); // if no exception is thrown, the test passes. } @@ -645,12 +664,13 @@ /** * Another format for GMT string parse */ + @Test public void Test4266432() { String dateFormat = "MM/dd HH:mm:ss zzz yyyy"; SimpleDateFormat fmt = new SimpleDateFormat(dateFormat); ParsePosition p0 = new ParsePosition(0); Date d = fmt.parse("01/22 04:52:00 GMT 1992", p0); - logln(d.toString()); + System.out.println(d.toString()); // In the failure case an exception is thrown by parse(); // if no exception is thrown, the test passes. } @@ -662,6 +682,7 @@ * NOTE: Updated for fixed semantics as of Kestrel. See * 4253490 */ + @Test public void Test4148168() throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat("", Locale.US); int ms = 456; @@ -677,7 +698,7 @@ fmt.applyPattern(PAT[i]); String str = fmt.format(d); if (!str.equals(OUT[i])) { - errln("FAIL: " + ms + " ms x \"" + PAT[i] + "\" -> \"" + + fail("FAIL: " + ms + " ms x \"" + PAT[i] + "\" -> \"" + str + "\", exp \"" + OUT[i] + '"'); } } @@ -692,7 +713,7 @@ cal.setTime(d); ms = cal.get(Calendar.MILLISECOND); if (ms != MS[i]) { - errln("FAIL: parse(\"" + IN[i] + "\" x \"s.S\") -> " + + fail("FAIL: parse(\"" + IN[i] + "\" x \"s.S\") -> " + ms + " ms, exp " + MS[i] + " ms"); } } @@ -701,17 +722,18 @@ /** * SimpleDateFormat incorrect handling of 2 single quotes in format() */ + @Test public void Test4151631() { String pattern = "'TO_DATE('''dd'-'MM'-'yyyy HH:mm:ss''' , ''DD-MM-YYYY HH:MI:SS'')'"; - logln("pattern=" + pattern); + System.out.println("pattern=" + pattern); SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US); @SuppressWarnings("deprecation") String result = format.format(new Date(1998-1900, Calendar.JUNE, 30, 13, 30, 0)); if (!result.equals("TO_DATE('30-06-1998 13:30:00' , 'DD-MM-YYYY HH:MI:SS')")) { - errln("Fail: result=" + result); + fail("Fail: result=" + result); } else { - logln("Pass: result=" + result); + System.out.println("Pass: result=" + result); } } @@ -720,15 +742,16 @@ * CANNOT REPRODUCE THIS BUG ON 1.2FCS */ @SuppressWarnings("deprecation") + @Test public void Test4151706() { SimpleDateFormat fmt = new SimpleDateFormat("EEEE, dd-MMM-yy HH:mm:ss z", Locale.US); try { Date d = fmt.parse("Thursday, 31-Dec-98 23:00:00 GMT"); if (d.getTime() != Date.UTC(1998-1900, Calendar.DECEMBER, 31, 23, 0, 0)) - errln("Incorrect value: " + d); + fail("Incorrect value: " + d); } catch (Exception e) { - errln("Fail: " + e); + fail("Fail: " + e); } } @@ -737,6 +760,7 @@ * This is actually a bug down in GregorianCalendar, but it was reported * as follows... */ + @Test public void Test4153860() throws ParseException { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -751,7 +775,7 @@ // Try to create a Date for February 4th Date d2 = sf.parse("1998.02-04 1"); if (!d1.equals(d2)) { - errln("Parse failed, got " + d2 + + fail("Parse failed, got " + d2 + ", expected " + d1); } } @@ -765,6 +789,7 @@ * as "EST" or "CST", not Australian "EST" and "CST". */ @SuppressWarnings("deprecation") + @Test public void Test4406615() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -784,13 +809,13 @@ d1.getDate() != 31 || d1.getHours() != 21 || d1.getMinutes() != 0 || d2.getYear() != (2000-1900) || d2.getMonth() != 11 || d2.getDate() != 31 || d2.getHours() != 22 || d2.getMinutes() != 0) { - errln("Parse failed, d1 = " + d1 + ", d2 = " + d2); + fail("Parse failed, d1 = " + d1 + ", d2 = " + d2); } else { - logln("Parse passed"); + System.out.println("Parse passed"); } } catch (Exception e) { - errln("Parse failed, got Exception " + e); + fail("Parse failed, got Exception " + e); } finally { Locale.setDefault(savedLocale); @@ -802,6 +827,7 @@ * Cannot reproduce this bug under 1.2 FCS -- it may be a convoluted duplicate * of some other bug that has been fixed. */ + @Test public void Test4162071() { String dateString = "Thu, 30-Jul-1999 11:51:14 GMT"; String format = "EEE', 'dd-MMM-yyyy HH:mm:ss z"; // RFC 822/1123 @@ -810,16 +836,17 @@ try { Date x = df.parse(dateString); - logln("Parse format \"" + format + "\" ok"); - logln(dateString + " -> " + df.format(x)); + System.out.println("Parse format \"" + format + "\" ok"); + System.out.println(dateString + " -> " + df.format(x)); } catch (Exception e) { - errln("Parse format \"" + format + "\" failed."); + fail("Parse format \"" + format + "\" failed."); } } /** * DateFormat shouldn't parse year "-1" as a two-digit year (e.g., "-1" -> 1999). */ + @Test public void Test4182066() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -869,9 +896,9 @@ } } if (pass) { - log(out.toString()); + System.out.println(out.toString()); } else { - err(out.toString()); + fail(out.toString()); } } finally { @@ -884,6 +911,7 @@ * Bug 4209272 * DateFormat cannot parse Feb 29 2000 when setLenient(false) */ + @Test public void Test4210209() { String pattern = "MMM d, yyyy"; DateFormat fmt = new SimpleDateFormat(pattern, @@ -892,13 +920,13 @@ @SuppressWarnings("deprecation") Date d = new Date(2000-1900, Calendar.FEBRUARY, 29); String s = fmt.format(d); - logln(d + " x " + pattern + " => " + s); + System.out.println(d + " x " + pattern + " => " + s); ParsePosition pos = new ParsePosition(0); d = fmt.parse(s, pos); - logln(d + " <= " + pattern + " x " + s); - logln("Parse pos = " + pos); + System.out.println(d + " <= " + pattern + " x " + s); + System.out.println("Parse pos = " + pos); if (pos.getErrorIndex() != -1) { - errln("FAIL"); + fail("FAIL"); } // The underlying bug is in GregorianCalendar. If the following lines @@ -908,12 +936,13 @@ cal.clear(); cal.setLenient(false); cal.set(2000, Calendar.FEBRUARY, 29); // This should work! - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); } /** * DateFormat.getDateTimeInstance() allows illegal parameters. */ + @Test public void Test4213086() { int[] DATA = { // Style value, 0/1 for illegal/legal @@ -962,7 +991,7 @@ e = ex; } if (got != DATA[i+1] || e != null) { - errln("FAIL: DateFormat." + DESC[j] + " style " + DATA[i] + " " + + fail("FAIL: DateFormat." + DESC[j] + " style " + DATA[i] + " " + (e != null ? e.toString() : GOT[got])); } } @@ -970,6 +999,7 @@ } @SuppressWarnings("deprecation") + @Test public void Test4253490() throws ParseException { SimpleDateFormat fmt = new SimpleDateFormat("S", Locale.US); @@ -993,10 +1023,10 @@ fmt.applyPattern(FORMAT_PAT[i]); String s = fmt.format(d); if (s.equals(FORMAT_TO[i])) { - logln(String.valueOf(FORMAT_MS) + " ms f* \"" + + System.out.println(String.valueOf(FORMAT_MS) + " ms f* \"" + FORMAT_PAT[i] + "\" -> \"" + s + '"'); } else { - errln("FAIL: " + FORMAT_MS + " ms f* \"" + + fail("FAIL: " + FORMAT_MS + " ms f* \"" + FORMAT_PAT[i] + "\" -> \"" + s + "\", expect \"" + FORMAT_TO[i] + '"'); } @@ -1008,10 +1038,10 @@ cal.setTime(fmt.parse(PARSE_STR[i])); int ms = cal.get(Calendar.MILLISECOND); if (ms == PARSE_TO[i]) { - logln("\"" + PARSE_STR[i] + "\" p* \"" + + System.out.println("\"" + PARSE_STR[i] + "\" p* \"" + PARSE_PAT + "\" -> " + ms + " ms"); } else { - errln("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + + fail("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + PARSE_PAT + "\" -> " + ms + " ms, expect " + PARSE_TO[i] + " ms"); } @@ -1023,10 +1053,10 @@ cal.setTime(fmt.parse(PARSE_STR[i])); int ms = cal.get(Calendar.MILLISECOND); if (ms == PARSE_TO[i]) { - logln("\"" + PARSE_STR[i] + "\" p* \"" + + System.out.println("\"" + PARSE_STR[i] + "\" p* \"" + PARSE_LPAT + "\" -> " + ms + " ms"); } else { - errln("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + + fail("FAIL: \"" + PARSE_STR[i] + "\" p* \"" + PARSE_LPAT + "\" -> " + ms + " ms, expect " + PARSE_TO[i] + " ms"); } @@ -1036,6 +1066,7 @@ /** * Bug in handling of time instance; introduces in fix for 4213086. */ + @Test public void Test4250359() { DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US); @@ -1048,7 +1079,7 @@ int i = s.indexOf("AM"); int j = s.indexOf("AM", i+1); if (i < 0 || j >= 0) { - errln("FAIL: getTimeInstance().format(d) => \"" + + fail("FAIL: getTimeInstance().format(d) => \"" + s + "\""); } } @@ -1057,6 +1088,7 @@ * Test whether SimpleDataFormat (DateFormatSymbols) can format/parse * non-localized time zones. */ + @Test public void Test4261506() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -1068,22 +1100,22 @@ SimpleDateFormat fmt = new SimpleDateFormat("yy/MM/dd hh:ss zzz", Locale.JAPAN); @SuppressWarnings("deprecation") String result = fmt.format(new Date(1999 - 1900, 0, 1)); - logln("format()=>" + result); + System.out.println("format()=>" + result); if (!result.endsWith("PST")) { - errln("FAIL: SimpleDataFormat.format() did not retrun PST"); + fail("FAIL: SimpleDataFormat.format() did not retrun PST"); } Date d = null; try { d = fmt.parse("99/1/1 10:10 PST"); } catch (ParseException e) { - errln("FAIL: SimpleDataFormat.parse() could not parse PST"); + fail("FAIL: SimpleDataFormat.parse() could not parse PST"); } result = fmt.format(d); - logln("roundtrip:" + result); + System.out.println("roundtrip:" + result); if (!result.equals("99/01/01 10:10 PST")) { - errln("FAIL: SimpleDataFomat timezone roundtrip failed"); + fail("FAIL: SimpleDataFomat timezone roundtrip failed"); } Locale.setDefault(savedLocale); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatRoundTripTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,14 +25,24 @@ * @test * @summary test Date Format (Round Trip) * @bug 8008577 - * @library /java/text/testlib * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatRoundTripTest */ -import java.text.*; -import java.util.*; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Locale; +import java.util.Random; +import java.util.SimpleTimeZone; +import java.util.TimeZone; -public class DateFormatRoundTripTest extends IntlTest { +public class DateFormatRoundTripTest { static Random RANDOM = null; @@ -107,15 +117,15 @@ List newArgs = new ArrayList<>(); for (int i=0; i Random using as seed."); - super.usage(); } static private class TestCase { @@ -310,8 +320,8 @@ public void TestDateFormatRoundTrip() { avail = DateFormat.getAvailableLocales(); - logln("DateFormat available locales: " + avail.length); - logln("Default TimeZone: " + + System.out.println("DateFormat available locales: " + avail.length); + System.out.println("Default TimeZone: " + (defaultZone = TimeZone.getDefault()).getID()); if (random || initialDate != null) { @@ -333,7 +343,7 @@ * TimeZone must be set to tc.zone before this method is called. */ private void doTestInZone(TestCase tc) { - logln(escape(tc.toString())); + System.out.println(escape(tc.toString())); Locale save = Locale.getDefault(); try { if (locale != null) { @@ -368,10 +378,10 @@ if (INFINITE) { // Special infinite loop test mode for finding hard to reproduce errors if (locale != null) { - logln("ENTERING INFINITE TEST LOOP, LOCALE " + locale.getDisplayName()); + System.out.println("ENTERING INFINITE TEST LOOP, LOCALE " + locale.getDisplayName()); for (;;) doTest(locale); } else { - logln("ENTERING INFINITE TEST LOOP, ALL LOCALES"); + System.out.println("ENTERING INFINITE TEST LOOP, ALL LOCALES"); for (;;) { for (int i=0; i0&&d[j].getTime()==d[j-1].getTime()?" d==":"") + (j>0&&s[j].equals(s[j-1])?" s==":"")); } - errln(escape(out.toString())); + throw new RuntimeException(escape(out.toString())); } } } catch (ParseException e) { - errln(e.toString()); + throw new RuntimeException(e.toString()); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/DateFormatTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/DateFormatTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,30 +26,31 @@ * @bug 4052223 4089987 4469904 4326988 4486735 8008577 8045998 8140571 * 8190748 8216969 * @summary test DateFormat and SimpleDateFormat. - * @library /java/text/testlib * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT,SPI DateFormatTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI DateFormatTest */ import java.util.*; import java.text.*; import static java.util.GregorianCalendar.*; -public class DateFormatTest extends IntlTest +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; + +import static org.junit.jupiter.api.Assertions.fail; + +public class DateFormatTest { - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - new DateFormatTest().run(args); - } finally { - // restore the reserved locale - Locale.setDefault(reservedLocale); - } + + // Change JVM default Locale + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); } // Test 4 digit year parsing with pattern "yy" @SuppressWarnings("deprecation") + @Test public void TestYearParsing() { String str = "7/Sep/2001"; @@ -58,17 +59,18 @@ SimpleDateFormat sdf = new SimpleDateFormat(pat, Locale.US); try { Date d = sdf.parse(str); - logln(str + " parses with " + pat + " to " + d); + System.out.println(str + " parses with " + pat + " to " + d); if (d.getTime() != exp.getTime()) { - errln("FAIL: Expected " + exp); + fail("FAIL: Expected " + exp); } } catch (ParseException e) { - errln(str + " parse fails with " + pat); + fail(str + " parse fails with " + pat); } } // Test written by Wally Wedel and emailed to me. + @Test public void TestWallyWedel() { /* @@ -91,11 +93,11 @@ /* * How many ids do we have? */ - logln("Time Zone IDs size: " + ids.length); + System.out.println("Time Zone IDs size: " + ids.length); /* * Column headings (sort of) */ - logln("Ordinal ID offset(h:m) name"); + System.out.println("Ordinal ID offset(h:m) name"); /* * Loop through the tzs. */ @@ -136,19 +138,20 @@ boolean ok = fmtDstOffset == null || fmtDstOffset.equals(dstOffset); if (ok) { - logln(i + " " + ids[i] + " " + dstOffset + + System.out.println(i + " " + ids[i] + " " + dstOffset + " " + fmtOffset + (fmtDstOffset != null ? " ok" : " ?")); } else { - errln(i + " " + ids[i] + " " + dstOffset + + fail(i + " " + ids[i] + " " + dstOffset + " " + fmtOffset + " *** FAIL ***"); } } } // Test equals + @Test public void TestEquals() { DateFormat fmtA = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); @@ -156,12 +159,13 @@ DateFormat fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.FULL); if (!fmtA.equals(fmtB)) { - errln("FAIL"); + fail("FAIL"); } } // Check out some specific parsing problem @SuppressWarnings("deprecation") + @Test public void TestTwoDigitYearDSTParse() { SimpleDateFormat fullFmt = @@ -181,12 +185,12 @@ try { TimeZone.setDefault(PST); Date d = fmt.parse(s); - logln(s + " P> " + fullFmt.format(d)); + System.out.println(s + " P> " + fullFmt.format(d)); if (d.getHours() != hour) { - errln("FAIL: Should parse to hour " + hour); + fail("FAIL: Should parse to hour " + hour); } } - catch (ParseException e) { errln("FAIL: " + e.getMessage()); } + catch (ParseException e) { fail("FAIL: " + e.getMessage()); } finally { TimeZone.setDefault(save); } @@ -234,6 +238,7 @@ /** * Bug 4089987 */ + @Test public void TestFieldPosition() { DateFormat[] dateFormats = { @@ -273,13 +278,13 @@ continue; } df.setTimeZone(PST); - logln(" Pattern = " + ((SimpleDateFormat)df).toPattern()); - logln(" Result = " + df.format(someDate)); + System.out.println(" Pattern = " + ((SimpleDateFormat)df).toPattern()); + System.out.println(" Result = " + df.format(someDate)); for (int i = 0; i < fieldIDs.length; ++i) { String field = getFieldText(df, fieldIDs[i], someDate); if (!field.equals(expected[exp])) { - errln("FAIL: field #" + i + " " + fieldNames[i] + " = \"" + + fail("FAIL: field #" + i + " " + fieldNames[i] + " = \"" + escape(field) + "\", expected \"" + escape(expected[exp]) + "\""); } ++exp; @@ -298,6 +303,7 @@ // Test parsing of partial strings @SuppressWarnings("deprecation") + @Test public void TestPartialParse994() { SimpleDateFormat f = new SimpleDateFormat(); @@ -312,34 +318,35 @@ void tryPat994(SimpleDateFormat format, String pat, String str, Date expected) { - logln("Pattern \"" + pat + "\" String \"" + str + "\""); + System.out.println("Pattern \"" + pat + "\" String \"" + str + "\""); try { format.applyPattern(pat); Date date = format.parse(str); String f = format.format(date); - logln(" parse(" + str + ") -> " + date.toString()); - logln(" format -> " + f); + System.out.println(" parse(" + str + ") -> " + date.toString()); + System.out.println(" format -> " + f); if (expected == null || !date.equals(expected)) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } if (!f.equals(str)) { - errln("FAIL: Expected " + str); + fail("FAIL: Expected " + str); } } catch(ParseException e) { - logln("ParseException: " + e.getMessage()); + System.out.println("ParseException: " + e.getMessage()); if (expected != null) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch(Exception e) { - errln("*** Exception:"); + fail("*** Exception:"); e.printStackTrace(); } } // Test pattern with runs things together + @Test public void TestRunTogetherPattern985() { String format = "yyyyMMddHHmmssSSSzzzz"; @@ -350,7 +357,7 @@ Date date1 = new Date(); now = formatter.format(date1); - logln(now); + System.out.println(now); ParsePosition pos = new ParsePosition(0); @@ -361,15 +368,16 @@ then = formatter.format(date2); } - logln(then); + System.out.println(then); if (!date2.equals(date1)) { - errln("FAIL"); + fail("FAIL"); } } // Test patterns which run numbers together @SuppressWarnings("deprecation") + @Test public void TestRunTogetherPattern917() { SimpleDateFormat fmt; @@ -386,7 +394,7 @@ } void _testIt917( SimpleDateFormat fmt, String str, Date expected ) { - logln( "pattern=" + fmt.toPattern() + " string=" + str ); + System.out.println( "pattern=" + fmt.toPattern() + " string=" + str ); Object o; try { @@ -395,27 +403,28 @@ e.printStackTrace(); return; } - logln( "Parsed object: " + o ); + System.out.println( "Parsed object: " + o ); if (!o.equals(expected)) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } String formatted = fmt.format( o ); - logln( "Formatted string: " + formatted ); + System.out.println( "Formatted string: " + formatted ); if (!formatted.equals(str)) { - errln("FAIL: Expected " + str); + fail("FAIL: Expected " + str); } } // Test Czech month formatting -- this can cause a problem because the June and // July month names share a common prefix. @SuppressWarnings("deprecation") + @Test public void TestCzechMonths459() { // Use Czech, which has month names with shared prefixes for June and July DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, new Locale("cs", "", "")); //((SimpleDateFormat)fmt).applyPattern("MMMM d yyyy"); - logln("Pattern " + ((SimpleDateFormat)fmt).toPattern()); + System.out.println("Pattern " + ((SimpleDateFormat)fmt).toPattern()); Date june = new Date(97, Calendar.JUNE, 15); Date july = new Date(97, Calendar.JULY, 15); @@ -424,31 +433,32 @@ String julyStr = fmt.format(july); try { - logln("format(June 15 1997) = " + juneStr); + System.out.println("format(June 15 1997) = " + juneStr); Date d = fmt.parse(juneStr); String s = fmt.format(d); int month = d.getMonth(); - logln(" -> parse -> " + s + " (month = " + month + ")"); + System.out.println(" -> parse -> " + s + " (month = " + month + ")"); if (month != JUNE) { - errln("FAIL: Month should be June"); + fail("FAIL: Month should be June"); } - logln("format(July 15 1997) = " + julyStr); + System.out.println("format(July 15 1997) = " + julyStr); d = fmt.parse(julyStr); s = fmt.format(d); month = d.getMonth(); - logln(" -> parse -> " + s + " (month = " + month + ")"); + System.out.println(" -> parse -> " + s + " (month = " + month + ")"); if (month != JULY) { - errln("FAIL: Month should be July"); + fail("FAIL: Month should be July"); } } catch (ParseException e) { - errln("Exception: " + e); + fail("Exception: " + e); } } // Test big D (day of year) versus little d (day of month) @SuppressWarnings("deprecation") + @Test public void TestLetterDPattern212() { String dateString = "1995-040.05:01:29"; @@ -457,32 +467,33 @@ Date expLittleD = new Date(95, 0, 1, 5, 1, 29); Date expBigD = new Date(expLittleD.getTime() + 39*24*3600000L); // 39 days expLittleD = expBigD; // Expect the same, with default lenient parsing - logln( "dateString= " + dateString ); + System.out.println( "dateString= " + dateString ); SimpleDateFormat formatter = new SimpleDateFormat(bigD); ParsePosition pos = new ParsePosition(0); Date myDate = formatter.parse( dateString, pos ); - logln("Using " + bigD + " -> " + myDate); + System.out.println("Using " + bigD + " -> " + myDate); if (myDate.getTime() != expBigD.getTime()) { - errln("FAIL: Expected " + expBigD + " got " + myDate); + fail("FAIL: Expected " + expBigD + " got " + myDate); } formatter = new SimpleDateFormat(littleD); pos = new ParsePosition(0); myDate = formatter.parse( dateString, pos ); - logln("Using " + littleD + " -> " + myDate); + System.out.println("Using " + littleD + " -> " + myDate); if (myDate.getTime() != expLittleD.getTime()) { - errln("FAIL: Expected " + expLittleD + " got " + myDate); + fail("FAIL: Expected " + expLittleD + " got " + myDate); } } // Test the 'G' day of year pattern @SuppressWarnings("deprecation") + @Test public void TestDayOfYearPattern195() { Date today = new Date(); Date expected = new Date(today.getYear(), today.getMonth(), today.getDate()); - logln("Test Date: " + today); + System.out.println("Test Date: " + today); SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateInstance(); @@ -496,29 +507,30 @@ if (pattern != null) { sdf.applyPattern(pattern); } - logln("pattern: " + sdf.toPattern()); + System.out.println("pattern: " + sdf.toPattern()); String formatResult = sdf.format(d); - logln(" format -> " + formatResult); + System.out.println(" format -> " + formatResult); try { Date d2 = sdf.parse(formatResult); - logln(" parse(" + formatResult + ") -> " + d2); + System.out.println(" parse(" + formatResult + ") -> " + d2); if (d2.getTime() != expected.getTime()) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } String format2 = sdf.format(d2); - logln(" format -> " + format2); + System.out.println(" format -> " + format2); if (!formatResult.equals(format2)) { - errln("FAIL: Round trip drift"); + fail("FAIL: Round trip drift"); } } catch(Exception e) { - errln("Error: " + e.getMessage()); + fail("Error: " + e.getMessage()); } } // Test a pattern with single quotes @SuppressWarnings("deprecation") + @Test public void TestQuotePattern161() { // This pattern used to end in " zzz" but that makes this test zone-dependent @@ -526,9 +538,9 @@ Date currentTime_1 = new Date(97, Calendar.AUGUST, 13, 10, 42, 28); String dateString = formatter.format(currentTime_1); String exp = "08/13/1997 at 10:42:28 AM "; - logln("format(" + currentTime_1 + ") = " + dateString); + System.out.println("format(" + currentTime_1 + ") = " + dateString); if (!dateString.regionMatches(0, exp, 0, exp.length())) { - errln("FAIL: Expected " + exp); + fail("FAIL: Expected " + exp); } } @@ -540,6 +552,7 @@ * 1 line that should be correct is off by 100 years. (In this day * and age, no one would assume that 1/1/00 is Jan 1 1900.) **/ + @Test public void TestBadInput135() { int looks[] = { DateFormat.SHORT, DateFormat.MEDIUM, @@ -560,22 +573,22 @@ try { Date when = df.parse(text); if ( when == null ){ - errln(prefix + + fail(prefix + "SHOULD NOT HAPPEN: parse returned null."); continue; } String format = full.format(when); - logln(prefix + "OK: " + format); + System.out.println(prefix + "OK: " + format); // Only match the start -- not the zone, which could vary if (!format.regionMatches(0, expected, 0, expected.length())) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch ( ParseException e ){ //errln(prefix + e); // This is expected. } catch ( StringIndexOutOfBoundsException e ){ - errln(prefix + "SHOULD NOT HAPPEN: " + e); + fail(prefix + "SHOULD NOT HAPPEN: " + e); } } } @@ -610,6 +623,7 @@ }; // More testing of the parsing of bad input @SuppressWarnings("UnusedAssignment") + @Test public void TestBadInput135a() { SimpleDateFormat dateParse = new SimpleDateFormat(); @@ -620,12 +634,12 @@ dateParse.applyPattern("d MMMM, yyyy"); dateParse.setTimeZone(TimeZone.getDefault()); s = "not parseable"; - logln("Trying to parse \"" + s + "\" with " + dateParse.toPattern()); + System.out.println("Trying to parse \"" + s + "\" with " + dateParse.toPattern()); try { date = dateParse.parse(s); - errln("FAIL: Expected exception during parse"); + fail("FAIL: Expected exception during parse"); } catch (Exception ex) { - logln("Exception during parse: " + ex); // This is expected + System.out.println("Exception during parse: " + ex); // This is expected } for (int i=0; i " + d.toString()); if (d.getTime() != expected.getTime()) { - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); } } catch (ParseException e) { - errln("FAIL: Got exception"); + fail("FAIL: Got exception"); } } // Test behavior of DateFormat with applied time zone + @Test public void TestDateFormatZone061() { Date date; @@ -732,28 +748,29 @@ // 25-Mar-97 00:00:00 GMT date = new Date( 859248000000L ); - logln( "Date 1997/3/25 00:00 GMT: " + date ); + System.out.println( "Date 1997/3/25 00:00 GMT: " + date ); formatter = new SimpleDateFormat("dd-MMM-yyyyy HH:mm", Locale.UK); formatter.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); String temp = formatter.format( date ); - logln( "Formatted in GMT to: " + temp ); + System.out.println( "Formatted in GMT to: " + temp ); /* Parse date string */ try { Date tempDate = formatter.parse( temp ); - logln( "Parsed to: " + tempDate ); + System.out.println( "Parsed to: " + tempDate ); if (tempDate.getTime() != date.getTime()) { - errln("FAIL: Expected " + date); + fail("FAIL: Expected " + date); } } catch( Throwable t ) { - errln( "Date Formatter throws: " + + fail( "Date Formatter throws: " + t.toString() ); } } // Make sure DateFormat uses the correct zone. + @Test public void TestDateFormatZone146() { TimeZone saveDefault = TimeZone.getDefault(); @@ -767,9 +784,9 @@ TimeZone testdefault = TimeZone.getDefault(); String testtimezone = testdefault.getID(); if (testtimezone.equals("GMT")) { - logln("Test timezone = " + testtimezone); + System.out.println("Test timezone = " + testtimezone); } else { - errln("Test timezone should be GMT, not " + testtimezone); + fail("Test timezone should be GMT, not " + testtimezone); } // now try to use the default GMT time zone @@ -799,9 +816,9 @@ DateFormat fmt = new SimpleDateFormat(DATA[i+2], Locale.ENGLISH); fmt.setCalendar(greenwichcalendar); String result = fmt.format(greenwichdate); - logln(DATA[i] + result); + System.out.println(DATA[i] + result); if (!result.equals(DATA[i+1])) { - errln("FAIL: Expected " + DATA[i+1] + fail("FAIL: Expected " + DATA[i+1] + ", got " + result); } } @@ -812,6 +829,7 @@ } /* HS : Commented out for now, need to be changed not to use hardcoded results. + @Test public void TestLocaleDateFormat() // Bug 495 { Date testDate = new Date (97, Calendar.SEPTEMBER, 15); @@ -821,13 +839,13 @@ DateFormat.FULL, Locale.US); String expectedFRENCH = "lundi 15 septembre 1997 00 h 00 GMT-07:00"; String expectedUS = "Monday, September 15, 1997 12:00:00 o'clock AM PDT"; - logln("Date set to : " + testDate); + System.out.println("Date set to : " + testDate); String out = dfFrench.format(testDate); - logln("Date Formated with French Locale " + out); - if (!out.equals(expectedFRENCH)) errln("FAIL: Expected " + expectedFRENCH); + System.out.println("Date Formated with French Locale " + out); + if (!out.equals(expectedFRENCH)) fail("FAIL: Expected " + expectedFRENCH); out = dfUS.format(testDate); - logln("Date Formated with US Locale " + out); - if (!out.equals(expectedUS)) errln("FAIL: Expected " + expectedUS); + System.out.println("Date Formated with US Locale " + out); + if (!out.equals(expectedUS)) fail("FAIL: Expected " + expectedUS); } */ /** @@ -835,13 +853,14 @@ */ /* test commented out pending API-change approval + @Test public void Test2YearStartDate() throws ParseException { // create a SimpleDateFormat to test with; dump out if it's not a SimpleDateFormat DateFormat test = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); if (!(test instanceof SimpleDateFormat)) { - errln("DateFormat.getInstance() didn't return an instance of SimpleDateFormat!"); + fail("DateFormat.getInstance() didn't return an instance of SimpleDateFormat!"); return; } @@ -861,7 +880,7 @@ cal.setTime(date); if (cal.get(Calendar.YEAR) != 1900 || cal.get(Calendar.MONTH) != 0 || cal.get(Calendar.DATE) != 1) - errln("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + fail("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) + " instead of 1/1/1900."); @@ -869,19 +888,19 @@ date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1967) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1967."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1900 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1900 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -891,19 +910,19 @@ date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2067) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 2067."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/2000 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/2000 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -913,19 +932,19 @@ date = sdf.parse(testString1); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1967) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 yielded a year of " + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1967."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 10) - errln("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 failed: got " + + fail("Parsing \"3/10/67\" with 2-digit start date set to 1/1/1950 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/10."); date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 1/1/1950 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); @@ -935,19 +954,19 @@ date = sdf.parse(testString2); cal.setTime(date); if (cal.get(Calendar.YEAR) != 2043) - errln("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + fail("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 2043."); if (cal.get(Calendar.MONTH) != 2 || cal.get(Calendar.DATE) != 16) - errln("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 failed: got " + + fail("Parsing \"3/16/43\" with 2-digit start date set to 6/1/1943 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 3/16."); date = sdf.parse(testString3); cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943) - errln("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + fail("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 yielded a year of " + cal.get(Calendar.YEAR) + " instead of 1943."); if (cal.get(Calendar.MONTH) != 6 || cal.get(Calendar.DATE) != 21) - errln("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 failed: got " + + fail("Parsing \"7/21/43\" with 2-digit start date set to 6/1/1943 failed: got " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + " instead of 7/21."); @@ -957,7 +976,7 @@ cal.setTime(date); if (cal.get(Calendar.YEAR) != 1943 || cal.get(Calendar.MONTH) != 5 || cal.get(Calendar.DATE) != 1) - errln("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + fail("SimpleDateFormat.get2DigitStartDate() returned " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DATE) + "/" + cal.get(Calendar.YEAR) + " instead of 6/1/1943."); } @@ -967,6 +986,7 @@ * ParsePosition.errorIndex tests. */ @SuppressWarnings("deprecation") + @Test public void Test4052223() { String str = "7/SOS/2001"; @@ -975,17 +995,18 @@ SimpleDateFormat sdf = new SimpleDateFormat(pat); ParsePosition pos = new ParsePosition(0); Date d = sdf.parse(str, pos); - logln(str + " parses with " + pat + " to " + d); + System.out.println(str + " parses with " + pat + " to " + d); if (d == null && pos.getErrorIndex() == 2) { - logln("Expected null returned, failed at : " + pos.getErrorIndex()); + System.out.println("Expected null returned, failed at : " + pos.getErrorIndex()); } else { - errln("Failed, parse " + str + " got : " + d + ", index=" + pos.getErrorIndex()); + fail("Failed, parse " + str + " got : " + d + ", index=" + pos.getErrorIndex()); } } /** * Bug4469904 -- th_TH date format doesn't use Thai B.E. */ + @Test public void TestBuddhistEraBugId4469904() { String era = "\u0e1e.\u0e28."; Locale loc = new Locale("th", "TH"); @@ -996,7 +1017,7 @@ String output = df.format(date); int index = output.indexOf(era); if (index == -1) { - errln("Test4469904: Failed. Buddhist Era abbrev not present."); + fail("Test4469904: Failed. Buddhist Era abbrev not present."); } } @@ -1004,6 +1025,7 @@ * 4326988: API: SimpleDateFormat throws NullPointerException when parsing with null pattern */ @SuppressWarnings("UnusedAssignment") + @Test public void Test4326988() { String[] wrongPatterns = { "hh o''clock", @@ -1021,28 +1043,28 @@ // Check NullPointerException try { SimpleDateFormat fmt = new SimpleDateFormat(null); - errln("SimpleDateFormat() doesn't throw NPE with null pattern"); + fail("SimpleDateFormat() doesn't throw NPE with null pattern"); } catch (NullPointerException e) { // Okay } try { Locale loc = null; SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd", loc); - errln("SimpleDateFormat() doesn't throw NPE with null locale"); + fail("SimpleDateFormat() doesn't throw NPE with null locale"); } catch (NullPointerException e) { // Okay } try { DateFormatSymbols symbols = null; SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd", symbols); - errln("SimpleDateFormat() doesn't throw NPE with null DateFormatSymbols"); + fail("SimpleDateFormat() doesn't throw NPE with null DateFormatSymbols"); } catch (NullPointerException e) { // Okay } try { SimpleDateFormat fmt = new SimpleDateFormat(); fmt.applyPattern(null); - errln("applyPattern() doesn't throw NPE with null pattern"); + fail("applyPattern() doesn't throw NPE with null pattern"); } catch (NullPointerException e) { // Okay } @@ -1051,7 +1073,7 @@ for (int i = 0; i < wrongPatterns.length; i++) { try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i]); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + "\")" + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\")" + " doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1059,7 +1081,7 @@ try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i], DateFormatSymbols.getInstance()); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + "\", DateFormatSymbols) doesn't " + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\", DateFormatSymbols) doesn't " + "throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1067,7 +1089,7 @@ try { SimpleDateFormat fmt = new SimpleDateFormat(wrongPatterns[i], Locale.US); - errln("SimpleDateFormat(\"" + wrongPatterns[i] + + fail("SimpleDateFormat(\"" + wrongPatterns[i] + "\", Locale) doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1075,7 +1097,7 @@ try { SimpleDateFormat fmt = new SimpleDateFormat(); fmt.applyPattern(wrongPatterns[i]); - errln("SimpleDateFormat.applyPattern(\"" + wrongPatterns[i] + + fail("SimpleDateFormat.applyPattern(\"" + wrongPatterns[i] + "\") doesn't throw an IllegalArgumentException"); } catch (IllegalArgumentException e) { // Okay @@ -1100,6 +1122,7 @@ * Another round trip test */ @SuppressWarnings("deprecation") + @Test public void Test4486735() throws Exception { TimeZone initialTimeZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); @@ -1109,7 +1132,7 @@ // Round to minutes. Some FULL formats don't have seconds. long time = System.currentTimeMillis()/60000 * 60000; Date date = new Date(time); - logln("the test date: " + date); + System.out.println("the test date: " + date); try { for (int z = 0; z < zones.length; z++) { @@ -1120,7 +1143,7 @@ DateFormat.FULL, loc); String s = df.format(date); - logln(s); + System.out.println(s); Date parsedDate = df.parse(s); long parsedTime = parsedDate.getTime(); if (time != parsedTime) { @@ -1133,7 +1156,7 @@ continue; } } - errln("round trip conversion failed: timezone="+zones[z]+ + fail("round trip conversion failed: timezone="+zones[z]+ ", locale=" + loc + ", expected=" + time + ", got=" + parsedTime); } @@ -1191,13 +1214,13 @@ SimpleDateFormat sdf = new SimpleDateFormat(pat); String s = sdf.format(new Date(2001-1900, Calendar.JANUARY, 1)); if (!expected.equals(s)) { - errln("wrong format result: expected="+expected+", got="+s); + fail("wrong format result: expected="+expected+", got="+s); } Date longday = sdf.parse(s); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(longday); if (cal.get(YEAR) != 2001) { - errln("wrong parse result: expected=2001, got=" + cal.get(YEAR)); + fail("wrong parse result: expected=2001, got=" + cal.get(YEAR)); } } catch (Exception e) { throw e; @@ -1207,6 +1230,7 @@ } } + @Test public void Test8216969() throws Exception { Locale locale = new Locale("ru"); String format = "\u0434\u0435\u043a"; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/DateFormat/IntlTestDateFormat.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,7 @@ * @test * @summary test International Date Format * @bug 8008577 - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI IntlTestDateFormat + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI IntlTestDateFormat * @key randomness */ /* @@ -44,7 +43,11 @@ import java.text.*; import java.util.*; -public class IntlTestDateFormat extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestDateFormat { // Values in milliseconds (== Date) private static final long ONESECOND = 1000; private static final long ONEMINUTE = 60 * ONESECOND; @@ -62,10 +65,7 @@ private String fTestName = new String("getInstance"); private int fLimit = 3; // How many iterations it should take to reach convergence - public static void main(String[] args) throws Exception { - new IntlTestDateFormat().run(args); - } - + @Test public void TestLocale() { localeTest(Locale.getDefault(), "Default Locale"); } @@ -85,7 +85,7 @@ fFormat = DateFormat.getTimeInstance(timeStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest time getTimeInstance exception"); + fail("FAIL: localeTest time getTimeInstance exception"); throw e; } TestFormat(); @@ -99,7 +99,7 @@ fFormat = DateFormat.getDateInstance(dateStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest date getTimeInstance exception"); + fail("FAIL: localeTest date getTimeInstance exception"); throw e; } TestFormat(); @@ -112,7 +112,7 @@ fFormat = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } catch(StringIndexOutOfBoundsException e) { - errln("FAIL: localeTest date/time getDateTimeInstance exception"); + fail("FAIL: localeTest date/time getDateTimeInstance exception"); throw e; } TestFormat(); @@ -120,9 +120,10 @@ } } + @Test public void TestFormat() { if (fFormat == null) { - errln("FAIL: DateFormat creation failed"); + fail("FAIL: DateFormat creation failed"); return; } // logln("TestFormat: " + fTestName); @@ -142,13 +143,13 @@ private void describeTest() { if (fFormat == null) { - errln("FAIL: no DateFormat"); + fail("FAIL: no DateFormat"); return; } // Assume it's a SimpleDateFormat and get some info SimpleDateFormat s = (SimpleDateFormat) fFormat; - logln(fTestName + " Pattern " + s.toPattern()); + System.out.println(fTestName + " Pattern " + s.toPattern()); } private void tryDate(Date theDate) { @@ -169,7 +170,7 @@ } catch (ParseException e) { describeTest(); - errln("********** FAIL: Parse of " + string[i-1] + " failed."); + fail("********** FAIL: Parse of " + string[i-1] + " failed."); dump = true; break; } @@ -180,14 +181,14 @@ if (dateMatch == 0 && date[i] == date[i-1]) dateMatch = i; else if (dateMatch > 0 && date[i] != date[i-1]) { describeTest(); - errln("********** FAIL: Date mismatch after match."); + fail("********** FAIL: Date mismatch after match."); dump = true; break; } if (stringMatch == 0 && string[i] == string[i-1]) stringMatch = i; else if (stringMatch > 0 && string[i] != string[i-1]) { describeTest(); - errln("********** FAIL: String mismatch after match."); + fail("********** FAIL: String mismatch after match."); dump = true; break; } @@ -198,13 +199,13 @@ if (stringMatch > fLimit || dateMatch > fLimit) { describeTest(); - errln("********** FAIL: No string and/or date match within " + fLimit + " iterations."); + fail("********** FAIL: No string and/or date match within " + fLimit + " iterations."); dump = true; } if (dump) { for (int k=0; k<=i; ++k) { - logln("" + k + ": " + date[k] + " F> " + string[k] + " P> "); + System.out.println("" + k + ": " + date[k] + " F> " + string[k] + " P> "); } } } @@ -235,34 +236,36 @@ return rand.nextDouble(); } + @Test public void TestAvailableLocales() { final Locale[] locales = DateFormat.getAvailableLocales(); long count = locales.length; - logln("" + count + " available locales"); + System.out.println("" + count + " available locales"); if (locales != null && count != 0) { StringBuffer all = new StringBuffer(); for (int i=0; i subsitution failed. result = " + tempBuffer.toString()); - logln("Formatted with extra params : " + tempBuffer); + fail("Formatted with arguments > subsitution failed. result = " + tempBuffer.toString()); + System.out.println("Formatted with extra params : " + tempBuffer); //This statement gives an exception while formatting... //If we use pattern[1] for the message with param, //we get an NullPointerException in MessageFormat.java(617) @@ -103,28 +104,30 @@ //in applyPattern() when the pattern does not //contain any param. } catch (Exception foo) { - errln("Exception when formatting with no params."); + fail("Exception when formatting with no params."); } } /* @bug 4058973 * MessageFormat.toPattern has weird rounding behavior. */ + @Test public void Test4058973() { MessageFormat fmt = new MessageFormat("{0,choice,0#no files|1#one file|1< {0,number,integer} files}"); String pat = fmt.toPattern(); if (!pat.equals("{0,choice,0.0#no files|1.0#one file|1.0< {0,number,integer} files}")) { - errln("MessageFormat.toPattern failed"); + fail("MessageFormat.toPattern failed"); } } /* @bug 4031438 * More robust message formats. */ + @Test public void Test4031438() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -134,91 +137,94 @@ MessageFormat messageFormatter = new MessageFormat(""); try { - logln("Apply with pattern : " + pattern1); + System.out.println("Apply with pattern : " + pattern1); messageFormatter.applyPattern(pattern1); Object[] params = {7}; String tempBuffer = messageFormatter.format(params); if (!tempBuffer.equals("Impossible {1} has occurred -- status code is 7 and message is {2}.")) - errln("Tests arguments < substitution failed. Formatted text=" + + fail("Tests arguments < substitution failed. Formatted text=" + "<" + tempBuffer + ">"); - logln("Formatted with 7 : " + tempBuffer); + System.out.println("Formatted with 7 : " + tempBuffer); ParsePosition status = new ParsePosition(0); Object[] objs = messageFormatter.parse(tempBuffer, status); if (objs[params.length] != null) - errln("Parse failed with more than expected arguments"); + fail("Parse failed with more than expected arguments"); for (int i = 0; i < objs.length; i++) { if (objs[i] != null && !objs[i].toString().equals(params[i].toString())) { - errln("Parse failed on object " + objs[i] + " at index : " + i); + fail("Parse failed on object " + objs[i] + " at index : " + i); } } tempBuffer = messageFormatter.format(null); if (!tempBuffer.equals("Impossible {1} has occurred -- status code is {0} and message is {2}.")) - errln("Tests with no arguments failed"); - logln("Formatted with null : " + tempBuffer); - logln("Apply with pattern : " + pattern2); + fail("Tests with no arguments failed"); + System.out.println("Formatted with null : " + tempBuffer); + System.out.println("Apply with pattern : " + pattern2); messageFormatter.applyPattern(pattern2); tempBuffer = messageFormatter.format(params); if (!tempBuffer.equals("Double ' Quotes 7 test and quoted {1} test plus other {2} stuff.")) - errln("quote format test (w/ params) failed."); - logln("Formatted with params : " + tempBuffer); + fail("quote format test (w/ params) failed."); + System.out.println("Formatted with params : " + tempBuffer); tempBuffer = messageFormatter.format(null); if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff.")) - errln("quote format test (w/ null) failed."); - logln("Formatted with null : " + tempBuffer); - logln("toPattern : " + messageFormatter.toPattern()); + fail("quote format test (w/ null) failed."); + System.out.println("Formatted with null : " + tempBuffer); + System.out.println("toPattern : " + messageFormatter.toPattern()); } catch (Exception foo) { - errln("Exception when formatting in bug 4031438. "+foo.getMessage()); + fail("Exception when formatting in bug 4031438. "+foo.getMessage()); } } + @Test public void Test4052223() { ParsePosition pos = new ParsePosition(0); if (pos.getErrorIndex() != -1) { - errln("ParsePosition.getErrorIndex initialization failed."); + fail("ParsePosition.getErrorIndex initialization failed."); } MessageFormat fmt = new MessageFormat("There are {0} apples growing on the {1} tree."); String str = new String("There is one apple growing on the peach tree."); Object[] objs = fmt.parse(str, pos); - logln("unparsable string , should fail at " + pos.getErrorIndex()); + System.out.println("unparsable string , should fail at " + pos.getErrorIndex()); if (pos.getErrorIndex() == -1) - errln("Bug 4052223 failed : parsing string " + str); + fail("Bug 4052223 failed : parsing string " + str); pos.setErrorIndex(4); if (pos.getErrorIndex() != 4) - errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4"); + fail("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4"); ChoiceFormat f = new ChoiceFormat( "-1#are negative|0#are no or fraction|1#is one|1.0 " + + fail("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " + out + "; want \"" + DATA[i+1+j] + '"'); } String pat = cf.toPattern(); String pat2 = new ChoiceFormat(pat).toPattern(); if (!pat.equals(pat2)) - errln("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); + fail("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); else - logln("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); + System.out.println("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"'); } catch (IllegalArgumentException e) { - errln("Fail: Pattern \"" + DATA[i] + "\" -> " + e); + fail("Fail: Pattern \"" + DATA[i] + "\" -> " + e); } } } @@ -587,17 +607,18 @@ * MessageFormat.equals(null) throws a NullPointerException. The JLS states * that it should return false. */ + @Test public void Test4112104() { MessageFormat format = new MessageFormat(""); try { // This should NOT throw an exception if (format.equals(null)) { // It also should return false - errln("MessageFormat.equals(null) returns false"); + fail("MessageFormat.equals(null) returns false"); } } catch (NullPointerException e) { - errln("MessageFormat.equals(null) throws " + e); + fail("MessageFormat.equals(null) throws " + e); } } @@ -605,15 +626,17 @@ * @bug 4169959 * MessageFormat does not format null objects. CANNOT REPRODUCE THIS BUG. */ + @Test public void Test4169959() { // This works - logln(MessageFormat.format( "This will {0}", "work")); + System.out.println(MessageFormat.format( "This will {0}", "work")); // This fails - logln(MessageFormat.format( "This will {0}", + System.out.println(MessageFormat.format( "This will {0}", new Object[]{ null } ) ); } + @Test public void test4232154() { boolean gotException = false; try { @@ -632,6 +655,7 @@ } } + @Test public void test4293229() { MessageFormat format = new MessageFormat("'''{'0}'' '''{0}'''"); Object[] args = { null }; @@ -647,6 +671,7 @@ * @bug 8187551 * test MessageFormat.setFormat() method to throw AIOOBE on invalid index. */ + @Test public void test8187551() { //invalid cases ("pattern", "invalid format element index") String[][] invalidCases = {{"The disk \"{1}\" contains {0}.", "2"}, diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/MessageFormat/MessageTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/MessageTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/MessageFormat/MessageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/MessageTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test MessageFormat + * @run junit MessageTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -43,13 +43,14 @@ import java.io.*; import java.text.*; -public class MessageTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new MessageTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; +public class MessageTest { + + @Test public void TestMSGPatternTest() { Object[] testArgs = { 1D, 3456D, @@ -71,12 +72,12 @@ Locale save = Locale.getDefault(); try { Locale.setDefault(Locale.US); - logln(""); - logln( i + " Pat in: " + testCases[i]); + System.out.println(""); + System.out.println( i + " Pat in: " + testCases[i]); MessageFormat form = new MessageFormat(testCases[i]); - logln( i + " Pat out: " + form.toPattern()); + System.out.println( i + " Pat out: " + form.toPattern()); String result = form.format(testArgs); - logln( i + " Result: " + result); + System.out.println( i + " Result: " + result); Object[] values = form.parse(result); for (int j = 0; j < testArgs.length; ++j) { Object testArg = testArgs[j]; @@ -86,8 +87,8 @@ } if ((testArg == null && value != null) || (testArg != null && !testArg.equals(value))) { - logln( i + " " + j + " old: " + testArg); - logln( i + " " + j + " new: " + value); + System.out.println( i + " " + j + " old: " + testArg); + System.out.println( i + " " + j + " new: " + value); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/MessageFormat/bug4492719.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/bug4492719.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/MessageFormat/bug4492719.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/MessageFormat/bug4492719.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,35 @@ * @test * * @bug 4492719 - * @library /java/text/testlib * @summary Confirm that Message.parse() interprets time zone which uses "GMT+/-" format correctly and doesn't throw ParseException. + * @run junit/othervm bug4492719 */ import java.util.*; import java.text.*; -public class bug4492719 extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { +import static org.junit.jupiter.api.Assertions.fail; + +public class bug4492719 { + + // MessageFormat.parse() should be able to interpret a time zone + // that uses "GMT+/-". + @Test + public void testParse() throws Exception { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); MessageFormat mf; boolean err =false; String[] formats = { - "short", "medium", "long", "full" + "short", "medium", "long", "full" }; String[] timezones = { - "America/Los_Angeles", "GMT", "GMT+09:00", "GMT-8:00", - "GMT+123", "GMT-1234", "GMT+2", "GMT-13" + "America/Los_Angeles", "GMT", "GMT+09:00", "GMT-8:00", + "GMT+123", "GMT-1234", "GMT+2", "GMT-13" }; String text; @@ -58,14 +66,14 @@ for (int j = 0; j < formats.length; j++) { mf = new MessageFormat("{0,time," + formats[j] + "} - time"); text = MessageFormat.format("{0,time," + formats[j] + "} - time", - new Object [] { new Date(123456789012L)}); + new Object [] { new Date(123456789012L)}); Object[] objs = mf.parse(text); } } } catch (ParseException e) { err = true; System.err.println("Invalid ParseException occurred : " + - e.getMessage()); + e.getMessage()); System.err.println(" TimeZone=" + TimeZone.getDefault()); } finally { diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalFormat.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,20 +25,22 @@ * @test * @bug 4018937 8008577 * @summary Confirm that methods which are newly added to support BigDecimal and BigInteger work as expected. - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalFormat + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalFormat */ import java.math.BigDecimal; import java.math.BigInteger; -import java.text.*; -import java.util.*; +import java.text.DecimalFormat; +import java.text.FieldPosition; +import java.text.MessageFormat; +import java.text.NumberFormat; +import java.util.Locale; -public class BigDecimalFormat extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new BigDecimalFormat().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BigDecimalFormat { static final String nonsep_int = "123456789012345678901234567890123456789012345678901234567890" + @@ -99,6 +101,7 @@ /** * Test for normal big numbers which have the fraction part */ + @Test void test_Format_in_NumberFormat_BigDecimal() { String from, to; @@ -520,6 +523,7 @@ /** * Test for normal big numbers which have the fraction part with multiplier */ + @Test void test_Format_in_NumberFormat_BigDecimal_usingMultiplier() { String from, to; @@ -580,6 +584,7 @@ /** * Test for normal big numbers which don't have the fraction part */ + @Test void test_Format_in_NumberFormat_BigInteger() { String from, to; @@ -720,6 +725,7 @@ * Test for normal big numbers which don't have the fraction part with * multiplier */ + @Test void test_Format_in_NumberFormat_BigInteger_usingMultiplier() { String from, to; @@ -775,6 +781,7 @@ * Test for normal Long numbers when maximum and minimum digits are * specified */ + @Test void test_Format_in_NumberFormat_Long_checkDigits() { String from, to; @@ -890,6 +897,7 @@ * Double.POSITIVE_INFINITY * Double.NEGATIVE_INFINITY */ + @Test void test_Format_in_NumberFormat_SpecialNumber() { String from, to; @@ -932,6 +940,7 @@ * (Formatting Long.MIN_VALUE w/ multiplier=-1 used to return a wrong * number.) */ + @Test void test_Format_in_NumberFormat_Other() { String from, to; @@ -964,6 +973,7 @@ /** * Test for MessageFormat */ + @Test void test_Format_in_MessageFormat() { MessageFormat mf = new MessageFormat( " {0, number}\n" + @@ -998,7 +1008,7 @@ ; if (!expected.equals(mf.format(testArgs))) { - errln("Wrong format.\n got:\n" + mf.format(testArgs) + + fail("Wrong format.\n got:\n" + mf.format(testArgs) + " expected:\n" + expected); } } @@ -1014,7 +1024,7 @@ private void checkFormat(String orig, StringBuffer got, String expected, int multiplier) { if (!expected.equals(new String(got))) { - errln("Formatting... failed." + + fail("Formatting... failed." + "\n original: " + orig + "\n multiplier: " + multiplier + "\n formatted: " + got + @@ -1027,14 +1037,14 @@ int position; if ((position = fp.getBeginIndex()) != begin) { - errln("Formatting... wrong Begin index returned for " + + fail("Formatting... wrong Begin index returned for " + fp.getFieldAttribute() + "." + "\n original: " + orig + "\n got: " + position + "\n expected: " + begin + "\n"); } if ((position = fp.getEndIndex()) != end) { - errln("Formatting... wrong End index returned for " + + fail("Formatting... wrong End index returned for " + fp.getFieldAttribute() + "." + "\n original: " + orig + "\n got: " + position + diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/BigDecimalParse.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,27 +25,27 @@ * @test * @bug 4018937 8008577 * @summary Confirm that methods which are newly added to support BigDecimal and BigInteger work as expected. - * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalParse + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI BigDecimalParse */ import java.math.BigDecimal; import java.text.*; import java.util.*; -public class BigDecimalParse extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale loc = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - new BigDecimalParse().run(args); - } finally { - // restore the reserved locale - Locale.setDefault(loc); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class BigDecimalParse { + + // Change JVM default Locale + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); } + static final String nonsep_int = "123456789012345678901234567890123456789012345678901234567890" + "123456789012345678901234567890123456789012345678901234567890" + @@ -108,7 +108,8 @@ /** * Test for normal big numbers which have the fraction part */ - void test_Parse_in_DecimalFormat_BigDecimal() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -150,7 +151,8 @@ /** * Test for normal big numbers which have the fraction part with multiplier */ - void test_Parse_in_DecimalFormat_BigDecimal_usingMultiplier() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal_usingMultiplier() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -192,7 +194,8 @@ /** * Test for division by zero (BigDecimal) */ - void test_Parse_in_DecimalFormat_BigDecimal_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_BigDecimal_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(true); df.setMultiplier(0); @@ -213,7 +216,8 @@ /** * Test for division by zero (Double) */ - void test_Parse_in_DecimalFormat_Double_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_Double_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(false); df.setMultiplier(0); @@ -250,7 +254,8 @@ /** * Test for division by zero (Long) */ - void test_Parse_in_DecimalFormat_Long_DivisionByZero() { + @Test + public void test_Parse_in_DecimalFormat_Long_DivisionByZero() { df = new DecimalFormat(); df.setParseBigDecimal(false); df.setMultiplier(0); @@ -271,7 +276,8 @@ /** * Test for normal big numbers which don't have the fraction part */ - void test_Parse_in_DecimalFormat_BigInteger() { + @Test + public void test_Parse_in_DecimalFormat_BigInteger() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -296,7 +302,8 @@ * Test for normal big numbers which don't have the fraction part with * multiplier */ - void test_Parse_in_DecimalFormat_BigInteger_usingMultiplier() { + @Test + public void test_Parse_in_DecimalFormat_BigInteger_usingMultiplier() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -337,7 +344,8 @@ * Double.POSITIVE_INFINITY * Double.NEGATIVE_INFINITY */ - void test_Parse_in_DecimalFormat_SpecialNumber() { + @Test + public void test_Parse_in_DecimalFormat_SpecialNumber() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -378,7 +386,8 @@ /** * Test for special numbers */ - void test_Parse_in_DecimalFormat_Other() { + @Test + public void test_Parse_in_DecimalFormat_Other() { df = new DecimalFormat(); df.setParseBigDecimal(true); @@ -472,7 +481,8 @@ /** * Test for MessageFormat: setParseIntegerOnly(false) */ - void test_Parse_in_MessageFormat_NotParseIntegerOnly() { + @Test + public void test_Parse_in_MessageFormat_NotParseIntegerOnly() { for (int i=0; i < patterns.length; i++) { pp = new ParsePosition(0); Object[] parsed = null; @@ -487,19 +497,19 @@ parsed = mf.parse(from[i], pp); if (pp.getErrorIndex() != -1) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:-1, got:"+ pp.getErrorIndex() + " for " + from[i]); } if (pp.getIndex() != parsePosition1[i]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition1[i] + ", got:"+ pp.getIndex() + " for " + from[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } checkType(from[i], getType(new BigDecimal(expected1[i])), @@ -558,7 +568,8 @@ /** * Test for MessageFormat: setParseIntegerOnly(true) */ - void test_Parse_in_MessageFormat_ParseIntegerOnly() { + @Test + public void test_Parse_in_MessageFormat_ParseIntegerOnly() { for (int i=0; i < patterns.length; i++) { pp = new ParsePosition(0); Object[] parsed = null; @@ -574,20 +585,20 @@ parsed = mf.parse(from[i], pp); if (pp.getErrorIndex() != parsePosition2[i][0]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:" + parsePosition2[i][0] + ", got:"+ pp.getErrorIndex() + " for " + from[i]); } if (pp.getIndex() != parsePosition2[i][1]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition2[i][1] + ", got:"+ pp.getIndex() + " for " + from[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } if (parsePosition2[i][0] == -1) { @@ -624,7 +635,8 @@ /** * Test for DecimalFormat: setParseIntegerOnly(true) */ - void test_Parse_in_DecimalFormat_ParseIntegerOnly() { + @Test + public void test_Parse_in_DecimalFormat_ParseIntegerOnly() { DecimalFormat df = (DecimalFormat)NumberFormat.getIntegerInstance(); df.setParseBigDecimal(true); @@ -636,20 +648,20 @@ parsed = df.parse(from3[i], pp); if (pp.getErrorIndex() != parsePosition3[i][0]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getErrorIndex() returns wrong value. expected:" + parsePosition3[i][0] + ", got:"+ pp.getErrorIndex() + " for " + from3[i]); } if (pp.getIndex() != parsePosition3[i][1]) { - errln("Case" + (i+1) + + fail("Case" + (i+1) + ": getIndex() returns wrong value. expected:" + parsePosition3[i][1] + ", got:"+ pp.getIndex() + " for " + from3[i]); } } catch(Exception e) { - errln("Unexpected exception: " + e.getMessage()); + fail("Unexpected exception: " + e.getMessage()); } if (parsePosition3[i][0] == -1) { @@ -667,7 +679,7 @@ } catch(Exception e) { exceptionOccurred = true; - errln(e.getMessage()); + fail(e.getMessage()); } if (!exceptionOccurred) { checkParse(from, to, parsed); @@ -678,7 +690,7 @@ private void checkParse(String orig, Number expected, Number got) { if (!expected.equals(got)) { - errln("Parsing... failed." + + fail("Parsing... failed." + "\n original: " + orig + "\n parsed: " + got + "\n expected: " + expected + "\n"); @@ -687,7 +699,7 @@ private void checkType(String orig, String expected, String got) { if (!expected.equals(got)) { - errln("Parsing... unexpected Class returned." + + fail("Parsing... unexpected Class returned." + "\n original: " + orig + "\n got: " + got + "\n expected: " + expected + "\n"); @@ -696,7 +708,7 @@ private void checkParsePosition(String orig, int expected, int got) { if (expected != got) { - errln("Parsing... wrong ParsePosition returned." + + fail("Parsing... wrong ParsePosition returned." + "\n original: " + orig + "\n got: " + got + "\n expected: " + expected + "\n"); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/Bug4838107.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/Bug4838107.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/Bug4838107.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/Bug4838107.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,6 @@ * @summary Confirm that DecimalFormat can format a number with a negative * exponent number correctly. Tests also involve using a DecimalFormat * with a custom pattern or a custom minus sign. - * @library /java/text/testlib * @run junit/othervm -Djava.locale.providers=COMPAT,SPI Bug4838107 */ @@ -40,6 +39,7 @@ import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -57,7 +57,7 @@ * parsing using the same DecimalFormat instance will not change the * Number's value anymore. */ -public class Bug4838107 extends IntlTest { +public class Bug4838107 { // Save JVM default Locale private static final Locale savedLocale = Locale.getDefault(); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/DFSExponential.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSExponential.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/DFSExponential.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSExponential.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,67 +21,58 @@ * questions. */ -/** +/* * @test * @bug 4068067 - * @library /java/text/testlib * @summary test NumberFormat with exponential separator symbols. It also tests the new * public methods in DecimalFormatSymbols, setExponentSeparator() and * getExponentSeparator() + * @run junit DFSExponential */ -import java.util.*; -import java.text.*; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Locale; -public class DFSExponential extends IntlTest -{ +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DFSExponential().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; +public class DFSExponential { - public void DFSExponenTest() throws Exception { + @Test + public void TestDFSExponential() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); - String pat[] = { "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; - double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 }; - long lval[] = { 0, -1, 1, 123456789 }; - String valFormat[][] = { + String[] pat = { "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]"}; + double[] val = { 0.01234, 123456789, 1.23e300, -3.141592653e-271}; + String[][] valFormat = { {"1.234x10^-2", "1.2346x10^8", "1.23x10^300", "-3.1416x10^-271"}, {"12.340x10^-03", "12.346x10^07", "12.300x10^299", "-31.416x10^-272"}, {"12.34x10^-003", "123.4568x10^006", "1.23x10^300", "-314.1593x10^-273"}, {"1.234x10^-2", "1.235x10^8", "1.23x10^300", "[3.142x10^-271]"}, }; - - - int ival = 0, ilval = 0; - logln("Default exponent separator: "+sym.getExponentSeparator()); + System.out.println("Default exponent separator: "+sym.getExponentSeparator()); try { sym.setExponentSeparator("x10^"); } catch (NullPointerException e){ - errln("null String was passed to set an exponent separator symbol"); - throw new RuntimeException("Test Malfunction: null String was passed to set an exponent separator symbol" ); + fail("null String was passed to set an exponent separator symbol"); } - logln("Current exponent separator: "+sym.getExponentSeparator()); + System.out.println("Current exponent separator: "+sym.getExponentSeparator()); for (int p=0; p "+s); - if(valFormat[p][v].equals(s)){ - logln(": Passed"); - }else{ - errln(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); - throw new RuntimeException(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); + System.out.println(" " + val[v]+" --> "+s); + if (valFormat[p][v].equals(s)){ + System.out.println(": Passed"); + } else{ + fail(" Failed: Should be formatted as "+valFormat[p][v]+ "but got "+s); } } - } //end of the first for loop - } + } + } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/DFSSerialization.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,8 @@ * @test * @bug 4068067 * @library /java/text/testlib - * @build DFSSerialization IntlTest HexDumpReader - * @run main DFSSerialization + * @build DFSSerialization HexDumpReader + * @run junit DFSSerialization * @summary Three different tests are done. * 1. read from the object created using jdk1.4.2 * 2. create a valid DecimalFormatSymbols object with current JDK, then read the object @@ -43,10 +43,13 @@ import java.text.DecimalFormatSymbols; import java.util.Locale; -public class DFSSerialization extends IntlTest{ - public static void main(String[] args) throws Exception { - new DFSSerialization().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class DFSSerialization{ + + @Test public void TestDFSSerialization(){ /* * 1. read from the object created using jdk1.4.2 @@ -56,9 +59,9 @@ if (dfs142 != null){ if (dfs142.getExponentSeparator().equals("E") && dfs142.getCurrencySymbol().equals("*SpecialCurrencySymbol*")){ System.out.println("\n Deserialization of JDK1.4.2 Object from the current JDK: Passed."); - logln(" Deserialization of JDK1.4.2 Object from the current JDK: Passed."); + System.out.println(" Deserialization of JDK1.4.2 Object from the current JDK: Passed."); } else { - errln(" Deserialization of JDK1.4.2 Object from the current JDK was Failed:" + fail(" Deserialization of JDK1.4.2 Object from the current JDK was Failed:" +dfs142.getCurrencySymbol()+" "+dfs142.getExponentSeparator()); /* * logically should not throw this exception as errln throws exception @@ -79,9 +82,9 @@ if (dfsValid.getExponentSeparator().equals("*SpecialExponentSeparator*") && dfsValid.getCurrencySymbol().equals("*SpecialCurrencySymbol*")){ System.out.println(" Deserialization of current JDK Object from the current JDK: Passed."); - logln(" Deserialization of current JDK Object from the current JDK: Passed."); + System.out.println(" Deserialization of current JDK Object from the current JDK: Passed."); } else { - errln(" Deserialization of current JDK Object from the current JDK was Failed:" + fail(" Deserialization of current JDK Object from the current JDK was Failed:" +dfsValid.getCurrencySymbol()+" "+dfsValid.getExponentSeparator()); /* * logically should not throw this exception as errln throws exception @@ -102,11 +105,11 @@ } catch (NullPointerException npe){ npePassed = true; System.out.println(" Trying to set exponent separator with null: Passed."); - logln(" Trying to set exponent separator with null: Passed."); + System.out.println(" Trying to set exponent separator with null: Passed."); } if (!npePassed){ System.out.println(" Trying to set exponent separator with null:Failed."); - errln(" Trying to set exponent separator with null:Failed."); + fail(" Trying to set exponent separator with null:Failed."); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed @@ -124,7 +127,7 @@ DecimalFormatSymbols dfs = (DecimalFormatSymbols)p.readObject(); return dfs; } catch (Exception e) { - errln("Test Malfunction in DFSSerialization: Exception while reading the object"); + fail("Test Malfunction in DFSSerialization: Exception while reading the object"); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed @@ -137,8 +140,8 @@ DecimalFormatSymbols dfs= new DecimalFormatSymbols(); dfs.setExponentSeparator(expString); dfs.setCurrencySymbol("*SpecialCurrencySymbol*"); - logln(" The special exponent separator is set : " + dfs.getExponentSeparator()); - logln(" The special currency symbol is set : " + dfs.getCurrencySymbol()); + System.out.println(" The special exponent separator is set : " + dfs.getExponentSeparator()); + System.out.println(" The special currency symbol is set : " + dfs.getCurrencySymbol()); // 6345659: create a test object in the test.class dir where test user has a write permission. File file = new File(System.getProperty("test.class", "."), objectName); @@ -148,7 +151,7 @@ //System.out.println(" The special currency symbol is set : " + dfs.getCurrencySymbol()); return file; } catch (Exception e){ - errln("Test Malfunction in DFSSerialization: Exception while creating an object"); + fail("Test Malfunction in DFSSerialization: Exception while creating an object"); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatAPI.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,8 @@ /* * @test - * @library /java/text/testlib * @summary test International Decimal Format API + * @run junit IntlTestDecimalFormatAPI */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -41,23 +41,24 @@ import java.text.*; import java.util.*; -public class IntlTestDecimalFormatAPI extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestDecimalFormatAPI().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; +public class IntlTestDecimalFormatAPI +{ // This test checks various generic API methods in DecimalFormat to achieve 100% API coverage. + @Test public void TestAPI() { Locale reservedLocale = Locale.getDefault(); try { - logln("DecimalFormat API test---"); logln(""); + System.out.println("DecimalFormat API test---"); System.out.println(""); Locale.setDefault(Locale.ENGLISH); // ======= Test constructors - logln("Testing DecimalFormat constructors"); + System.out.println("Testing DecimalFormat constructors"); DecimalFormat def = new DecimalFormat(); @@ -67,7 +68,7 @@ pat = new DecimalFormat(pattern); } catch (IllegalArgumentException e) { - errln("ERROR: Could not create DecimalFormat (pattern)"); + fail("ERROR: Could not create DecimalFormat (pattern)"); } DecimalFormatSymbols symbols = @@ -77,16 +78,16 @@ // ======= Test clone(), assignment, and equality - logln("Testing clone() and equality operators"); + System.out.println("Testing clone() and equality operators"); Format clone = (Format) def.clone(); if( ! def.equals(clone)) { - errln("ERROR: Clone() failed"); + fail("ERROR: Clone() failed"); } // ======= Test various format() methods - logln("Testing various format() methods"); + System.out.println("Testing various format() methods"); // final double d = -10456.0037; // this appears as // -10456.003700000001 on NT @@ -94,7 +95,7 @@ // -1.0456003700000002E-4 on NT final double d = -10456.00370000000000; // this works! final long l = 100000000; - logln("" + d + " is the double value"); + System.out.println("" + d + " is the double value"); StringBuffer res1 = new StringBuffer(); StringBuffer res2 = new StringBuffer(); @@ -106,20 +107,20 @@ FieldPosition pos4 = new FieldPosition(0); res1 = def.format(d, res1, pos1); - logln("" + d + " formatted to " + res1); + System.out.println("" + d + " formatted to " + res1); res2 = pat.format(l, res2, pos2); - logln("" + l + " formatted to " + res2); + System.out.println("" + l + " formatted to " + res2); res3 = cust1.format(d, res3, pos3); - logln("" + d + " formatted to " + res3); + System.out.println("" + d + " formatted to " + res3); res4 = cust1.format(l, res4, pos4); - logln("" + l + " formatted to " + res4); + System.out.println("" + l + " formatted to " + res4); // ======= Test parse() - logln("Testing parse()"); + System.out.println("Testing parse()"); String text = new String("-10,456.0037"); ParsePosition pos = new ParsePosition(0); @@ -127,109 +128,109 @@ pat.applyPattern(patt); double d2 = pat.parse(text, pos).doubleValue(); if(d2 != d) { - errln("ERROR: Roundtrip failed (via parse(" + + fail("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text); } - logln(text + " parsed into " + (long) d2); + System.out.println(text + " parsed into " + (long) d2); // ======= Test getters and setters - logln("Testing getters and setters"); + System.out.println("Testing getters and setters"); final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols(); def.setDecimalFormatSymbols(syms); if(!pat.getDecimalFormatSymbols().equals( def.getDecimalFormatSymbols())) { - errln("ERROR: set DecimalFormatSymbols() failed"); + fail("ERROR: set DecimalFormatSymbols() failed"); } String posPrefix; pat.setPositivePrefix("+"); posPrefix = pat.getPositivePrefix(); - logln("Positive prefix (should be +): " + posPrefix); + System.out.println("Positive prefix (should be +): " + posPrefix); if(posPrefix != "+") { - errln("ERROR: setPositivePrefix() failed"); + fail("ERROR: setPositivePrefix() failed"); } String negPrefix; pat.setNegativePrefix("-"); negPrefix = pat.getNegativePrefix(); - logln("Negative prefix (should be -): " + negPrefix); + System.out.println("Negative prefix (should be -): " + negPrefix); if(negPrefix != "-") { - errln("ERROR: setNegativePrefix() failed"); + fail("ERROR: setNegativePrefix() failed"); } String posSuffix; pat.setPositiveSuffix("_"); posSuffix = pat.getPositiveSuffix(); - logln("Positive suffix (should be _): " + posSuffix); + System.out.println("Positive suffix (should be _): " + posSuffix); if(posSuffix != "_") { - errln("ERROR: setPositiveSuffix() failed"); + fail("ERROR: setPositiveSuffix() failed"); } String negSuffix; pat.setNegativeSuffix("~"); negSuffix = pat.getNegativeSuffix(); - logln("Negative suffix (should be ~): " + negSuffix); + System.out.println("Negative suffix (should be ~): " + negSuffix); if(negSuffix != "~") { - errln("ERROR: setNegativeSuffix() failed"); + fail("ERROR: setNegativeSuffix() failed"); } long multiplier = 0; pat.setMultiplier(8); multiplier = pat.getMultiplier(); - logln("Multiplier (should be 8): " + multiplier); + System.out.println("Multiplier (should be 8): " + multiplier); if(multiplier != 8) { - errln("ERROR: setMultiplier() failed"); + fail("ERROR: setMultiplier() failed"); } int groupingSize = 0; pat.setGroupingSize(2); groupingSize = pat.getGroupingSize(); - logln("Grouping size (should be 2): " + (long) groupingSize); + System.out.println("Grouping size (should be 2): " + (long) groupingSize); if(groupingSize != 2) { - errln("ERROR: setGroupingSize() failed"); + fail("ERROR: setGroupingSize() failed"); } pat.setDecimalSeparatorAlwaysShown(true); boolean tf = pat.isDecimalSeparatorAlwaysShown(); - logln("DecimalSeparatorIsAlwaysShown (should be true) is " + + System.out.println("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false")); if(tf != true) { - errln("ERROR: setDecimalSeparatorAlwaysShown() failed"); + fail("ERROR: setDecimalSeparatorAlwaysShown() failed"); } String funkyPat; funkyPat = pat.toPattern(); - logln("Pattern is " + funkyPat); + System.out.println("Pattern is " + funkyPat); String locPat; locPat = pat.toLocalizedPattern(); - logln("Localized pattern is " + locPat); + System.out.println("Localized pattern is " + locPat); // ======= Test applyPattern() - logln("Testing applyPattern()"); + System.out.println("Testing applyPattern()"); String p1 = new String("#,##0.0#;(#,##0.0#)"); - logln("Applying pattern " + p1); + System.out.println("Applying pattern " + p1); pat.applyPattern(p1); String s2; s2 = pat.toPattern(); - logln("Extracted pattern is " + s2); + System.out.println("Extracted pattern is " + s2); if( ! s2.equals(p1) ) { - errln("ERROR: toPattern() result did not match " + + fail("ERROR: toPattern() result did not match " + "pattern applied"); } String p2 = new String("#,##0.0# FF;(#,##0.0# FF)"); - logln("Applying pattern " + p2); + System.out.println("Applying pattern " + p2); pat.applyLocalizedPattern(p2); String s3; s3 = pat.toLocalizedPattern(); - logln("Extracted pattern is " + s3); + System.out.println("Extracted pattern is " + s3); if( ! s3.equals(p2) ) { - errln("ERROR: toLocalizedPattern() result did not match " + + fail("ERROR: toLocalizedPattern() result did not match " + "pattern applied"); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestDecimalFormatSymbols.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,8 +23,9 @@ /* * @test - * @library /java/text/testlib + * @bug 8282625 * @summary test International Decimal Format Symbols + * @run junit IntlTestDecimalFormatSymbols */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -41,13 +42,14 @@ import java.text.*; import java.util.*; -public class IntlTestDecimalFormatSymbols extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestDecimalFormatSymbols().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class IntlTestDecimalFormatSymbols +{ // Test the API of DecimalFormatSymbols; primarily a simple get/set set. + @Test public void TestSymbols() { DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH); @@ -55,7 +57,7 @@ DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH); if(en.equals(fr)) { - errln("ERROR: English DecimalFormatSymbols equal to French"); + fail("ERROR: English DecimalFormatSymbols equal to French"); } // just do some VERY basic tests to make sure that get/set work @@ -63,63 +65,63 @@ char zero = en.getZeroDigit(); fr.setZeroDigit(zero); if(fr.getZeroDigit() != en.getZeroDigit()) { - errln("ERROR: get/set ZeroDigit failed"); + fail("ERROR: get/set ZeroDigit failed"); } char group = en.getGroupingSeparator(); fr.setGroupingSeparator(group); if(fr.getGroupingSeparator() != en.getGroupingSeparator()) { - errln("ERROR: get/set GroupingSeparator failed"); + fail("ERROR: get/set GroupingSeparator failed"); } char decimal = en.getDecimalSeparator(); fr.setDecimalSeparator(decimal); if(fr.getDecimalSeparator() != en.getDecimalSeparator()) { - errln("ERROR: get/set DecimalSeparator failed"); + fail("ERROR: get/set DecimalSeparator failed"); } char perMill = en.getPerMill(); fr.setPerMill(perMill); if(fr.getPerMill() != en.getPerMill()) { - errln("ERROR: get/set PerMill failed"); + fail("ERROR: get/set PerMill failed"); } char percent = en.getPercent(); fr.setPercent(percent); if(fr.getPercent() != en.getPercent()) { - errln("ERROR: get/set Percent failed"); + fail("ERROR: get/set Percent failed"); } char digit = en.getDigit(); fr.setDigit(digit); if(fr.getPercent() != en.getPercent()) { - errln("ERROR: get/set Percent failed"); + fail("ERROR: get/set Percent failed"); } char patternSeparator = en.getPatternSeparator(); fr.setPatternSeparator(patternSeparator); if(fr.getPatternSeparator() != en.getPatternSeparator()) { - errln("ERROR: get/set PatternSeparator failed"); + fail("ERROR: get/set PatternSeparator failed"); } String infinity = en.getInfinity(); fr.setInfinity(infinity); String infinity2 = fr.getInfinity(); if(! infinity.equals(infinity2)) { - errln("ERROR: get/set Infinity failed"); + fail("ERROR: get/set Infinity failed"); } String nan = en.getNaN(); fr.setNaN(nan); String nan2 = fr.getNaN(); if(! nan.equals(nan2)) { - errln("ERROR: get/set NaN failed"); + fail("ERROR: get/set NaN failed"); } char minusSign = en.getMinusSign(); fr.setMinusSign(minusSign); if(fr.getMinusSign() != en.getMinusSign()) { - errln("ERROR: get/set MinusSign failed"); + fail("ERROR: get/set MinusSign failed"); } // char exponential = en.getExponentialSymbol(); @@ -133,7 +135,7 @@ en = (DecimalFormatSymbols) fr.clone(); if(! en.equals(fr)) { - errln("ERROR: Clone failed"); + fail("ERROR: Clone failed"); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/IntlTestNumberFormatAPI.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,9 +23,9 @@ /* * @test - * @library /java/text/testlib * @summary test International Number Format API * @modules jdk.localedata + * @run junit IntlTestNumberFormatAPI */ /* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved @@ -42,23 +42,24 @@ import java.text.*; import java.util.*; -public class IntlTestNumberFormatAPI extends IntlTest -{ - public static void main(String[] args) throws Exception { - new IntlTestNumberFormatAPI().run(args); - } +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; +public class IntlTestNumberFormatAPI +{ // This test checks various generic API methods in DecimalFormat to achieve 100% API coverage. + @Test public void TestAPI() { Locale reservedLocale = Locale.getDefault(); try { - logln("NumberFormat API test---"); logln(""); + System.out.println("NumberFormat API test---"); System.out.println(""); Locale.setDefault(Locale.ENGLISH); // ======= Test constructors - logln("Testing NumberFormat constructors"); + System.out.println("Testing NumberFormat constructors"); NumberFormat def = NumberFormat.getInstance(); @@ -76,15 +77,15 @@ // ======= Test equality - logln("Testing equality operator"); + System.out.println("Testing equality operator"); if( per_fr.equals(cur_fr) ) { - errln("ERROR: == failed"); + fail("ERROR: == failed"); } // ======= Test various format() methods - logln("Testing various format() methods"); + System.out.println("Testing various format() methods"); // final double d = -10456.0037; // this appears as // -10456.003700000001 on NT @@ -105,27 +106,27 @@ FieldPosition pos4 = new FieldPosition(0); res1 = cur_fr.format(d); - logln( "" + d + " formatted to " + res1); + System.out.println( "" + d + " formatted to " + res1); res2 = cur_fr.format(l); - logln("" + l + " formatted to " + res2); + System.out.println("" + l + " formatted to " + res2); res3 = cur_fr.format(d, res3, pos1); - logln( "" + d + " formatted to " + res3); + System.out.println( "" + d + " formatted to " + res3); res4 = cur_fr.format(l, res4, pos2); - logln("" + l + " formatted to " + res4); + System.out.println("" + l + " formatted to " + res4); res5 = cur_fr.format(d, res5, pos3); - logln("" + d + " formatted to " + res5); + System.out.println("" + d + " formatted to " + res5); res6 = cur_fr.format(l, res6, pos4); - logln("" + l + " formatted to " + res6); + System.out.println("" + l + " formatted to " + res6); // ======= Test parse() - logln("Testing parse()"); + System.out.println("Testing parse()"); // String text = new String("-10,456.0037"); String text = new String("-10456,0037"); @@ -133,70 +134,70 @@ ParsePosition pos01 = new ParsePosition(0); double d1 = ((Number)fr.parseObject(text, pos)).doubleValue(); if(d1 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d1); + System.out.println(text + " parsed into " + d1); double d2 = fr.parse(text, pos01).doubleValue(); if(d2 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d2); + System.out.println(text + " parsed into " + d2); double d3 = 0; try { d3 = fr.parse(text).doubleValue(); } catch (ParseException e) { - errln("ERROR: parse() failed"); + fail("ERROR: parse() failed"); } if(d3 != d) { - errln("ERROR: Roundtrip failed (via parse()) for " + text); + fail("ERROR: Roundtrip failed (via parse()) for " + text); } - logln(text + " parsed into " + d3); + System.out.println(text + " parsed into " + d3); // ======= Test getters and setters - logln("Testing getters and setters"); + System.out.println("Testing getters and setters"); final Locale[] locales = NumberFormat.getAvailableLocales(); long count = locales.length; - logln("Got " + count + " locales" ); + System.out.println("Got " + count + " locales" ); for(int i = 0; i < count; i++) { String name; name = locales[i].getDisplayName(); - logln(name); + System.out.println(name); } fr.setParseIntegerOnly( def.isParseIntegerOnly() ); if(fr.isParseIntegerOnly() != def.isParseIntegerOnly() ) { - errln("ERROR: setParseIntegerOnly() failed"); + fail("ERROR: setParseIntegerOnly() failed"); } fr.setGroupingUsed( def.isGroupingUsed() ); if(fr.isGroupingUsed() != def.isGroupingUsed() ) { - errln("ERROR: setGroupingUsed() failed"); + fail("ERROR: setGroupingUsed() failed"); } fr.setMaximumIntegerDigits( def.getMaximumIntegerDigits() ); if(fr.getMaximumIntegerDigits() != def.getMaximumIntegerDigits() ) { - errln("ERROR: setMaximumIntegerDigits() failed"); + fail("ERROR: setMaximumIntegerDigits() failed"); } fr.setMinimumIntegerDigits( def.getMinimumIntegerDigits() ); if(fr.getMinimumIntegerDigits() != def.getMinimumIntegerDigits() ) { - errln("ERROR: setMinimumIntegerDigits() failed"); + fail("ERROR: setMinimumIntegerDigits() failed"); } fr.setMaximumFractionDigits( def.getMaximumFractionDigits() ); if(fr.getMaximumFractionDigits() != def.getMaximumFractionDigits() ) { - errln("ERROR: setMaximumFractionDigits() failed"); + fail("ERROR: setMaximumFractionDigits() failed"); } fr.setMinimumFractionDigits( def.getMinimumFractionDigits() ); if(fr.getMinimumFractionDigits() != def.getMinimumFractionDigits() ) { - errln("ERROR: setMinimumFractionDigits() failed"); + fail("ERROR: setMinimumFractionDigits() failed"); } // ======= Test getStaticClassID() diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/NumberRegression.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberRegression.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/NumberRegression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberRegression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,11 +32,11 @@ * 4217661 4243011 4243108 4330377 4233840 4241880 4833877 8008577 8227313 * @summary Regression tests for NumberFormat and associated classes * @library /java/text/testlib - * @build IntlTest HexDumpReader TestUtils + * @build HexDumpReader TestUtils * @modules java.base/sun.util.resources * jdk.localedata * @compile -XDignore.symbol.file NumberRegression.java - * @run main/othervm -Djava.locale.providers=COMPAT,SPI NumberRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI NumberRegression */ /* @@ -58,23 +58,24 @@ import java.math.BigInteger; import sun.util.resources.LocaleData; -public class NumberRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new NumberRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class NumberRegression { /** * NumberFormat.equals comparing with null should always return false. */ + @Test public void Test4075713(){ try { MyNumberFormatTest tmp = new MyNumberFormatTest(); if (!tmp.equals(null)) - logln("NumberFormat.equals passed"); + System.out.println("NumberFormat.equals passed"); } catch (NullPointerException e) { - errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception"); + fail("(new MyNumberFormatTest()).equals(null) throws unexpected exception"); } } @@ -82,6 +83,7 @@ * NumberFormat.equals comparing two obj equal even the setGroupingUsed * flag is different. */ + @Test public void Test4074620() { MyNumberFormatTest nf1 = new MyNumberFormatTest(); @@ -90,8 +92,8 @@ nf1.setGroupingUsed(false); nf2.setGroupingUsed(true); - if (nf1.equals(nf2)) errln("Test for bug 4074620 failed"); - else logln("Test for bug 4074620 passed."); + if (nf1.equals(nf2)) fail("Test for bug 4074620 failed"); + else System.out.println("Test for bug 4074620 passed."); return; } @@ -100,10 +102,11 @@ * DecimalFormat.format() incorrectly uses maxFractionDigits setting. */ + @Test public void Test4088161 (){ Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -113,39 +116,41 @@ df.setMaximumFractionDigits(16); StringBuffer sBuf1 = new StringBuffer(""); FieldPosition fp1 = new FieldPosition(0); - logln("d = " + d); - logln("maxFractionDigits = " + df.getMaximumFractionDigits()); - logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'"); + System.out.println("d = " + d); + System.out.println("maxFractionDigits = " + df.getMaximumFractionDigits()); + System.out.println(" format(d) = '" + df.format(d, sBuf1, fp1) + "'"); df.setMaximumFractionDigits(17); StringBuffer sBuf2 = new StringBuffer(""); FieldPosition fp2 = new FieldPosition(0); - logln("maxFractionDigits = " + df.getMaximumFractionDigits()); + System.out.println("maxFractionDigits = " + df.getMaximumFractionDigits()); df.format(d, sBuf2, fp2); String expected = "100"; if (!sBuf2.toString().equals(expected)) - errln(" format(d) = '" + sBuf2 + "'"); + fail(" format(d) = '" + sBuf2 + "'"); } /** * DecimalFormatSymbols should be cloned in the ctor DecimalFormat. * DecimalFormat(String, DecimalFormatSymbols). */ + @Test public void Test4087245 (){ DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(); DecimalFormat df = new DecimalFormat("#,##0.0", symbols); long n = 123; StringBuffer buf1 = new StringBuffer(); StringBuffer buf2 = new StringBuffer(); - logln("format(" + n + ") = " + + System.out.println("format(" + n + ") = " + df.format(n, buf1, new FieldPosition(0))); symbols.setDecimalSeparator('p'); // change value of field - logln("format(" + n + ") = " + + System.out.println("format(" + n + ") = " + df.format(n, buf2, new FieldPosition(0))); if (!buf1.toString().equals(buf2.toString())) - errln("Test for bug 4087245 failed"); + fail("Test for bug 4087245 failed"); } /** * DecimalFormat.format() incorrectly formats 0.0 */ + @Test public void Test4087535 () { DecimalFormat df = new DecimalFormat(); @@ -155,31 +160,33 @@ String buffer = new String(); buffer = df.format(n); if (buffer.length() == 0) - errln(n + ": '" + buffer + "'"); + fail(n + ": '" + buffer + "'"); n = 0.1; buffer = df.format(n); if (buffer.length() == 0) - errln(n + ": '" + buffer + "'"); + fail(n + ": '" + buffer + "'"); } /** * DecimalFormat.format fails when groupingSize is set to 0. */ + @Test public void Test4088503 (){ DecimalFormat df = new DecimalFormat(); df.setGroupingSize(0); StringBuffer sBuf = new StringBuffer(""); FieldPosition fp = new FieldPosition(0); try { - logln(df.format(123, sBuf, fp).toString()); + System.out.println(df.format(123, sBuf, fp).toString()); } catch (Exception foo) { - errln("Test for bug 4088503 failed."); + fail("Test for bug 4088503 failed."); } } /** * NumberFormat.getCurrencyInstance is wrong. */ + @Test public void Test4066646 () { float returnfloat = 0.0f; assignFloatValue(2.04f); @@ -190,42 +197,45 @@ public float assignFloatValue(float returnfloat) { - logln(" VALUE " + returnfloat); + System.out.println(" VALUE " + returnfloat); NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US); nfcommon.setGroupingUsed(false); String stringValue = nfcommon.format(returnfloat).substring(1); if (Float.valueOf(stringValue).floatValue() != returnfloat) - errln(" DISPLAYVALUE " + stringValue); + fail(" DISPLAYVALUE " + stringValue); return returnfloat; } // End Of assignFloatValue() /** * DecimalFormat throws exception when parsing "0" */ + @Test public void Test4059870() { DecimalFormat format = new DecimalFormat("00"); try { - logln(format.parse("0").toString()); - } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); } + System.out.println(format.parse("0").toString()); + } catch (Exception e) { fail("Test for bug 4059870 failed : " + e); } } /** * DecimalFormatSymbol.equals should always return false when * comparing with null. */ + @Test public void Test4083018 (){ DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); try { if (!dfs.equals(null)) - logln("Test Passed!"); + System.out.println("Test Passed!"); } catch (Exception foo) { - errln("Test for bug 4083018 failed => Message : " + foo.getMessage()); + fail("Test for bug 4083018 failed => Message : " + foo.getMessage()); } } /** * DecimalFormat does not round up correctly. */ + @Test public void Test4071492 (){ Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -233,10 +243,10 @@ NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumFractionDigits(4); String out = nf.format(x); - logln("0.00159999 formats with 4 fractional digits to " + out); + System.out.println("0.00159999 formats with 4 fractional digits to " + out); String expected = "0.0016"; if (!out.equals(expected)) - errln("FAIL: Expected " + expected); + fail("FAIL: Expected " + expected); Locale.setDefault(savedLocale); } @@ -244,33 +254,34 @@ * A space as a group separator for localized pattern causes * wrong format. WorkAround : use non-breaking space. */ + @Test public void Test4086575() { NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE); - logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern1: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern()); // No group separator - logln("...applyLocalizedPattern ###,00;(###,00) "); + System.out.println("...applyLocalizedPattern ###,00;(###,00) "); ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)"); - logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); - logln("nf: " + nf.format(1234)); // 1234,00 - logln("nf: " + nf.format(-1234)); // (1234,00) + System.out.println("nf: " + nf.format(1234)); // 1234,00 + System.out.println("nf: " + nf.format(-1234)); // (1234,00) // Space as group separator - logln("...applyLocalizedPattern # ###,00;(# ###,00) "); + System.out.println("...applyLocalizedPattern # ###,00;(# ###,00) "); ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)"); - logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); - logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); + System.out.println("nf toPattern2: " + ((DecimalFormat)nf).toPattern()); + System.out.println("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern()); String buffer = nf.format(1234); if (!buffer.equals("1\u00a0234,00")) - errln("nf : " + buffer); // Expect 1 234,00 + fail("nf : " + buffer); // Expect 1 234,00 buffer = nf.format(-1234); if (!buffer.equals("(1\u00a0234,00)")) - errln("nf : " + buffer); // Expect (1 234,00) + fail("nf : " + buffer); // Expect (1 234,00) // Erroneously prints: // 1234,00 , @@ -280,16 +291,17 @@ /** * DecimalFormat.parse returns wrong value */ + @Test public void Test4068693() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); - logln("----- Test Application -----"); + System.out.println("----- Test Application -----"); ParsePosition pos; DecimalFormat df = new DecimalFormat(); Double d = (Double)df.parse("123.55456", pos=new ParsePosition(0)); if (!d.toString().equals("123.55456")) { - errln("Result -> " + d); + fail("Result -> " + d); } Locale.setDefault(savedLocale); } @@ -298,53 +310,56 @@ * null pointer thrown when accessing a deserialized DecimalFormat * object. */ + @Test public void Test4069754() { try { myformat it = new myformat(); - logln(it.Now()); + System.out.println(it.Now()); FileOutputStream ostream = new FileOutputStream("t.tmp"); ObjectOutputStream p = new ObjectOutputStream(ostream); p.writeObject(it); ostream.close(); - logln("Saved ok."); + System.out.println("Saved ok."); FileInputStream istream = new FileInputStream("t.tmp"); ObjectInputStream p2 = new ObjectInputStream(istream); myformat it2 = (myformat)p2.readObject(); - logln(it2.Now()); + System.out.println(it2.Now()); istream.close(); - logln("Loaded ok."); + System.out.println("Loaded ok."); } catch (Exception foo) { - errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage()); + fail("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage()); } } /** * DecimalFormat.applyPattern(String) allows illegal patterns */ + @Test public void Test4087251 (){ DecimalFormat df = new DecimalFormat(); try { df.applyPattern("#.#.#"); - logln("toPattern() returns \"" + df.toPattern() + "\""); - errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException"); + System.out.println("toPattern() returns \"" + df.toPattern() + "\""); + fail("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException"); } catch (IllegalArgumentException e) { - logln("Caught Illegal Argument Error !"); + System.out.println("Caught Illegal Argument Error !"); } // Second test; added 5/11/98 when reported to fail on 1.2b3 try { df.applyPattern("#0.0#0#0"); - logln("toPattern() returns \"" + df.toPattern() + "\""); - errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException"); + System.out.println("toPattern() returns \"" + df.toPattern() + "\""); + fail("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException"); } catch (IllegalArgumentException e) { - logln("Ok - IllegalArgumentException for #0.0#0#0"); + System.out.println("Ok - IllegalArgumentException for #0.0#0#0"); } } /** * DecimalFormat.format() loses precision */ + @Test public void Test4090489 (){ Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -355,11 +370,11 @@ BigDecimal bd = new BigDecimal(d); StringBuffer sb = new StringBuffer(""); FieldPosition fp = new FieldPosition(0); - logln("d = " + d); - logln("BigDecimal.toString(): " + bd.toString()); + System.out.println("d = " + d); + System.out.println("BigDecimal.toString(): " + bd.toString()); df.format(d, sb, fp); if (!sb.toString().equals("10000000.0000000100")) { - errln("DecimalFormat.format(): " + sb.toString()); + fail("DecimalFormat.format(): " + sb.toString()); } Locale.setDefault(savedLocale); } @@ -367,10 +382,11 @@ /** * DecimalFormat.format() loses precision */ + @Test public void Test4090504 () { double d = 1; - logln("d = " + d); + System.out.println("d = " + d); DecimalFormat df = new DecimalFormat(); StringBuffer sb; FieldPosition fp; @@ -379,16 +395,17 @@ df.setMaximumFractionDigits(i); sb = new StringBuffer(""); fp = new FieldPosition(0); - logln(" getMaximumFractionDigits() = " + i); - logln(" formated: " + df.format(d, sb, fp)); + System.out.println(" getMaximumFractionDigits() = " + i); + System.out.println(" formated: " + df.format(d, sb, fp)); } } catch (Exception foo) { - errln("Bug 4090504 regression test failed. Message : " + foo.getMessage()); + fail("Bug 4090504 regression test failed. Message : " + foo.getMessage()); } } /** * DecimalFormat.parse(String str, ParsePosition pp) loses precision */ + @Test public void Test4095713 () { Locale savedLocale = Locale.getDefault(); @@ -397,15 +414,16 @@ String str = "0.1234"; Double d1 = 0.1234; Double d2 = (Double) df.parse(str, new ParsePosition(0)); - logln(d1.toString()); + System.out.println(d1.toString()); if (d2.doubleValue() != d1.doubleValue()) - errln("Bug 4095713 test failed, new double value : " + d2); + fail("Bug 4095713 test failed, new double value : " + d2); Locale.setDefault(savedLocale); } /** * DecimalFormat.parse() fails when multiplier is not set to 1 */ + @Test public void Test4092561 () { Locale savedLocale = Locale.getDefault(); @@ -413,32 +431,32 @@ DecimalFormat df = new DecimalFormat(); String str = Long.toString(Long.MIN_VALUE); - logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); + System.out.println("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); df.setMultiplier(100); Number num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != -9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); } df.setMultiplier(-100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != 9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); } str = Long.toString(Long.MAX_VALUE); - logln("Long.MAX_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); + System.out.println("Long.MAX_VALUE : " + df.parse(str, new ParsePosition(0)).toString()); df.setMultiplier(100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != 9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue()); } df.setMultiplier(-100); num = df.parse(str, new ParsePosition(0)); if (num.doubleValue() != -9.223372036854776E16) { - errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); + fail("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue()); } Locale.setDefault(savedLocale); @@ -447,6 +465,7 @@ /** * DecimalFormat: Negative format ignored. */ + @Test public void Test4092480 () { DecimalFormat dfFoo = new DecimalFormat("000"); @@ -454,28 +473,28 @@ try { dfFoo.applyPattern("0000;-000"); if (!dfFoo.toPattern().equals("#0000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("000;-000"); if (!dfFoo.toPattern().equals("#000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("000;-0000"); if (!dfFoo.toPattern().equals("#000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); dfFoo.applyPattern("0000;-000"); if (!dfFoo.toPattern().equals("#0000")) - errln("dfFoo.toPattern : " + dfFoo.toPattern()); - logln(dfFoo.format(42)); - logln(dfFoo.format(-42)); + fail("dfFoo.toPattern : " + dfFoo.toPattern()); + System.out.println(dfFoo.format(42)); + System.out.println(dfFoo.format(-42)); } catch (Exception foo) { - errln("Message " + foo.getMessage()); + fail("Message " + foo.getMessage()); } } /** @@ -486,6 +505,7 @@ * never contain the monetary separator! Decimal separator in pattern is * interpreted as monetary separator if currency symbol is seen! */ + @Test public void Test4087244 () { Locale de = new Locale("pt", "PT"); DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de); @@ -496,7 +516,7 @@ char monSep = sym.getMonetaryDecimalSeparator(); char zero = sym.getZeroDigit(); if (decSep == monSep) { - errln("ERROR in test: want decimal sep != monetary sep"); + fail("ERROR in test: want decimal sep != monetary sep"); } else { df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(2); @@ -504,10 +524,10 @@ String monStr = "1" + monSep + "23"; String decStr = "1" + decSep + "23"; if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) { - logln("OK: 1.23 -> \"" + str + "\" contains \"" + + System.out.println("OK: 1.23 -> \"" + str + "\" contains \"" + monStr + "\" and not \"" + decStr + '"'); } else { - errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" + + fail("FAIL: 1.23 -> \"" + str + "\", should contain \"" + monStr + "\" and not \"" + decStr + '"'); } @@ -516,6 +536,7 @@ /** * Number format data rounding errors for locale FR */ + @Test public void Test4070798 () { NumberFormat formatter; String tempString; @@ -533,9 +554,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4070798 default test passed."); + System.out.println("Bug 4070798 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -545,9 +566,9 @@ tempString = formatter.format( 5789.9876 ); if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4070798 currency test assed."); + System.out.println("Bug 4070798 currency test assed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -557,9 +578,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4070798 percentage test passed."); + System.out.println("Bug 4070798 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -567,6 +588,7 @@ /** * Data rounding errors for French (Canada) locale */ + @Test public void Test4071005 () { NumberFormat formatter; @@ -584,9 +606,9 @@ formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH); tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071005 default test passed."); + System.out.println("Bug 4071005 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -595,9 +617,9 @@ tempString = formatter.format( 5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071005 currency test passed."); + System.out.println("Bug 4071005 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -605,9 +627,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071005 percentage test passed."); + System.out.println("Bug 4071005 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -616,6 +638,7 @@ /** * Data rounding errors for German (Germany) locale */ + @Test public void Test4071014 () { NumberFormat formatter; String tempString; @@ -632,9 +655,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071014 default test passed."); + System.out.println("Bug 4071014 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -643,9 +666,9 @@ tempString = formatter.format( 5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071014 currency test passed."); + System.out.println("Bug 4071014 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -654,9 +677,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071014 percentage test passed."); + System.out.println("Bug 4071014 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -665,6 +688,7 @@ /** * Data rounding errors for Italian locale number formats */ + @Test public void Test4071859 () { NumberFormat formatter; String tempString; @@ -681,9 +705,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedDefault)) { - logln ("Bug 4071859 default test passed."); + System.out.println("Bug 4071859 default test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedDefault + " Received " + tempString ); } @@ -692,9 +716,9 @@ tempString = formatter.format( -5789.9876 ) ; if (tempString.equals(expectedCurrency) ) { - logln ("Bug 4071859 currency test passed."); + System.out.println("Bug 4071859 currency test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedCurrency + " Received " + tempString ); } @@ -703,9 +727,9 @@ tempString = formatter.format (-5789.9876); if (tempString.equals(expectedPercent) ) { - logln ("Bug 4071859 percentage test passed."); + System.out.println("Bug 4071859 percentage test passed."); } else { - errln("Failed:" + + fail("Failed:" + " Expected " + expectedPercent + " Received " + tempString ); } @@ -715,6 +739,7 @@ /* bug 4071859 * Test rounding for nearest even. */ + @Test public void Test4093610() { Locale savedLocale = Locale.getDefault(); @@ -739,20 +764,21 @@ void roundingTest(DecimalFormat df, double x, String expected) { String out = df.format(x); - logln("" + x + " formats with 1 fractional digits to " + out); - if (!out.equals(expected)) errln("FAIL: Expected " + expected); + System.out.println("" + x + " formats with 1 fractional digits to " + out); + if (!out.equals(expected)) fail("FAIL: Expected " + expected); } /** * Tests the setMaximumFractionDigits limit. */ + @Test public void Test4098741() { try { NumberFormat fmt = NumberFormat.getPercentInstance(); fmt.setMaximumFractionDigits(20); - logln(fmt.format(.001)); + System.out.println(fmt.format(.001)); } catch (Exception foo) { - errln("Bug 4098471 failed with exception thrown : " + foo.getMessage()); + fail("Bug 4098471 failed with exception thrown : " + foo.getMessage()); } } /** @@ -760,19 +786,20 @@ * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated. * Part2 has been fixed. */ + @Test public void Test4074454() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); try { DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#"); - logln("Inconsistent negative pattern is fine."); + System.out.println("Inconsistent negative pattern is fine."); DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces"); String tempString = newFmt.format(3456.78); if (!tempString.equals("3,456.78 p'ieces")) - errln("Failed! 3,456.78 p'ieces expected, but got : " + tempString); + fail("Failed! 3,456.78 p'ieces expected, but got : " + tempString); } catch (Exception foo) { - errln("An exception was thrown for any inconsistent negative pattern."); + fail("An exception was thrown for any inconsistent negative pattern."); } Locale.setDefault(savedLocale); } @@ -796,46 +823,50 @@ * Otherwise, an IllegalArgumentException will be thrown when formatting * "January 35". See GregorianCalendar class javadoc for more details. */ + @Test public void Test4099404() { try { DecimalFormat fmt = new DecimalFormat("000.0#0"); - errln("Bug 4099404 failed applying illegal pattern \"000.0#0\""); + fail("Bug 4099404 failed applying illegal pattern \"000.0#0\""); } catch (Exception foo) { - logln("Bug 4099404 pattern \"000.0#0\" passed"); + System.out.println("Bug 4099404 pattern \"000.0#0\" passed"); } try { DecimalFormat fmt = new DecimalFormat("0#0.000"); - errln("Bug 4099404 failed applying illegal pattern \"0#0.000\""); + fail("Bug 4099404 failed applying illegal pattern \"0#0.000\""); } catch (Exception foo) { - logln("Bug 4099404 pattern \"0#0.000\" passed"); + System.out.println("Bug 4099404 pattern \"0#0.000\" passed"); } } /** * DecimalFormat.applyPattern doesn't set minimum integer digits */ + @Test public void Test4101481() { DecimalFormat sdf = new DecimalFormat("#,##0"); if (sdf.getMinimumIntegerDigits() != 1) - errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits()); + fail("Minimum integer digits : " + sdf.getMinimumIntegerDigits()); } /** * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition(). */ + @Test public void Test4052223() { try { DecimalFormat fmt = new DecimalFormat("#,#00.00"); Number num = fmt.parse("abc3"); - errln("Bug 4052223 failed : can't parse string \"a\". Got " + num); + fail("Bug 4052223 failed : can't parse string \"a\". Got " + num); } catch (ParseException foo) { - logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset()); + System.out.println("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset()); } } /** * API tests for API addition request A9. */ + @Test public void Test4061302() { DecimalFormatSymbols fmt = DecimalFormatSymbols.getInstance(); @@ -845,9 +876,9 @@ if (currency.equals("") || intlCurrency.equals("") || monDecSeparator == 0) { - errln("getCurrencySymbols failed, got empty string."); + fail("getCurrencySymbols failed, got empty string."); } - logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); + System.out.println("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); fmt.setCurrencySymbol("XYZ"); fmt.setInternationalCurrencySymbol("ABC"); fmt.setMonetaryDecimalSeparator('*'); @@ -857,14 +888,15 @@ if (!currency.equals("XYZ") || !intlCurrency.equals("ABC") || monDecSeparator != '*') { - errln("setCurrencySymbols failed."); + fail("setCurrencySymbols failed."); } - logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); + System.out.println("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator); } /** * API tests for API addition request A23. FieldPosition.getBeginIndex and * FieldPosition.getEndIndex. */ + @Test public void Test4062486() { DecimalFormat fmt = new DecimalFormat("#,##0.00"); @@ -873,16 +905,17 @@ Double num = 1234.5; fmt.format(num, formatted, field); if (field.getBeginIndex() != 0 && field.getEndIndex() != 5) - errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); + fail("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); field.setBeginIndex(7); field.setEndIndex(4); if (field.getBeginIndex() != 7 && field.getEndIndex() != 4) - errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); + fail("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex()); } /** * DecimalFormat.parse incorrectly works with a group separator. */ + @Test public void Test4108738() { @@ -891,16 +924,17 @@ String text = "1.222,111"; Number num = df.parse(text,new ParsePosition(0)); if (!num.toString().equals("1.222")) - errln("\"" + text + "\" is parsed as " + num); + fail("\"" + text + "\" is parsed as " + num); text = "1.222x111"; num = df.parse(text,new ParsePosition(0)); if (!num.toString().equals("1.222")) - errln("\"" + text + "\" is parsed as " + num); + fail("\"" + text + "\" is parsed as " + num); } /** * DecimalFormat.format() incorrectly formats negative doubles. */ + @Test public void Test4106658() { Locale savedLocale = Locale.getDefault(); @@ -909,15 +943,15 @@ double d1 = -0.0; double d2 = -0.0001; StringBuffer buffer = new StringBuffer(); - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); df.format(d1, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d1 + " is formatted as " + buffer); + fail(d1 + " is formatted as " + buffer); } buffer.setLength(0); df.format(d2, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d2 + " is formatted as " + buffer); + fail(d2 + " is formatted as " + buffer); } Locale.setDefault(savedLocale); } @@ -925,40 +959,43 @@ /** * DecimalFormat.parse returns 0 if string parameter is incorrect. */ + @Test public void Test4106662() { DecimalFormat df = new DecimalFormat(); String text = "x"; ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0); - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); Number num = df.parse(text, pos1); if (num != null) { - errln("Test Failed: \"" + text + "\" is parsed as " + num); + fail("Test Failed: \"" + text + "\" is parsed as " + num); } df = null; df = new DecimalFormat("$###.00"); num = df.parse("$", pos2); if (num != null){ - errln("Test Failed: \"$\" is parsed as " + num); + fail("Test Failed: \"$\" is parsed as " + num); } } /** * NumberFormat.parse doesn't return null */ + @Test public void Test4114639() { NumberFormat format = NumberFormat.getInstance(); String text = "time 10:x"; ParsePosition pos = new ParsePosition(8); Number result = format.parse(text, pos); - if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't + if (result != null) fail("Should return null but got : " + result); // Should be null; it isn't } /** * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG. */ + @Test public void Test4106664() { DecimalFormat df = new DecimalFormat(); @@ -968,13 +1005,14 @@ bigN = bigN.multiply(BigInteger.valueOf(m)); df.setMultiplier(m); df.setGroupingUsed(false); - logln("formated: " + + System.out.println("formated: " + df.format(n, new StringBuffer(), new FieldPosition(0))); - logln("expected: " + bigN.toString()); + System.out.println("expected: " + bigN.toString()); } /** * DecimalFormat.format incorrectly formats -0.0. */ + @Test public void Test4106667() { Locale savedLocale = Locale.getDefault(); @@ -982,11 +1020,11 @@ DecimalFormat df = new DecimalFormat(); df.setPositivePrefix("+"); double d = -0.0; - logln("pattern: \"" + df.toPattern() + "\""); + System.out.println("pattern: \"" + df.toPattern() + "\""); StringBuffer buffer = new StringBuffer(); df.format(d, buffer, new FieldPosition(0)); if (!buffer.toString().equals("-0")) { // Corrected; see 4147706 - errln(d + " is formatted as " + buffer); + fail(d + " is formatted as " + buffer); } Locale.setDefault(savedLocale); } @@ -994,13 +1032,14 @@ /** * DecimalFormat.setMaximumIntegerDigits() works incorrectly. */ + @Test public void Test4110936() { NumberFormat nf = NumberFormat.getInstance(); nf.setMaximumIntegerDigits(128); - logln("setMaximumIntegerDigits(128)"); + System.out.println("setMaximumIntegerDigits(128)"); if (nf.getMaximumIntegerDigits() != 128) - errln("getMaximumIntegerDigits() returns " + + fail("getMaximumIntegerDigits() returns " + nf.getMaximumIntegerDigits()); } @@ -1011,6 +1050,7 @@ * 2) Make sure we get the same results using the generic symbol or a * hard-coded one. */ + @Test public void Test4122840() { Locale[] locales = NumberFormat.getAvailableLocales(); @@ -1027,7 +1067,7 @@ String pattern = numPatterns[1]; if (pattern.indexOf("\u00A4") == -1 ) { - errln("Currency format for " + locales[i] + + fail("Currency format for " + locales[i] + " does not contain generic currency symbol:" + pattern ); } @@ -1058,7 +1098,7 @@ String result2 = fmt2.format(1.111); if (!result1.equals(result2)) { - errln("Results for " + locales[i] + " differ: " + + fail("Results for " + locales[i] + " differ: " + result1 + " vs " + result2); } } @@ -1067,23 +1107,24 @@ /** * DecimalFormat.format() delivers wrong string. */ + @Test public void Test4125885() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); double rate = 12.34; DecimalFormat formatDec = new DecimalFormat ("000.00"); - logln("toPattern: " + formatDec.toPattern()); + System.out.println("toPattern: " + formatDec.toPattern()); String rateString= formatDec.format(rate); if (!rateString.equals("012.34")) - errln("result : " + rateString + " expected : 012.34"); + fail("result : " + rateString + " expected : 012.34"); rate = 0.1234; formatDec = null; formatDec = new DecimalFormat ("+000.00%;-000.00%"); - logln("toPattern: " + formatDec.toPattern()); + System.out.println("toPattern: " + formatDec.toPattern()); rateString= formatDec.format(rate); if (!rateString.equals("+012.34%")) - errln("result : " + rateString + " expected : +012.34%"); + fail("result : " + rateString + " expected : +012.34%"); Locale.setDefault(savedLocale); } @@ -1091,16 +1132,17 @@ ** * DecimalFormat produces extra zeros when formatting numbers. */ + @Test public void Test4134034() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); DecimalFormat nf = new DecimalFormat("##,###,###.00"); String f = nf.format(9.02); - if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02"); + if (f.equals("9.02")) System.out.println(f + " ok"); else fail("9.02 -> " + f + "; want 9.02"); f = nf.format(0); - if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00"); + if (f.equals(".00")) System.out.println(f + " ok"); else fail("0 -> " + f + "; want .00"); Locale.setDefault(savedLocale); } @@ -1128,6 +1170,7 @@ * Value 1.2 Format #0.0# Result '1.2' * Value 1.2 Format #0.00 Result '1.20' */ + @Test public void Test4134300() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1142,11 +1185,11 @@ for (int i=0; i " + s); + fail("Fail: Format empty pattern x 123.456 => " + s); s = f.format(-123.456); if (!s.equals("-123.456")) - errln("Fail: Format empty pattern x -123.456 => " + s); + fail("Fail: Format empty pattern x -123.456 => " + s); } } /** * BigDecimal numbers get their fractions truncated by NumberFormat. */ + @Test public void Test4141750() { try { String str = "12345.67"; @@ -1188,11 +1233,11 @@ NumberFormat nf = NumberFormat.getInstance(Locale.US); String sd = nf.format(bd); if (!sd.endsWith("67")) { - errln("Fail: " + str + " x format -> " + sd); + fail("Fail: " + str + " x format -> " + sd); } } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); e.printStackTrace(); } } @@ -1201,6 +1246,7 @@ * DecimalFormat toPattern() doesn't quote special characters or handle * single quotes. */ + @Test public void Test4145457() { try { DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(); @@ -1223,25 +1269,25 @@ double val2 = nf.parse(out2).doubleValue(); if (!pat.equals(pat2)) - errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" + + fail("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" + pat + "\" vs. \"" + pat2 + "\""); else - logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"'); + System.out.println("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"'); if (val == val2 && out.equals(out2)) { - logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" + + System.out.println("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" + out + "\" -> " + val + " -> \"" + out2 + "\" -> " + val2); } else { - errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" + + fail("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" + out + "\" -> " + val + " -> \"" + out2 + "\" -> " + val2); } } } catch (ParseException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } } @@ -1251,19 +1297,20 @@ * CANNOT REPRODUCE * This bug is a duplicate of 4139344, which is a duplicate of 4134300 */ + @Test public void Test4147295() { DecimalFormat sdf = new DecimalFormat(); String pattern = "#,###"; - logln("Applying pattern \"" + pattern + "\""); + System.out.println("Applying pattern \"" + pattern + "\""); sdf.applyPattern(pattern); int minIntDig = sdf.getMinimumIntegerDigits(); if (minIntDig != 0) { - errln("Test failed"); - errln(" Minimum integer digits : " + minIntDig); - errln(" new pattern: " + sdf.toPattern()); + fail("Test failed" + + "\n Minimum integer digits : " + minIntDig + + "\n new pattern: " + sdf.toPattern()); } else { - logln("Test passed"); - logln(" Minimum integer digits : " + minIntDig); + System.out.println("Test passed"); + System.out.println(" Minimum integer digits : " + minIntDig); } } @@ -1271,6 +1318,7 @@ * DecimalFormat formats -0.0 as +0.0 * See also older related bug 4106658, 4106667 */ + @Test public void Test4147706() { DecimalFormat df = new DecimalFormat("#,##0.0##"); df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH)); @@ -1279,39 +1327,41 @@ StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0)); StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0)); if (!f1.toString().equals("-0.0")) { - errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"'); + fail(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"'); } if (!f2.toString().equals("-0.0")) { - errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"'); + fail(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"'); } } /** * NumberFormat cannot format Double.MAX_VALUE */ + @Test public void Test4162198() { double dbl = Double.MAX_VALUE; NumberFormat f = NumberFormat.getInstance(); f.setMaximumFractionDigits(Integer.MAX_VALUE); f.setMaximumIntegerDigits(Integer.MAX_VALUE); String s = f.format(dbl); - logln("The number " + dbl + " formatted to " + s); + System.out.println("The number " + dbl + " formatted to " + s); Number n = null; try { n = f.parse(s); } catch (java.text.ParseException e) { - errln("Caught a ParseException:"); + fail("Caught a ParseException:"); e.printStackTrace(); } - logln("The string " + s + " parsed as " + n); + System.out.println("The string " + s + " parsed as " + n); if (n.doubleValue() != dbl) { - errln("Round trip failure"); + fail("Round trip failure"); } } /** * NumberFormat does not parse negative zero. */ + @Test public void Test4162852() throws ParseException { for (int i=0; i<2; ++i) { NumberFormat f = (i == 0) ? NumberFormat.getInstance() @@ -1319,12 +1369,12 @@ double d = -0.0; String s = f.format(d); double e = f.parse(s).doubleValue(); - logln("" + + System.out.println("" + d + " -> " + '"' + s + '"' + " -> " + e); if (e != 0.0 || 1.0/e > 0.0) { - logln("Failed to parse negative zero"); + System.out.println("Failed to parse negative zero"); } } } @@ -1332,6 +1382,7 @@ /** * NumberFormat truncates data */ + @Test public void Test4167494() throws Exception { NumberFormat fmt = NumberFormat.getInstance(Locale.US); @@ -1340,9 +1391,9 @@ double b = fmt.parse(s).doubleValue(); boolean match = a == b; if (match) { - logln("" + a + " -> \"" + s + "\" -> " + b + " ok"); + System.out.println("" + a + " -> \"" + s + "\" -> " + b + " ok"); } else { - errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); + fail("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); } // We don't test Double.MIN_VALUE because the locale data for the US @@ -1355,9 +1406,9 @@ b = fmt.parse(s).doubleValue(); match = a == b; if (match) { - logln("" + a + " -> \"" + s + "\" -> " + b + " ok"); + System.out.println("" + a + " -> \"" + s + "\" -> " + b + " ok"); } else { - errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); + fail("" + a + " -> \"" + s + "\" -> " + b + " FAIL"); } } } @@ -1365,6 +1416,7 @@ /** * DecimalFormat.parse() fails when ParseIntegerOnly set to true */ + @Test public void Test4170798() { Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1373,7 +1425,7 @@ Number n = df.parse("-0.0", new ParsePosition(0)); if (!(n instanceof Long || n instanceof Integer) || n.intValue() != 0) { - errln("FAIL: parse(\"-0.0\") returns " + + fail("FAIL: parse(\"-0.0\") returns " + n + " (" + n.getClass().getName() + ')'); } Locale.setDefault(savedLocale); @@ -1382,6 +1434,7 @@ /** * toPattern only puts the first grouping separator in. */ + @Test public void Test4176114() { String[] DATA = { "00", "#00", @@ -1398,7 +1451,7 @@ DecimalFormat df = new DecimalFormat(DATA[i]); String s = df.toPattern(); if (!s.equals(DATA[i+1])) { - errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]); + fail("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]); } } } @@ -1406,6 +1459,7 @@ /** * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2 */ + @Test public void Test4179818() { String DATA[] = { // Input Pattern Expected output @@ -1422,14 +1476,15 @@ fmt.applyPattern(pat); String out = fmt.format(in); if (out.equals(exp)) { - logln("Ok: " + in + " x " + pat + " = " + out); + System.out.println("Ok: " + in + " x " + pat + " = " + out); } else { - errln("FAIL: " + in + " x " + pat + " = " + out + + fail("FAIL: " + in + " x " + pat + " = " + out + ", expected " + exp); } } } + @Test public void Test4185761() throws IOException, ClassNotFoundException { /* Code used to write out the initial files, which are * then edited manually: @@ -1456,13 +1511,13 @@ ObjectInputStream p = new ObjectInputStream(istream); try { NumberFormat nf = (NumberFormat) p.readObject(); - errln("FAIL: Deserialized bogus NumberFormat int:" + + fail("FAIL: Deserialized bogus NumberFormat int:" + nf.getMinimumIntegerDigits() + ".." + nf.getMaximumIntegerDigits() + " frac:" + nf.getMinimumFractionDigits() + ".." + nf.getMaximumFractionDigits()); } catch (InvalidObjectException e) { - logln("Ok: " + e.getMessage()); + System.out.println("Ok: " + e.getMessage()); } istream.close(); @@ -1470,13 +1525,13 @@ p = new ObjectInputStream(istream); try { NumberFormat nf = (NumberFormat) p.readObject(); - errln("FAIL: Deserialized bogus DecimalFormat int:" + + fail("FAIL: Deserialized bogus DecimalFormat int:" + nf.getMinimumIntegerDigits() + ".." + nf.getMaximumIntegerDigits() + " frac:" + nf.getMinimumFractionDigits() + ".." + nf.getMaximumFractionDigits()); } catch (InvalidObjectException e) { - logln("Ok: " + e.getMessage()); + System.out.println("Ok: " + e.getMessage()); } istream.close(); } @@ -1488,6 +1543,7 @@ * symbol, percent, and permille. This is filed as bugs 4212072 and * 4212073. */ + @Test public void Test4212072() throws IOException, ClassNotFoundException { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); DecimalFormat fmt = new DecimalFormat("#", sym); @@ -1495,11 +1551,11 @@ sym.setMinusSign('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(-1).equals("^1")) { - errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) + + fail("FAIL: -1 x (minus=^) -> " + fmt.format(-1) + ", exp ^1"); } if (!fmt.getNegativePrefix().equals("^")) { - errln("FAIL: (minus=^).getNegativePrefix -> " + + fail("FAIL: (minus=^).getNegativePrefix -> " + fmt.getNegativePrefix() + ", exp ^"); } sym.setMinusSign('-'); @@ -1508,11 +1564,11 @@ sym.setPercent('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(0.25).equals("25^")) { - errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) + + fail("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) + ", exp 25^"); } if (!fmt.getPositiveSuffix().equals("^")) { - errln("FAIL: (percent=^).getPositiveSuffix -> " + + fail("FAIL: (percent=^).getPositiveSuffix -> " + fmt.getPositiveSuffix() + ", exp ^"); } sym.setPercent('%'); @@ -1521,11 +1577,11 @@ sym.setPerMill('^'); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(0.25).equals("250^")) { - errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) + + fail("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) + ", exp 250^"); } if (!fmt.getPositiveSuffix().equals("^")) { - errln("FAIL: (permill=^).getPositiveSuffix -> " + + fail("FAIL: (permill=^).getPositiveSuffix -> " + fmt.getPositiveSuffix() + ", exp ^"); } sym.setPerMill('\u2030'); @@ -1534,11 +1590,11 @@ sym.setCurrencySymbol("usd"); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(12.5).equals("usd12.50")) { - errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) + + fail("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) + ", exp usd12.50"); } if (!fmt.getPositivePrefix().equals("usd")) { - errln("FAIL: (currency=usd).getPositivePrefix -> " + + fail("FAIL: (currency=usd).getPositivePrefix -> " + fmt.getPositivePrefix() + ", exp usd"); } sym.setCurrencySymbol("$"); @@ -1547,11 +1603,11 @@ sym.setInternationalCurrencySymbol("DOL"); fmt.setDecimalFormatSymbols(sym); if (!fmt.format(12.5).equals("DOL12.50")) { - errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) + + fail("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) + ", exp DOL12.50"); } if (!fmt.getPositivePrefix().equals("DOL")) { - errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " + + fail("FAIL: (intlcurrency=DOL).getPositivePrefix -> " + fmt.getPositivePrefix() + ", exp DOL"); } sym.setInternationalCurrencySymbol("USD"); @@ -1580,7 +1636,7 @@ DecimalFormatSymbols symb = DecimalFormatSymbols.getInstance(avail[i]); DecimalFormat f2 = new DecimalFormat(pat, symb); if (!df.equals(f2)) { - errln("FAIL: " + avail[i] + " -> \"" + pat + + fail("FAIL: " + avail[i] + " -> \"" + pat + "\" -> \"" + f2.toPattern() + '"'); } @@ -1588,7 +1644,7 @@ pat = df.toLocalizedPattern(); f2.applyLocalizedPattern(pat); if (!df.equals(f2)) { - errln("FAIL: " + avail[i] + " -> localized \"" + pat + + fail("FAIL: " + avail[i] + " -> localized \"" + pat + "\" -> \"" + f2.toPattern() + '"'); } @@ -1603,7 +1659,7 @@ new ObjectInputStream(new ByteArrayInputStream(bytes)); f2 = (DecimalFormat) ois.readObject(); if (!df.equals(f2)) { - errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat + + fail("FAIL: Stream in/out " + avail[i] + " -> \"" + pat + "\" -> " + (f2 != null ? ("\""+f2.toPattern()+'"') : "null")); } @@ -1615,6 +1671,7 @@ /** * DecimalFormat.parse() fails for mulipliers 2^n. */ + @Test public void Test4216742() throws ParseException { DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US); long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L}; @@ -1624,7 +1681,7 @@ fmt.setMultiplier(m); long n = fmt.parse(str).longValue(); if (n > 0 != DATA[i] > 0) { - errln("\"" + str + "\" parse(x " + fmt.getMultiplier() + + fail("\"" + str + "\" parse(x " + fmt.getMultiplier() + ") => " + n); } } @@ -1635,6 +1692,7 @@ * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction * digits. */ + @Test public void Test4217661() { Object[] DATA = { 0.001, "0", @@ -1647,7 +1705,7 @@ for (int i=0; i 0 && args[0].equals("-debug")) { - DEBUG = true; - String[] newargs = new String[args.length - 1]; - System.arraycopy(args, 1, newargs, 0, newargs.length); - args = newargs; - } - new NumberRoundTrip().run(args); - } - + @Test public void TestNumberFormatRoundTrip() { - logln("Default Locale"); + System.out.println("Default Locale"); localeName = "Default Locale"; formatName = "getInstance"; doTest(NumberFormat.getInstance()); @@ -74,7 +70,7 @@ Locale[] loc = NumberFormat.getAvailableLocales(); for (int i=0; i " + escape(s)); + System.out.println(" " + value + " F> " + escape(s)); n = fmt.parse(s); - if (DEBUG) logln(" " + escape(s) + " P> " + n); + System.out.println(" " + escape(s) + " P> " + n); s2 = fmt.format(n); - if (DEBUG) logln(" " + n + " F> " + escape(s2)); + System.out.println(" " + n + " F> " + escape(s2)); if (STRING_COMPARE) { if (!s.equals(s2)) { if (fmt instanceof DecimalFormat) { - logln("Text mismatch: expected: " + s + ", got: " + s2 + " --- Try BigDecimal parsing."); + System.out.println("Text mismatch: expected: " + s + ", got: " + s2 + " --- Try BigDecimal parsing."); ((DecimalFormat)fmt).setParseBigDecimal(true); n = fmt.parse(s); - if (DEBUG) logln(" " + escape(s) + " P> " + n); + System.out.println(" " + escape(s) + " P> " + n); s2 = fmt.format(n); - if (DEBUG) logln(" " + n + " F> " + escape(s2)); + System.out.println(" " + n + " F> " + escape(s2)); ((DecimalFormat)fmt).setParseBigDecimal(false); if (!s.equals(s2)) { @@ -197,14 +193,14 @@ n + typeOf(n) + " F> " + escape(s2); if (err.length() > 0) { - errln("*** " + err + " with " + + fail("*** " + err + " with " + formatName + " in " + localeName + " " + message); } else { - logln(message); + System.out.println(message); } } catch (ParseException e) { - errln("*** " + e.toString() + " with " + + fail("*** " + e.toString() + " with " + formatName + " in " + localeName); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/NumberTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/NumberTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/NumberTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,24 +25,24 @@ * @test * @bug 4122840 4135202 4408066 4838107 8008577 * @summary test NumberFormat - * @library /java/text/testlib * @modules java.base/sun.util.resources * jdk.localedata * @compile -XDignore.symbol.file NumberTest.java - * @run main/othervm -Djava.locale.providers=COMPAT,SPI NumberTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI NumberTest */ import java.util.*; import java.text.*; import sun.util.resources.LocaleData; -public class NumberTest extends IntlTest -{ - public static void main(String[] args) throws Exception { - new NumberTest().run(args); - } +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.fail; + +public class NumberTest +{ // Test pattern handling + @Test public void TestPatterns() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); @@ -54,20 +54,21 @@ DecimalFormat fmt = new DecimalFormat(pat[i], sym); String newp = fmt.toPattern(); if (!newp.equals(newpat[i])) - errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + + fail("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); String s = fmt.format(0); if (!s.equals(num[i])) { - errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + + fail("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); - logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); + System.out.println("Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } // Test exponential pattern + @Test public void TestExponential() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); String pat[] = { "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; @@ -100,14 +101,14 @@ int ival = 0, ilval = 0; for (int p=0; p \"" + + System.out.println("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + '"'); for (int v=0; v " + escape(s)); + System.out.println(" Format " + val[v] + " -> " + escape(s)); if (!s.equals(valFormat[v+ival])) { - errln("FAIL: Expected " + valFormat[v+ival] + + fail("FAIL: Expected " + valFormat[v+ival] + ", got " + s + ", pattern=" + fmt.toPattern()); } @@ -115,22 +116,22 @@ ParsePosition pos = new ParsePosition(0); Number a = fmt.parse(s, pos); if (pos.getIndex() == s.length()) { - logln(" Parse -> " + a); + System.out.println(" Parse -> " + a); if (a.doubleValue() != valParse[v+ival]) { - errln("FAIL: Expected " + valParse[v+ival] + + fail("FAIL: Expected " + valParse[v+ival] + ", got " + a.doubleValue() + ", pattern=" + fmt.toPattern()); } } else { - errln(" FAIL: Partial parse (" + pos.getIndex() + + fail(" FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } } for (int v=0; v " + escape(s)); + System.out.println(" Format " + lval[v] + "L -> " + escape(s)); if (!s.equals(lvalFormat[v+ilval])) { - errln("ERROR: Expected " + lvalFormat[v+ilval] + + fail("ERROR: Expected " + lvalFormat[v+ilval] + ", got " + s + ", pattern=" + fmt.toPattern()); } @@ -138,14 +139,14 @@ ParsePosition pos = new ParsePosition(0); Number a = fmt.parse(s, pos); if (pos.getIndex() == s.length()) { - logln(" Parse -> " + a); + System.out.println(" Parse -> " + a); if (a.longValue() != lvalParse[v+ilval]) { - errln("FAIL: Expected " + lvalParse[v+ilval] + + fail("FAIL: Expected " + lvalParse[v+ilval] + ", got " + a + ", pattern=" + fmt.toPattern()); } } else { - errln(" FAIL: Partial parse (" + pos.getIndex() + + fail(" FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } } @@ -155,24 +156,26 @@ } // Test the handling of quotes + @Test public void TestQuotes() { String pat; DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); DecimalFormat fmt = new DecimalFormat(pat = "a'fo''o'b#", sym); String s = fmt.format(123); - logln("Pattern \"" + pat + "\""); - logln(" Format 123 -> " + escape(s)); - if (!s.equals("afo'ob123")) errln("FAIL: Expected afo'ob123"); + System.out.println("Pattern \"" + pat + "\""); + System.out.println(" Format 123 -> " + escape(s)); + if (!s.equals("afo'ob123")) fail("FAIL: Expected afo'ob123"); fmt = new DecimalFormat(pat = "a''b#", sym); s = fmt.format(123); - logln("Pattern \"" + pat + "\""); - logln(" Format 123 -> " + escape(s)); - if (!s.equals("a'b123")) errln("FAIL: Expected a'b123"); + System.out.println("Pattern \"" + pat + "\""); + System.out.println(" Format 123 -> " + escape(s)); + if (!s.equals("a'b123")) fail("FAIL: Expected a'b123"); } // Test the use of the currency sign + @Test public void TestCurrencySign() { DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US); @@ -181,21 +184,21 @@ // DecimalFormatSymbols sym = fmt.getDecimalFormatSymbols(); String s = fmt.format(1234.56); - logln("Pattern \"" + fmt.toPattern() + "\""); - logln(" Format " + 1234.56 + " -> " + escape(s)); - if (!s.equals("$1,234.56")) errln("FAIL: Expected $1,234.56"); + System.out.println("Pattern \"" + fmt.toPattern() + "\""); + System.out.println(" Format " + 1234.56 + " -> " + escape(s)); + if (!s.equals("$1,234.56")) fail("FAIL: Expected $1,234.56"); s = fmt.format(-1234.56); - logln(" Format " + -1234.56 + " -> " + escape(s)); - if (!s.equals("-$1,234.56")) errln("FAIL: Expected -$1,234.56"); + System.out.println(" Format " + -1234.56 + " -> " + escape(s)); + if (!s.equals("-$1,234.56")) fail("FAIL: Expected -$1,234.56"); fmt = new DecimalFormat("\u00A4\u00A4 #,##0.00;\u00A4\u00A4 -#,##0.00", sym); s = fmt.format(1234.56); - logln("Pattern \"" + fmt.toPattern() + "\""); - logln(" Format " + 1234.56 + " -> " + escape(s)); - if (!s.equals("USD 1,234.56")) errln("FAIL: Expected USD 1,234.56"); + System.out.println("Pattern \"" + fmt.toPattern() + "\""); + System.out.println(" Format " + 1234.56 + " -> " + escape(s)); + if (!s.equals("USD 1,234.56")) fail("FAIL: Expected USD 1,234.56"); s = fmt.format(-1234.56); - logln(" Format " + -1234.56 + " -> " + escape(s)); - if (!s.equals("USD -1,234.56")) errln("FAIL: Expected USD -1,234.56"); + System.out.println(" Format " + -1234.56 + " -> " + escape(s)); + if (!s.equals("USD -1,234.56")) fail("FAIL: Expected USD -1,234.56"); } static String escape(String s) { @@ -219,25 +222,26 @@ // Test simple currency format // Bug 4024941; this code used to throw a NumberFormat exception + @Test public void TestCurrency() { NumberFormat currencyFmt = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH); String s = currencyFmt.format(1.50); - logln("Un pauvre ici a..........." + s); + System.out.println("Un pauvre ici a..........." + s); if (!s.equals("1,50 $")) { - errln("FAIL: Expected 1,50 $; got " + s + "; "+ dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 $; got " + s + "; "+ dumpFmt(currencyFmt)); } currencyFmt = NumberFormat.getCurrencyInstance(Locale.GERMANY); s = currencyFmt.format(1.50); - logln("Un pauvre en Allemagne a.." + s); + System.out.println("Un pauvre en Allemagne a.." + s); if (!s.equals("1,50 \u20AC")) { - errln("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); } currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE); s = currencyFmt.format(1.50); - logln("Un pauvre en France a....." + s); + System.out.println("Un pauvre en France a....." + s); if (!s.equals("1,50 \u20AC")) { - errln("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); + fail("FAIL: Expected 1,50 \u20AC; got " + s + "; " + dumpFmt(currencyFmt)); } } @@ -254,18 +258,20 @@ // Test numeric parsing // Bug 4059870 + @Test public void TestParse() { String arg = "0"; java.text.DecimalFormat format = new java.text.DecimalFormat("00"); try { Number n = format.parse(arg); - logln("parse(" + arg + ") = " + n); - if (n.doubleValue() != 0.0) errln("FAIL: Expected 0"); - } catch (Exception e) { errln("Exception caught: " + e); } + System.out.println("parse(" + arg + ") = " + n); + if (n.doubleValue() != 0.0) fail("FAIL: Expected 0"); + } catch (Exception e) { fail("Exception caught: " + e); } } // Test rounding + @Test public void TestRounding487() { NumberFormat nf = NumberFormat.getInstance(Locale.US); roundingTest(nf, 0.00159999, 4, "0.0016"); @@ -278,9 +284,9 @@ void roundingTest(NumberFormat nf, double x, int maxFractionDigits, String expected) { nf.setMaximumFractionDigits(maxFractionDigits); String out = nf.format(x); - logln("" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); + System.out.println("" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!out.equals(expected)) { - errln("FAIL: Expected " + expected + ", got " + out); + fail("FAIL: Expected " + expected + ", got " + out); } } @@ -292,6 +298,7 @@ * a couple. * @see java.lang.Character#isDigit(char) */ + @Test public void TestUnicodeDigits() { char[] zeros = { 0x0030, // ISO-LATIN-1 digits ('0' through '9') @@ -324,9 +331,9 @@ } catch (ParseException e) { n = -2; } if (n != 314) - errln("Can't parse Unicode " + Integer.toHexString(zero) + " as digit (" + n + ")"); + fail("Can't parse Unicode " + Integer.toHexString(zero) + " as digit (" + n + ")"); else - logln("Parse digit " + Integer.toHexString(zero) + " ok"); + System.out.println("Parse digit " + Integer.toHexString(zero) + " ok"); } } @@ -334,6 +341,7 @@ * Bug 4122840 * Make sure that the currency symbol is not hard-coded in any locale. */ + @Test public void TestCurrencySubstitution() { final String SYM = ""; final String INTL_SYM = ""; @@ -356,36 +364,37 @@ String customPos = df.format(1234.5678); String customNeg = df.format(-1234.5678); if (genericPos.equals(customPos) || genericNeg.equals(customNeg)) { - errln("FAIL: " + locales[i] + + fail("FAIL: " + locales[i] + " not using currency symbol substitution: " + genericPos); } else { if (customPos.indexOf(SYM) >= 0) { if (customNeg.indexOf(INTL_SYM) >= 0) - errln("Fail: Positive and negative patterns use different symbols"); + fail("Fail: Positive and negative patterns use different symbols"); else - logln("Ok: " + locales[i] + + System.out.println("Ok: " + locales[i] + " uses currency symbol: " + genericPos + ", " + customPos); } else if (customPos.indexOf(INTL_SYM) >= 0) { if (customNeg.indexOf(SYM) >= 0) - errln("Fail: Positive and negative patterns use different symbols"); + fail("Fail: Positive and negative patterns use different symbols"); else - logln("Ok: " + locales[i] + + System.out.println("Ok: " + locales[i] + " uses intl. currency symbol: " + genericPos + ", " + customPos); } else { - errln("FAIL: " + locales[i] + + fail("FAIL: " + locales[i] + " contains no currency symbol (impossible!)"); } } } - else logln("Skipping " + locales[i] + "; not a DecimalFormat"); + else System.out.println("Skipping " + locales[i] + "; not a DecimalFormat"); } } + @Test public void TestIntegerFormat() throws ParseException { NumberFormat format = NumberFormat.getIntegerInstance(Locale.GERMANY); @@ -395,7 +404,7 @@ for (int i = 0; i < formatInput.length; i++) { String result = format.format(formatInput[i]); if (!result.equals(formatExpected[i])) { - errln("FAIL: Expected " + formatExpected[i] + ", got " + result); + fail("FAIL: Expected " + formatExpected[i] + ", got " + result); } } @@ -405,7 +414,7 @@ for (int i = 0; i < parseInput.length; i++) { float result = format.parse(parseInput[i]).floatValue(); if (result != parseExpected[i]) { - errln("FAIL: Expected " + parseExpected[i] + ", got " + result); + fail("FAIL: Expected " + parseExpected[i] + ", got " + result); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/PositionTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/PositionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Format/NumberFormat/PositionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Format/NumberFormat/PositionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,8 +24,8 @@ /** * @test * @bug 4109023 4153060 4153061 - * @library /java/text/testlib * @summary test ParsePosition and FieldPosition + * @run junit PositionTest */ /* (C) Copyright Taligent, Inc. 1996 - All Rights Reserved @@ -42,33 +42,34 @@ import java.text.*; import java.io.*; -public class PositionTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new PositionTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class PositionTest { + @Test public void TestParsePosition() { ParsePosition pp1 = new ParsePosition(0); if (pp1.getIndex() == 0) { - logln("PP constructor() tested."); + System.out.println("PP constructor() tested."); }else{ - errln("*** PP getIndex or constructor() result"); + fail("*** PP getIndex or constructor() result"); } { int to = 5; ParsePosition pp2 = new ParsePosition ( to ); if (pp2.getIndex() == 5) { - logln("PP getIndex and constructor(TextOffset) tested."); + System.out.println("PP getIndex and constructor(TextOffset) tested."); }else{ - errln("*** PP getIndex or constructor(TextOffset) result"); + fail("*** PP getIndex or constructor(TextOffset) result"); } pp2.setIndex( 3 ); if (pp2.getIndex() == 3) { - logln("PP setIndex tested."); + System.out.println("PP setIndex tested."); }else{ - errln("*** PP getIndex or setIndex result"); + fail("*** PP getIndex or setIndex result"); } } @@ -77,37 +78,38 @@ pp3 = new ParsePosition( 5 ); ParsePosition pp4 = new ParsePosition(5); if (! pp2.equals(pp3)) { - logln("PP not equals tested."); + System.out.println("PP not equals tested."); }else{ - errln("*** PP not equals fails"); + fail("*** PP not equals fails"); } if (pp3.equals(pp4)) { - logln("PP equals tested."); + System.out.println("PP equals tested."); }else{ - errln("*** PP equals fails (" + pp3.getIndex() + " != " + pp4.getIndex() + ")"); + fail("*** PP equals fails (" + pp3.getIndex() + " != " + pp4.getIndex() + ")"); } ParsePosition pp5; pp5 = pp4; if (pp4.equals(pp5)) { - logln("PP operator= tested."); + System.out.println("PP operator= tested."); }else{ - errln("*** PP operator= operator== or operator != result"); + fail("*** PP operator= operator== or operator != result"); } } + @Test public void TestFieldPosition() { FieldPosition fp = new FieldPosition( 7 ); if (fp.getField() == 7) { - logln("FP constructor(int) and getField tested."); + System.out.println("FP constructor(int) and getField tested."); }else{ - errln("*** FP constructor(int) or getField"); + fail("*** FP constructor(int) or getField"); } FieldPosition fph = new FieldPosition( 3 ); - if ( fph.getField() != 3) errln("*** FP getField or heap constr."); + if ( fph.getField() != 3) fail("*** FP getField or heap constr."); boolean err1 = false; boolean err2 = false; @@ -121,24 +123,25 @@ // if (fp.getEndIndex() != i+7) err3 = true; // } if (!err1) { - logln("FP setField and getField tested."); + System.out.println("FP setField and getField tested."); }else{ - errln("*** FP setField or getField"); + fail("*** FP setField or getField"); } if (!err2) { - logln("FP setBeginIndex and getBeginIndex tested."); + System.out.println("FP setBeginIndex and getBeginIndex tested."); }else{ - errln("*** FP setBeginIndex or getBeginIndex"); + fail("*** FP setBeginIndex or getBeginIndex"); } if (!err3) { - logln("FP setEndIndex and getEndIndex tested."); + System.out.println("FP setEndIndex and getEndIndex tested."); }else{ - errln("*** FP setEndIndex or getEndIndex"); + fail("*** FP setEndIndex or getEndIndex"); } - logln(""); + System.out.println(""); } + @Test public void TestFieldPosition_example() { //***** no error detection yet !!!!!!! //***** this test is for compiler checks and visual verification only. @@ -164,41 +167,43 @@ tempLen : (tempLen - pos.getEndIndex()); for (int j=0; j contents = parser.parse(new BufferedReader( new FileReader(file))); List test = (List)contents.get("tests"); for (int counter = 0; counter < test.size(); counter++) { - logln("creating: " + (counter / 2)); + System.out.println("creating: " + (counter / 2)); AttributedCharacterIterator iterator = create((Map)test.get(counter)); - logln("verifying: " + (counter / 2)); + System.out.println("verifying: " + (counter / 2)); verify(iterator, (Map)test.get(++counter)); } } catch (IOException ioe) { - errln("Error reading: " + ioe); + fail("Error reading: " + ioe); } } @@ -175,20 +169,20 @@ escapeIfNecessary((String)table.get("text")))) { String text = getText(iterator); - errln("text doesn't match, got: " + getText(iterator)); + fail("text doesn't match, got: " + getText(iterator)); } if (iterator.getBeginIndex() != 0) { - errln("Bogus start: " + iterator.getBeginIndex()); + fail("Bogus start: " + iterator.getBeginIndex()); } if (iterator.getEndIndex() != length) { - errln("Bogus end: " + iterator.getEndIndex()); + fail("Bogus end: " + iterator.getEndIndex()); } for (int counter = 0; counter < length; counter++) { iterator.setIndex(counter); if (!verifyAttributes(iterator.getAttributes().keySet(), makeAttributes((List)table.get(Integer. toString(counter))))) { - errln("Attributes don't match at " + counter + " expecting " + + fail("Attributes don't match at " + counter + " expecting " + makeAttributes((List)table.get(Integer.toString (counter))) + " got " + iterator.getAttributes().keySet()); @@ -199,7 +193,7 @@ if (!verifyAttributes(iterator.getAttributes().keySet(), makeAttributes((List)table.get(Integer. toString(counter))))) { - errln("Attributes don't match at " + counter + " expecting " + + fail("Attributes don't match at " + counter + " expecting " + makeAttributes((List)table.get(Integer.toString (counter))) + " got " + iterator.getAttributes().keySet()); @@ -243,22 +237,22 @@ for (int counter = begin; counter < end; counter++) { iterator.setIndex(counter); if (iterator.getRunStart() != begin) { - errln("Begin doesn't match want " + begin + " got " + + fail("Begin doesn't match want " + begin + " got " + iterator.getRunStart() + " at " + counter + " attrs " + attrs); } if (iterator.getRunStart(attrs) != begin2) { - errln("Begin2 doesn't match want " + begin2 + " got " + + fail("Begin2 doesn't match want " + begin2 + " got " + iterator.getRunStart(attrs) + " at " + counter + " attrs " + attrs); } if (iterator.getRunLimit() != end) { - errln("End doesn't match want " + end + " got " + + fail("End doesn't match want " + end + " got " + iterator.getRunLimit() + " at " + counter + " attrs " + attrs); } if (iterator.getRunLimit(attrs) != end2) { - errln("End2 doesn't match want " + end2 + " got " + + fail("End2 doesn't match want " + end2 + " got " + iterator.getRunLimit(attrs) + " at " + counter + " attrs " + attrs); } @@ -312,15 +306,15 @@ format.format(value, buffer, fp); if (fp.getBeginIndex() != begin) { - errln("bogus begin want " + begin + " got " + fp.getBeginIndex() + + fail("bogus begin want " + begin + " got " + fp.getBeginIndex() + " for " + fp + " at " + index); } if (fp.getEndIndex() != end) { - errln("bogus end want " + end + " got " + fp.getEndIndex() + + fail("bogus end want " + end + " got " + fp.getEndIndex() + " for " + fp + " at " + index); } if (!buffer.toString().equals(text)) { - errln("Text does not match, want !" + buffer.toString() + + fail("Text does not match, want !" + buffer.toString() + "! got !" + text + "!"); } } @@ -331,11 +325,11 @@ value = createInstance((String)table.get("valueClass"), ((List)table.get("valueArgs")).toArray()); - logln("Created format: " + format + " value " + value); + System.out.println("Created format: " + format + " value " + value); AttributedCharacterIterator aci = format. formatToCharacterIterator(value); - logln("Obtained Iterator: " + aci); + System.out.println("Obtained Iterator: " + aci); return aci; } @@ -373,7 +367,7 @@ return value; } } catch (Throwable th) { - errln("Error creating instance " + th); + fail("Error creating instance " + th); return null; } } @@ -413,7 +407,7 @@ } catch (Throwable th) { error = th; } - errln("Could not lookup field " + name + " " + error); + fail("Could not lookup field " + name + " " + error); return null; } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Normalizer/ICUBasicTest.java openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/ICUBasicTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Normalizer/ICUBasicTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/ICUBasicTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,8 @@ * @summary Confirm Normalizer's fundamental behavior. Imported from ICU4J 3.2's * src/com/ibm/icu/dev/test and modified. * @modules java.base/sun.text java.base/jdk.internal.icu.text - * @library /java/text/testlib * @compile -XDignore.symbol.file ICUBasicTest.java - * @run main/timeout=30 ICUBasicTest + * @run junit/timeout=30 ICUBasicTest */ /* @@ -41,13 +40,15 @@ import sun.text.Normalizer; import jdk.internal.icu.text.NormalizerBase; +import java.util.HexFormat; + import static java.text.Normalizer.Form.*; -public class ICUBasicTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new ICUBasicTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class ICUBasicTest { /* * Normalization modes @@ -75,6 +76,7 @@ * PRI #29 is supported in Unicode 4.1.0. Therefore, expected results are * different for earlier Unicode versions. */ + @Test public void TestComposition() { final TestCompositionCase cases[] = new TestCompositionCase[] { @@ -114,10 +116,7 @@ output = Normalizer.normalize(cases[i].input, cases[i].form, cases[i].options); if (!output.equals(cases[i].expect)) { - errln("unexpected result for case " + i + ". Expected=" - + cases[i].expect + ", Actual=" + output); - } else if (verbose) { - logln("expected result for case " + i + ". Expected=" + fail("unexpected result for case " + i + ". Expected=" + cases[i].expect + ", Actual=" + output); } } @@ -142,26 +141,29 @@ /* * Added in order to detect a regression. */ + @Test public void TestCombiningMarks() { String src = "\u0f71\u0f72\u0f73\u0f74\u0f75"; String expected = "\u0F71\u0F71\u0F71\u0F72\u0F72\u0F74\u0F74"; String result = NormalizerBase.normalize(src, NFD); if (!expected.equals(result)) { - errln("Reordering of combining marks failed. Expected: " + - toHexString(expected) + " Got: "+ toHexString(result)); + fail("Reordering of combining marks failed. Expected: " + + HexFormat.of().withDelimiter(" ").formatHex(expected.getBytes()) + + " Got: "+ HexFormat.of().withDelimiter(" ").formatHex(result.getBytes())); } } /* * Added in order to detect a regression. */ + @Test public void TestBengali() throws Exception { String input = "\u09bc\u09be\u09cd\u09be"; String output=NormalizerBase.normalize(input, NFC); if (!input.equals(output)) { - errln("ERROR in NFC of string"); + fail("ERROR in NFC of string"); } return; } @@ -175,6 +177,7 @@ * characters at the start of a string are not put in canonical * order correctly by compose() if there is no starter. */ + @Test public void TestVerisign() throws Exception { String[] inputs = { "\u05b8\u05b9\u05b1\u0591\u05c3\u05b0\u05ac\u059f", @@ -191,16 +194,22 @@ String result = NormalizerBase.normalize(input, NFD); if (!result.equals(output)) { - errln("FAIL input: " + toHexString(input) + "\n" + - " decompose: " + toHexString(result) + "\n" + - " expected: " + toHexString(output)); + fail("FAIL input: " + HexFormat.of().withDelimiter(" ") + .formatHex(input.getBytes()) + "\n" + + " decompose: " + HexFormat.of().withDelimiter(" ") + .formatHex(result.getBytes()) + "\n" + + " expected: " + HexFormat.of().withDelimiter(" ") + .formatHex(output.getBytes())); } result = NormalizerBase.normalize(input, NFC); if (!result.equals(output)) { - errln("FAIL input: " + toHexString(input) + "\n" + - " compose: " + toHexString(result) + "\n" + - " expected: " + toHexString(output)); + fail("FAIL input: " + HexFormat.of().withDelimiter(" ") + .formatHex(input.getBytes()) + "\n" + + " compose: " + HexFormat.of().withDelimiter(" ") + .formatHex(output.getBytes()) + "\n" + + " expected: " + HexFormat.of().withDelimiter(" ") + .formatHex(output.getBytes())); } } } @@ -214,6 +223,7 @@ * map to the same canonical class, which is not the case, in * reality. */ + @Test public void TestZeroIndex() throws Exception { String[] DATA = { // Expect col1 x COMPOSE_COMPAT => col2 @@ -231,21 +241,27 @@ String exp = DATA[i+1]; if (b.equals(exp)) { - logln("Ok: " + toHexString(a) + " x COMPOSE_COMPAT => " + - toHexString(b)); + System.out.println("Ok: " + HexFormat.of().withDelimiter(" ") + .formatHex(a.getBytes()) + " x COMPOSE_COMPAT => " + + HexFormat.of().withDelimiter(" ") + .formatHex(b.getBytes())); } else { - errln("FAIL: " + toHexString(a) + " x COMPOSE_COMPAT => " + - toHexString(b) + ", expect " + toHexString(exp)); + fail("FAIL: " + HexFormat.of().withDelimiter(" ") + .formatHex(b.getBytes()) + " x COMPOSE_COMPAT => " + + HexFormat.of().withDelimiter(" ") + .formatHex(a.getBytes()) + ", expect " + + HexFormat.of().withDelimiter(" ") + .formatHex(exp.getBytes())); } a = NormalizerBase.normalize(b, NFD); exp = DATA[i+2]; if (a.equals(exp)) { - logln("Ok: " + toHexString(b) + " x DECOMP => " + - toHexString(a)); + System.out.println("Ok: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + + HexFormat.of().withDelimiter(" ").formatHex(a.getBytes())); } else { - errln("FAIL: " + toHexString(b) + " x DECOMP => " + - toHexString(a) + ", expect " + toHexString(exp)); + fail("FAIL: " + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x DECOMP => " + + HexFormat.of().withDelimiter(" ").formatHex(a.getBytes()) + ", expect " + HexFormat.of().withDelimiter(" ").formatHex(exp.getBytes())); } } } @@ -254,6 +270,7 @@ * Make sure characters in the CompositionExclusion.txt list do not get * composed to. */ + @Test public void TestCompositionExclusion() throws Exception { // This list is generated from CompositionExclusion.txt. // Update whenever the normalizer tables are updated. Note @@ -382,28 +399,25 @@ String c = NormalizerBase.normalize(b, NFC); if (c.equals(a)) { - errln("FAIL: " + toHexString(a) + " x DECOMP_COMPAT => " + - toHexString(b) + " x COMPOSE => " + - toHexString(c) + " for the latest Unicode"); - } else if (verbose) { - logln("Ok: " + toHexString(a) + " x DECOMP_COMPAT => " + - toHexString(b) + " x COMPOSE => " + - toHexString(c) + " for the latest Unicode"); + fail("FAIL: " + HexFormat.of().withDelimiter(" ") + .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + + HexFormat.of().withDelimiter(" ") + .formatHex(b.getBytes()) + " x COMPOSE => " + + HexFormat.of().withDelimiter(" ") + .formatHex(c.getBytes()) + " for the latest Unicode"); } b = NormalizerBase.normalize(a, NFKD, Normalizer.UNICODE_3_2); c = NormalizerBase.normalize(b, NFC, Normalizer.UNICODE_3_2); if (c.equals(a)) { - errln("FAIL: " + toHexString(a) + " x DECOMP_COMPAT => " + - toHexString(b) + " x COMPOSE => " + - toHexString(c) + " for Unicode 3.2.0"); - } else if (verbose) { - logln("Ok: " + toHexString(a) + " x DECOMP_COMPAT => " + - toHexString(b) + " x COMPOSE => " + - toHexString(c) + " for Unicode 3.2.0"); + fail("FAIL: " + HexFormat.of().withDelimiter(" ") + .formatHex(a.getBytes()) + " x DECOMP_COMPAT => " + + HexFormat.of().withDelimiter(" ").formatHex(b.getBytes()) + " x COMPOSE => " + + HexFormat.of().withDelimiter(" ").formatHex(c.getBytes()) + " for Unicode 3.2.0"); } } + @Test public void TestTibetan() throws Exception { String[][] decomp = { { "\u0f77", "\u0f77", "\u0fb2\u0f71\u0f80" } @@ -418,6 +432,7 @@ staticTest(NFKC,compose, 2); } + @Test public void TestExplodingBase() throws Exception{ // \u017f - Latin small letter long s // \u0307 - combining dot above @@ -551,18 +566,22 @@ { "\u30AB\uFF9E", "\u30AB\u3099", "\u30AC" }, }; + @Test public void TestNFD() throws Exception{ staticTest(NFD, canonTests, 1); } + @Test public void TestNFC() throws Exception{ staticTest(NFC, canonTests, 2); } + @Test public void TestNFKD() throws Exception{ staticTest(NFKD, compatTests, 1); } + @Test public void TestNFKC() throws Exception{ staticTest(NFKC, compatTests, 2); } @@ -572,15 +591,18 @@ int outCol) throws Exception { for (int i = 0; i < tests.length; i++) { String input = tests[i][0]; - logln("Normalizing '" + input + "' (" + toHexString(input) + ")" ); + System.out.println("Normalizing '" + input + "' (" + HexFormat.of() + .withDelimiter(" ").formatHex(input.getBytes()) + ")" ); String expect =tests[i][outCol]; String output = java.text.Normalizer.normalize(input, form); if (!output.equals(expect)) { - errln("FAIL: case " + i - + " expected '" + expect + "' (" + toHexString(expect) + ")" - + " but got '" + output + "' (" + toHexString(output) + ")" + fail("FAIL: case " + i + + " expected '" + expect + "' (" + HexFormat.of() + .withDelimiter(" ").formatHex(expect.getBytes()) + ")" + + " but got '" + output + "' (" + HexFormat.of() + .withDelimiter(" ").formatHex(output.getBytes()) + ")" ); } } @@ -595,13 +617,15 @@ { "\u1111\u1171\u11b6", "\u1111\u1171\u11b6", "\ud4db" }, }; + @Test public void TestHangulCompose() throws Exception{ - logln("Canonical composition..."); + System.out.println("Canonical composition..."); staticTest(NFC, hangulCanon, 2); } + @Test public void TestHangulDecomp() throws Exception{ - logln("Canonical decomposition..."); + System.out.println("Canonical decomposition..."); staticTest(NFD, hangulCanon, 1); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/Normalizer/NormalizerAPITest.java openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/NormalizerAPITest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/Normalizer/NormalizerAPITest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/Normalizer/NormalizerAPITest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,14 +26,17 @@ * @bug 4221795 8174270 * @summary Confirm Normalizer's fundamental behavior * @modules java.base/sun.text java.base/jdk.internal.icu.text - * @library /java/text/testlib * @compile -XDignore.symbol.file NormalizerAPITest.java - * @run main/timeout=30 NormalizerAPITest + * @run junit/timeout=30 NormalizerAPITest */ import java.text.Normalizer; import java.nio.CharBuffer; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /* * Tests around null/"" arguments for public methods. @@ -41,7 +44,7 @@ * You may think that so elaborate testing for such a part is not necessary. * But I actually detected a bug by this program during my porting work. */ -public class NormalizerAPITest extends IntlTest { +public class NormalizerAPITest { // // Shortcuts @@ -71,13 +74,10 @@ static final String nonNullStr = "testdata"; - public static void main(String[] args) throws Exception { - new NormalizerAPITest().run(args); - } - /* * Check if normalize(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_java_normalize() { boolean error = false; @@ -100,13 +100,14 @@ } if (error) { - errln("normalize(null) should throw NullPointerException."); + fail("normalize(null) should throw NullPointerException."); } } /* * Check if normalize(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_sun_normalize() { boolean error = false; @@ -131,13 +132,14 @@ } if (error) { - errln("normalize(null) should throw NullPointerException."); + fail("normalize(null) should throw NullPointerException."); } } /* * Check if isNormalized(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_java_isNormalized() { boolean error = false; @@ -160,13 +162,14 @@ catch (NullPointerException e) { } if (error) { - errln("isNormalized(null) should throw NullPointerException."); + fail("isNormalized(null) should throw NullPointerException."); } } /* * Check if isNormalized(null) throws NullPointerException as expected. */ + @Test public void Test_NullPointerException_sun_isNormalized() { boolean error = false; @@ -191,7 +194,7 @@ } if (error) { - errln("isNormalized(null) should throw NullPointerException."); + fail("isNormalized(null) should throw NullPointerException."); } } @@ -199,6 +202,7 @@ * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_java_normalize() { boolean error = false; @@ -215,7 +219,7 @@ } if (error) { - errln("normalize() for String(\"\") should return \"\"."); + fail("normalize() for String(\"\") should return \"\"."); } } @@ -223,6 +227,7 @@ * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_sun_normalize() { boolean error = false; @@ -240,7 +245,7 @@ } } if (error) { - errln("normalize() for String(\"\") should return \"\"."); + fail("normalize() for String(\"\") should return \"\"."); } } @@ -248,6 +253,7 @@ * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_java_isNormalized() { boolean error = false; @@ -263,7 +269,7 @@ } } if (error) { - errln("isNormalized() for String(\"\") should not return true."); + fail("isNormalized() for String(\"\") should not return true."); } } @@ -271,6 +277,7 @@ * Check if isNormalized("") doesn't throw NullPointerException and returns * "" as expected. */ + @Test public void Test_No_NullPointerException_sun_isNormalized() { boolean error = false; @@ -288,7 +295,7 @@ } } if (error) { - errln("isNormalized() for String(\"\") should not return true."); + fail("isNormalized() for String(\"\") should not return true."); } } @@ -296,6 +303,7 @@ * Check if normalize() and isNormalized() work as expected for every * known class which implement CharSequence Interface. */ + @Test public void Test_CharSequence() { check_CharSequence(String.valueOf(inputData), @@ -315,23 +323,23 @@ void check_CharSequence(CharSequence in, CharSequence expected) { String out = Normalizer.normalize(in, NFD); if (!out.equals(expected.toString())) { - errln("java.text.Normalizer.normalize(" + + fail("java.text.Normalizer.normalize(" + in.getClass().getSimpleName() + ") failed."); } out = sun.text.Normalizer.normalize(in, NFD, jdk.internal.icu.text.NormalizerBase.UNICODE_LATEST); if (!out.equals(expected.toString())) { - errln("sun.text.Normalizer.normalize(" + + fail("sun.text.Normalizer.normalize(" + in.getClass().getSimpleName() + ") failed."); } if (!Normalizer.isNormalized(expected, NFD)) { - errln("java.text.Normalizer.isNormalize(" + + fail("java.text.Normalizer.isNormalize(" + in.getClass().getSimpleName() + ") failed."); } if (!sun.text.Normalizer.isNormalized(expected, NFD, jdk.internal.icu.text.NormalizerBase.UNICODE_LATEST)) { - errln("sun.text.Normalizer.isNormalize(" + + fail("sun.text.Normalizer.isNormalize(" + in.getClass().getSimpleName() + ") failed."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/testlib/HexDumpReader.java openjdk-17-17.0.15+6/test/jdk/java/text/testlib/HexDumpReader.java --- openjdk-17-17.0.14+7/test/jdk/java/text/testlib/HexDumpReader.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/testlib/HexDumpReader.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -37,7 +38,11 @@ * * $ od -vw -t x1 foo | sed -r -e 's/^[0-9]+ ?//' -e 's/ //g' -e '/^$/d' */ -public class HexDumpReader { +public final class HexDumpReader { + + // Utility class should not be instantiated + private HexDumpReader() {} + public static InputStream getStreamFromHexDump(String fileName) { return getStreamFromHexDump(new File(System.getProperty("test.src", "."), fileName)); @@ -48,7 +53,7 @@ int lineNo = 0; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(hexFile), - "us-ascii"))) { + StandardCharsets.US_ASCII))) { String line; while ((line = reader.readLine()) != null) { lineNo++; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/testlib/IntlTest.java openjdk-17-17.0.15+6/test/jdk/java/text/testlib/IntlTest.java --- openjdk-17-17.0.14+7/test/jdk/java/text/testlib/IntlTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/testlib/IntlTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,274 +0,0 @@ -/* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.IOException; -import java.io.PrintWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Map; -import java.util.LinkedHashMap; -import java.util.List; - -/** - * IntlTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of public void methods named "Test*" or - * "test*" with no arguments. Each of these methods performs some - * test. Test methods should indicate errors by calling either err() or - * errln(). This will increment the errorCount field and may optionally - * print a message to the log. Debugging information may also be added to - * the log via the log and logln methods. These methods will add their - * arguments to the log only if the test is being run in verbose mode. - */ -public abstract class IntlTest { - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a method to an existing class. - //------------------------------------------------------------------------ - - protected IntlTest() { - // Populate testMethods with all the test methods. - Method[] methods = getClass().getDeclaredMethods(); - for (Method method : methods) { - if (Modifier.isPublic(method.getModifiers()) - && method.getReturnType() == void.class - && method.getParameterCount() == 0) { - String name = method.getName(); - if (name.length() > 4) { - if (name.startsWith("Test") || name.startsWith("test")) { - testMethods.put(name, method); - } - } - } - } - } - - protected void run(String[] args) throws Exception - { - // Set up the log and reference streams. We use PrintWriters in order to - // take advantage of character conversion. The JavaEsc converter will - // convert Unicode outside the ASCII range to Java's \\uxxxx notation. - log = new PrintWriter(System.out, true); - - // Parse the test arguments. They can be either the flag - // "-verbose" or names of test methods. Create a list of - // tests to be run. - List testsToRun = new ArrayList<>(args.length); - for (String arg : args) { - switch (arg) { - case "-verbose": - verbose = true; - break; - case "-prompt": - prompt = true; - break; - case "-nothrow": - nothrow = true; - break; - case "-exitcode": - exitCode = true; - break; - default: - Method m = testMethods.get(arg); - if (m == null) { - System.out.println("Method " + arg + ": not found"); - usage(); - return; - } - testsToRun.add(m); - break; - } - } - - // If no test method names were given explicitly, run them all. - if (testsToRun.isEmpty()) { - testsToRun.addAll(testMethods.values()); - } - - System.out.println(getClass().getName() + " {"); - indentLevel++; - - // Run the list of tests given in the test arguments - for (Method testMethod : testsToRun) { - int oldCount = errorCount; - - writeTestName(testMethod.getName()); - - try { - testMethod.invoke(this, new Object[0]); - } catch (IllegalAccessException e) { - errln("Can't acces test method " + testMethod.getName()); - } catch (InvocationTargetException e) { - errln("Uncaught exception thrown in test method " - + testMethod.getName()); - e.getTargetException().printStackTrace(this.log); - } - writeTestResult(errorCount - oldCount); - } - indentLevel--; - writeTestResult(errorCount); - - if (prompt) { - System.out.println("Hit RETURN to exit..."); - try { - System.in.read(); - } catch (IOException e) { - System.out.println("Exception: " + e.toString() + e.getMessage()); - } - } - if (nothrow) { - if (exitCode) { - System.exit(errorCount); - } - if (errorCount > 0) { - throw new IllegalArgumentException("encountered " + errorCount + " errors"); - } - } - } - - /** - * Adds the given message to the log if we are in verbose mode. - */ - protected void log(String message) { - logImpl(message, false); - } - - protected void logln(String message) { - logImpl(message, true); - } - - protected void logln() { - logImpl(null, true); - } - - private void logImpl(String message, boolean newline) { - if (verbose) { - if (message != null) { - indent(indentLevel + 1); - log.print(message); - } - if (newline) { - log.println(); - } - } - } - - protected void err(String message) { - errImpl(message, false); - } - - protected void errln(String message) { - errImpl(message, true); - } - - private void errImpl(String message, boolean newline) { - errorCount++; - indent(indentLevel + 1); - log.print(message); - if (newline) { - log.println(); - } - log.flush(); - - if (!nothrow) { - throw new RuntimeException(message); - } - } - - protected int getErrorCount() { - return errorCount; - } - - protected void writeTestName(String testName) { - indent(indentLevel); - log.print(testName); - log.flush(); - needLineFeed = true; - } - - protected void writeTestResult(int count) { - if (!needLineFeed) { - indent(indentLevel); - log.print("}"); - } - needLineFeed = false; - - if (count != 0) { - log.println(" FAILED"); - } else { - log.println(" Passed"); - } - } - - /* - * Returns a spece-delimited hex String. - */ - protected static String toHexString(String s) { - StringBuilder sb = new StringBuilder(" "); - - for (int i = 0; i < s.length(); i++) { - sb.append(Integer.toHexString(s.charAt(i))); - sb.append(' '); - } - - return sb.toString(); - } - - private void indent(int distance) { - if (needLineFeed) { - log.println(" {"); - needLineFeed = false; - } - log.print(SPACES.substring(0, distance * 2)); - } - - /** - * Print a usage message for this test class. - */ - void usage() { - System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); - - System.out.println(" Available test names:"); - for (String methodName : testMethods.keySet()) { - System.out.println("\t" + methodName); - } - } - - private boolean prompt; - private boolean nothrow; - protected boolean verbose; - private boolean exitCode; - private PrintWriter log; - private int indentLevel; - private boolean needLineFeed; - private int errorCount; - - private final Map testMethods = new LinkedHashMap<>(); - - private static final String SPACES = " "; -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/text/testlib/TestUtils.java openjdk-17-17.0.15+6/test/jdk/java/text/testlib/TestUtils.java --- openjdk-17-17.0.14+7/test/jdk/java/text/testlib/TestUtils.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/text/testlib/TestUtils.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,23 +21,35 @@ * questions. */ +import java.text.CollationElementIterator; +import java.text.CollationKey; +import java.text.Collator; import java.text.DecimalFormatSymbols; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; -import java.util.Locale.Builder; - /** - * TestUtils provides utility methods to get a locale-dependent attribute. - * For example, - * - whether or not a non-Gregorian calendar is used - * - whether or not non-ASCII digits are used - * + * TestUtils provides utility methods used by i18n related tests. * This class was developed to help testing for internationalization & - * localization and is not versatile. + * localization and is not versatile. This class is split into the following sections, + * 1) Methods to get a locale-dependent attribute. + * For example, + * - whether a non-Gregorian calendar is used + * - whether non-ASCII digits are used + * 2) Methods that help Collator related tests + * For example, + * - compare CollationElementIterators + * - test the expected relation key result for a Collator */ -public class TestUtils { +public final class TestUtils { + + // Utility class should not be instantiated + private TestUtils() {} + + /* + * The below methods are utilities for getting locale-dependent attributes. + */ /** * Returns true if the give locale uses Gregorian calendar. @@ -56,7 +68,6 @@ /** * Returns true if the given locale has a special variant which is treated * as ill-formed in BCP 47. - * * BCP 47 requires a variant subtag to be 5 to 8 alphanumerics or a * single numeric followed by 3 alphanumerics. * However, note that this methods doesn't check a variant so rigorously @@ -71,4 +82,103 @@ && "JP".equals(variant) || "NY".equals(variant) || "TH".equals(variant); } + /* + * The below methods are utilities specific to the Collation tests + */ + + /** + * Compares two CollationElementIterators and throws an exception + * with a message detailing which collation elements were not equal + */ + public static void compareCollationElementIters(CollationElementIterator i1, CollationElementIterator i2) { + int c1, c2, count = 0; + do { + c1 = i1.next(); + c2 = i2.next(); + if (c1 != c2) { + throw new RuntimeException(" " + count + ": " + c1 + " != " + c2); + } + count++; + } while (c1 != CollationElementIterator.NULLORDER); + } + + // Replace non-printable characters with unicode escapes + public static String prettify(String str) { + StringBuilder result = new StringBuilder(); + + String zero = "0000"; + + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if (ch < 0x09 || (ch > 0x0A && ch < 0x20)|| (ch > 0x7E && ch < 0xA0) || ch > 0x100) { + String hex = Integer.toString((int)ch,16); + + result.append("\\u").append(zero.substring(0, 4 - hex.length())).append(hex); + } else { + result.append(ch); + } + } + return result.toString(); + } + + // Produce a printable representation of a CollationKey + public static String prettifyCKey(CollationKey key) { + StringBuilder result = new StringBuilder(); + byte[] bytes = key.toByteArray(); + + for (int i = 0; i < bytes.length; i += 2) { + int val = (bytes[i] << 8) + bytes[i+1]; + result.append(Integer.toString(val, 16)).append(" "); + } + return result.toString(); + } + + /** + * Utility to test a collator with an array of test values. + * See the other doTest() method for specific comparison details. + */ + public static void doCollatorTest(Collator col, int strength, + String[] source, String[] target, int[] result) { + if (source.length != target.length) { + throw new RuntimeException("Data size mismatch: source = " + + source.length + ", target = " + target.length); + } + if (source.length != result.length) { + throw new RuntimeException("Data size mismatch: source & target = " + + source.length + ", result = " + result.length); + } + + col.setStrength(strength); + for (int i = 0; i < source.length ; i++) { + doCollatorTest(col, source[i], target[i], result[i]); + } + } + + /** + * Test that a collator returns the correct relation result value when + * comparing a source and target string. Also tests that the compare and collation + * key results return the same value. + */ + public static void doCollatorTest(Collator col, + String source, String target, int result) { + char relation = '='; + if (result <= -1) { + relation = '<'; + } else if (result >= 1) { + relation = '>'; + } + + int compareResult = col.compare(source, target); + CollationKey sortKey1 = col.getCollationKey(source); + CollationKey sortKey2 = col.getCollationKey(target); + int keyResult = sortKey1.compareTo(sortKey2); + if (compareResult != keyResult) { + throw new RuntimeException("Compare and Collation Key results are different! Source = " + + source + " Target = " + target); + } + if (keyResult != result) { + throw new RuntimeException("Collation Test failed! Source = " + source + " Target = " + + target + " result should be " + relation); + } + } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/time/tck/java/time/TCKInstant.java openjdk-17-17.0.15+6/test/jdk/java/time/tck/java/time/TCKInstant.java --- openjdk-17-17.0.14+7/test/jdk/java/time/tck/java/time/TCKInstant.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/time/tck/java/time/TCKInstant.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -187,10 +187,21 @@ //----------------------------------------------------------------------- @Test public void now() { - Instant expected = Instant.now(Clock.systemUTC()); - Instant test = Instant.now(); - long diff = Math.abs(test.toEpochMilli() - expected.toEpochMilli()); - assertTrue(diff < 100); // less than 0.1 secs + long beforeMillis, instantMillis, afterMillis, diff; + int retryRemaining = 5; // MAX_RETRY_COUNT + do { + beforeMillis = Instant.now(Clock.systemUTC()).toEpochMilli(); + instantMillis = Instant.now().toEpochMilli(); + afterMillis = Instant.now(Clock.systemUTC()).toEpochMilli(); + diff = instantMillis - beforeMillis; + if (instantMillis < beforeMillis || instantMillis > afterMillis) { + throw new RuntimeException(": Invalid instant: (~" + instantMillis + "ms)" + + " when systemUTC in millis is in [" + + beforeMillis + ", " + + afterMillis + "]"); + } + } while (diff > 100 && --retryRemaining > 0); // retry if diff more than 0.1 sec + assertTrue(retryRemaining > 0); } //----------------------------------------------------------------------- diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/BuddhistCalendarTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/BuddhistCalendarTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/BuddhistCalendarTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/BuddhistCalendarTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,191 +24,200 @@ /* * @test * @bug 4817812 4847186 4956227 4956479 - * @summary Confirm that BuddhistCalendar's add(), roll() and toString() work correctly with Buddhist Era years. + * @summary Confirm that BuddhistCalendar's add(), roll(), set(), and toString() + * work correctly with Buddhist Era years. + * @run junit BuddhistCalendarTest */ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; -import static java.util.Calendar.*; +import java.util.stream.Stream; + +import static java.util.Calendar.APRIL; +import static java.util.Calendar.DATE; +import static java.util.Calendar.DECEMBER; +import static java.util.Calendar.ERA; +import static java.util.Calendar.FEBRUARY; +import static java.util.Calendar.JANUARY; +import static java.util.Calendar.MAY; +import static java.util.Calendar.MONTH; +import static java.util.Calendar.WEEK_OF_YEAR; +import static java.util.Calendar.YEAR; + + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class BuddhistCalendarTest { private static final Locale THAI_LOCALE = new Locale("th", "TH"); - public static void main(String[] args) { - testAddRoll(); - testToString(); - testException(); - testLeastMax(); - } - - /** - * 4817812 - */ - static void testAddRoll() { - Calendar cal; - int base, year; - - /* - * Test: BuddhistCalendar.add(YEAR) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.add(YEAR, 1); - year = cal.get(YEAR); - check(year, base+1, "add(+YEAR)"); - - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.add(YEAR, -3); - year = cal.get(YEAR); - check(year, base-3, "add(-YEAR)"); - - /* - * Test BuddhistCalendar.add(MONTH) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.set(MONTH, DECEMBER); - cal.add(MONTH, 2); - year = cal.get(YEAR); - check(year, base+1, "add(+MONTH)"); - - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.set(MONTH, FEBRUARY); - cal.add(MONTH, -4); - year = cal.get(YEAR); - check(year, base-1, "add(-MONTH)"); - - /* - * Test BuddhistCalendar.roll(YEAR) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.roll(YEAR, 2); - year = cal.get(YEAR); - check(year, base+2, "roll(+YEAR)"); - - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.roll(YEAR, -4); - year = cal.get(YEAR); - check(year, base-4, "roll(-YEAR)"); - - /* - * Test BuddhistCalendar.roll(WEEK_OF_YEAR) - */ - cal = getBuddhistCalendar(); - cal.set(YEAR, 2543); // A.D.2000 - cal.set(MONTH, DECEMBER); - cal.set(DATE, 31); - base = cal.get(YEAR); - check(base, 2543, "roll(+WEEK_OF_YEAR)"); - cal.roll(WEEK_OF_YEAR, 10); - year = cal.get(YEAR); - check(year, base, "roll(+WEEK_OF_YEAR)"); - - cal = getBuddhistCalendar(); - cal.set(YEAR, 2543); // A.D.2000 - cal.set(MONTH, JANUARY); - cal.set(DATE, 1); - base = cal.get(YEAR); - check(base, 2543, "roll(+WEEK_OF_YEAR)"); - cal.roll(WEEK_OF_YEAR, -10); - year = cal.get(YEAR); - check(year, base, "roll(-WEEK_OF_YEAR)"); - - /* - * Test Calendar.set(year, month, date) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.set(3001, APRIL, 10); - year = cal.get(YEAR); - check(year, 3001, "set(year, month, date)"); + /* + * Test some add values for the BuddhistCalendar. This test compares the same field + * as the one added. + */ + @ParameterizedTest + @MethodSource("addDataProvider") + public void buddhistAddTest(Calendar cal, int amount, int fieldToAdd) { + int base = cal.get(YEAR); + cal.add(fieldToAdd, amount); + int yearAfterRoll = cal.get(YEAR); + assertEquals(yearAfterRoll, base+amount, String.format( + "Added: %s to field: %s", amount, fieldToAdd)); + } - /* - * Test Calendar.set(year, month, date, hour, minute) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.set(3020, MAY, 20, 9, 10); - year = cal.get(YEAR); - check(year, 3020, "set(year, month, date, hour, minute)"); + /* + * Given in the format: Calendar, amount to add, and field to add. + * Test adding of positive and negative year values. + */ + private static Stream addDataProvider() { + return Stream.of( + Arguments.of(getBuddhistCalendar(), 1, YEAR), + Arguments.of(getBuddhistCalendar(), -3, YEAR) + ); + } + + /* + * Test some add values for the BuddhistCalendar. Compare a bigger field + * (year) than the one added (month). Larger field should roll over. + */ + @ParameterizedTest + @MethodSource("alternateAddDataProvider") + public void buddhistAlternateAddTest(Calendar cal, int amount, int fieldToAdd) { + int base = cal.get(YEAR); + cal.add(fieldToAdd, amount); + int yearAfterRoll = cal.get(YEAR); + assertEquals(yearAfterRoll, (amount>0) ? (base+1): (base-1), String.format( + "Added: %s to field: %s", amount, fieldToAdd)); + } + + /* + * Given in the format: Calendar, amount to add, and field to add. + * Test adding of positive and negative month values. + */ + private static Stream alternateAddDataProvider() { + return Stream.of( + Arguments.of(getBuddhistCalendarBuilder().set(MONTH, DECEMBER).build(), 2, MONTH), + Arguments.of(getBuddhistCalendarBuilder().set(MONTH, FEBRUARY).build(), -4, MONTH) + ); + } + + /* + * Test some roll values for the BuddhistCalendar. Compare same field + * that was rolled, value should change. + */ + @ParameterizedTest + @MethodSource("rollProvider") + public void buddhistRollTest(Calendar cal, int amount, int fieldToRoll) { + int base = cal.get(YEAR); + cal.roll(fieldToRoll, amount); + int year = cal.get(YEAR); + assertEquals(year, base+amount, "Rolling field should change value"); + } + + /* + * Given in the format: Calendar, amount to roll, and field to roll. + * Test rolling of positive and negative year values. + */ + private static Stream rollProvider() { + return Stream.of( + Arguments.of(getBuddhistCalendar(), 2, YEAR), + Arguments.of(getBuddhistCalendar(), -4, YEAR) + ); + } + + /* + * Set some calendar values and roll, however, measure a different + * field than the field that was rolled. Rolling should not change the + * larger field. + */ + @ParameterizedTest + @MethodSource("alternateRollProvider") + public void buddhistAlternateRollTest(Calendar cal, int amount, int fieldToRoll) { + int base = cal.get(YEAR); + cal.roll(fieldToRoll, amount); + int year = cal.get(YEAR); + assertEquals(year, base, "Rolling smaller field should not change bigger field"); + } - /* - * Test Calendar.set(year, month, date, hour, minute, second) - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - cal.set(3120, MAY, 20, 9, 10, 52); - year = cal.get(YEAR); - check(year, 3120, "set(year, month, date, hour, minute, second)"); - - /* - * Test BuddhistCalendar.getActualMaximum(YEAR); - * set(YEAR)/get(YEAR) in this method doesn't affect the real - * YEAR value because a clone is used with set()&get(). - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - int limit = cal.getActualMaximum(YEAR); - year = cal.get(YEAR); - check(year, base, "BuddhistCalendar.getActualMaximum(YEAR)"); - - /* - * Test BuddhistCalendar.getActualMinimum(YEAR); - * This doesn't call set(YEAR) nor get(YEAR), though. - */ - cal = getBuddhistCalendar(); - base = cal.get(YEAR); - limit = cal.getActualMinimum(YEAR); - year = cal.get(YEAR); - check(year, base, "BuddhistCalendar.getActualMinimum(YEAR)"); + /* + * Given in the format: Calendar, amount to roll, and field to roll. + * Test rolling of positive and negative week_of_year values. + */ + private static Stream alternateRollProvider() { + return Stream.of( + Arguments.of(getBuddhistCalendarBuilder().set(YEAR, 2543) + .set(MONTH, DECEMBER).set(DATE, 31).build(), 10, WEEK_OF_YEAR), + Arguments.of(getBuddhistCalendarBuilder().set(YEAR, 2543) + .set(MONTH, JANUARY).set(DATE, 1).build(), -10, WEEK_OF_YEAR) + ); } - /** - * 4847186: BuddhistCalendar: toString() returns Gregorian year + // Test the overloaded set() methods. Check year value. + @Test + public void buddhistSetTest() { + Calendar cal = getBuddhistCalendar(); + cal.set(3001, APRIL, 10); + assertEquals(cal.get(YEAR), 3001); + cal.set(3020, MAY, 20, 9, 10); + assertEquals(cal.get(YEAR), 3020); + cal.set(3120, MAY, 20, 9, 10, 52 ); + assertEquals(cal.get(YEAR), 3120); + } + + /* + * Test BuddhistCalendar.getActualMaximum(YEAR); + * set(YEAR)/get(YEAR) in this method doesn't affect the real + * YEAR value because a clone is used with set() and get(). */ - static void testToString() { + @Test + public void buddhistActualMaximumTest() { + Calendar cal = getBuddhistCalendar(); + int base = cal.get(YEAR); + int ignored = cal.getActualMaximum(YEAR); + int year = cal.get(YEAR); + assertEquals(year, base, "BuddhistCalendar.getActualMaximum(YEAR)"); + } + + // Test BuddhistCalendar.getActualMinimum(YEAR), doesn't call set(YEAR) nor get(YEAR). + @Test + public void buddhistActualMinimumTest() { + Calendar cal = getBuddhistCalendar(); + int base = cal.get(YEAR); + int ignored = cal.getActualMinimum(YEAR); + int year = cal.get(YEAR); + assertEquals(year, base, "BuddhistCalendar.getActualMinimum(YEAR)"); + } + + // 4847186: BuddhistCalendar: toString() returns Gregorian year + @Test + public void buddhistToStringTest() { Calendar cal = getBuddhistCalendar(); int year = cal.get(YEAR); String s = cal.toString(); String y = s.replaceAll(".+,YEAR=(\\d+),.+", "$1"); - if (Integer.parseInt(y) != year) { - throw new RuntimeException("toString(): wrong year value: got " + y - + ", expected " + year); - } + assertEquals(year, Integer.parseInt(y), "Wrong year value"); } - /** - * 4956479: BuddhistCalendar methods may return wrong values after exception - */ - static void testException() { + // 4956479: BuddhistCalendar methods may return wrong values after exception + @Test + public void buddhistValuesAfterExceptionTest() { Calendar cal = getBuddhistCalendar(); int year = cal.get(YEAR); - boolean exceptionOccurred = false; - try { - cal.add(100, +1); // cause exception - } catch (Exception e) { - exceptionOccurred = true; - } - if (!exceptionOccurred) { - throw new RuntimeException("testException: test case failed: no exception thrown"); - } + assertThrows(IllegalArgumentException.class, ()-> cal.add(100, +1)); int year2 = cal.get(YEAR); - if (year2 != year) { - throw new RuntimeException("wrong year value after exception: got " + year2 - + ", expected " + year); - } + assertEquals(year2, year, "Wrong year value after exception thrown"); } - /** - * 4956227: getLeastMaximum(WEEK_OF_MONTH) return diff. val. for Greg. and Buddhist Calendar - */ - static void testLeastMax() { + // 4956227: getLeastMaximum(WEEK_OF_MONTH) return diff. val. for Greg. and Buddhist Calendar + @Test + public void buddhistLeastMaximumTest() { Calendar bc = getBuddhistCalendar(); // Specify THAI_LOCALE to get the same params for WEEK // calculations (6904680). @@ -219,25 +228,17 @@ } int bn = bc.getLeastMaximum(f); int gn = gc.getLeastMaximum(f); - if (bn != gn) { - throw new RuntimeException("inconsistent Least Max value for " + Koyomi.getFieldName(f) - + ": Buddhist=" + bn - + ": Gregorian=" + gn); - } + assertEquals(bn, gn, "Inconsistent Least Max value for " + Koyomi.getFieldName(f)); } } - /** - * @return a BuddhistCalendar - */ - static Calendar getBuddhistCalendar() { - return Calendar.getInstance(THAI_LOCALE); + // Utility to get a new Buddhist Calendar Builder (to allow setting of other values) + private static Calendar.Builder getBuddhistCalendarBuilder() { + return new Calendar.Builder().setLocale(THAI_LOCALE); } - static void check(int got, int expected, String s) { - if (got != expected) { - throw new RuntimeException("Failed: " + - s + ": got:" + got + ", expected:" + expected); - } + // Utility to get a new Buddhist calendar + private static Calendar getBuddhistCalendar() { + return Calendar.getInstance(THAI_LOCALE); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/Bug4302966.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4302966.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/Bug4302966.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4302966.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,18 +26,22 @@ * @bug 4302966 8176841 * @modules jdk.localedata * @summary In Czech Republic first day of week is Monday not Sunday + * @run junit Bug4302966 */ import java.util.Calendar; import java.util.Locale; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + public class Bug4302966 { - public static void main(String[] args) { + // Specific day of week test for Czech locale + public void czechDayOfWeekTest() { Calendar czechCalendar = Calendar.getInstance(new Locale("cs", "CZ")); int firstDayOfWeek = czechCalendar.getFirstDayOfWeek(); - if (firstDayOfWeek != Calendar.MONDAY) { - throw new RuntimeException(); - } + assertEquals(firstDayOfWeek, Calendar.MONDAY); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/Bug4766302.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4766302.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/Bug4766302.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/Bug4766302.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,16 +24,21 @@ /* * @test * @bug 4766302 - * @summary Make sure that computeTime call doesn't reset the isTimeSet value. + * @summary Make sure that calling computeTime doesn't reset the isTimeSet value. + * @run junit Bug4766302 */ import java.util.GregorianCalendar; -@SuppressWarnings("serial") +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + public class Bug4766302 { + // Extend GregorianCalendar to check the protected value of isTimeSet + @SuppressWarnings("serial") static class MyCalendar extends GregorianCalendar { - boolean isTimeStillSet() { return isTimeSet; } @@ -43,11 +48,11 @@ } } - public static void main(String[] args) { + // Check the value of isTimeStillSet() after calling computeTime() + @Test + public void validateIsTimeSetTest() { MyCalendar cal = new MyCalendar(); cal.computeTime(); - if (!cal.isTimeStillSet()) { - throw new RuntimeException("computeTime() call reset isTimeSet."); - } + assertTrue(cal.isTimeStillSet(), "computeTime() call reset isTimeSet."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarLimitTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarLimitTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarLimitTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarLimitTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,16 @@ * @bug 4033662 * @summary test for limit on Calendar * @library /java/text/testlib - * @run main CalendarLimitTest -verbose + * @run junit CalendarLimitTest */ import java.util.*; import java.text.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * This test verifies the behavior of Calendar around the very earliest limits * which it can handle. It also verifies the behavior for large values of millis. @@ -42,7 +46,7 @@ * March 17, 1998: Added code to make sure big + dates are big + AD years, and * big - dates are big + BC years. */ -public class CalendarLimitTest extends IntlTest +public class CalendarLimitTest { // This number determined empirically; this is the old limit, // which we test for to make sure it isn't there anymore. @@ -61,16 +65,6 @@ static long ORIGIN; // This is the *approximate* point at which BC switches to AD - public static void main(String argv[]) throws Exception { - Locale locale = Locale.getDefault(); - if (!TestUtils.usesGregorianCalendar(locale)) { - System.out.println("Skipping this test because locale is " + locale); - return; - } - - new CalendarLimitTest().run(argv); - } - /** * Converts Julian day to time as milliseconds. * @param julian the given Julian day number. @@ -108,32 +102,38 @@ boolean ok = true; if (exception != null) { - errln("FAIL: Exception " + s); + fail("FAIL: Exception " + s); ok = false; } if (((millis >= ORIGIN) && (era != GregorianCalendar.AD)) || ((millis < ORIGIN) && (era != GregorianCalendar.BC)) || (year < 1)) { - errln("FAIL: Bad year/era " + s); + fail("FAIL: Bad year/era " + s); ok = false; } if (dom<1 || dom>31) { - errln("FAIL: Bad DOM " + s); + fail("FAIL: Bad DOM " + s); ok = false; } if (Math.abs(millis - rt.getTime()) > ONE_DAY) { - errln("FAIL: RT fail " + s + " -> 0x" + + fail("FAIL: RT fail " + s + " -> 0x" + Long.toHexString(rt.getTime()) + " " + fmt.format(rt)); ok = false; } - if (ok) logln(s); + if (ok) System.out.println(s); if (era==GregorianCalendar.BC) year = 1-year; return year; } + @Test public void TestCalendarLimit() { + Locale locale = Locale.getDefault(); + if (!TestUtils.usesGregorianCalendar(locale)) { + System.out.println("Skipping this test because locale is " + locale); + return; + } ORIGIN = julianDayToMillis(JAN_1_1_JULIAN_DAY); Calendar cal = Calendar.getInstance(); @@ -154,7 +154,7 @@ { int y = test(m, cal, dateFormat); if (!first && y > lastYear) - errln("FAIL: Years should be decreasing " + lastYear + " " + y); + fail("FAIL: Years should be decreasing " + lastYear + " " + y); first = false; lastYear = y; } @@ -165,7 +165,7 @@ { int y = test(m, cal, dateFormat); if (!first && y < lastYear) - errln("FAIL: Years should be increasing " + lastYear + " " + y); + fail("FAIL: Years should be increasing " + lastYear + " " + y); first = false; lastYear = y; } @@ -188,7 +188,7 @@ cal.set(292269055, Calendar.DECEMBER, dom, h, 0); Date d = cal.getTime(); cal.setTime(d); - logln("" + h + ":00 Dec "+dom+", 292269055 BC -> " + + System.out.println("" + h + ":00 Dec "+dom+", 292269055 BC -> " + Long.toHexString(d.getTime()) + " -> " + dateFormat.format(cal.getTime())); } @@ -197,7 +197,7 @@ long t = 0x80000000018c5c00L; // Dec 3, 292269055 BC while (t<0) { cal.setTime(new Date(t)); - logln("0x" + Long.toHexString(t) + " -> " + + System.out.println("0x" + Long.toHexString(t) + " -> " + dateFormat.format(cal.getTime())); t -= ONE_HOUR; } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarRegression.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarRegression.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarRegression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarRegression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -32,7 +32,7 @@ * 4652815 4652830 4740554 4936355 4738710 4633646 4846659 4822110 4960642 * 4973919 4980088 4965624 5013094 5006864 8152077 * @library /java/text/testlib - * @run main CalendarRegression + * @run junit CalendarRegression */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -53,22 +53,16 @@ import static java.util.Calendar.*; -public class CalendarRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new CalendarRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class CalendarRegression { /* Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 ==== Here is the test ==== - public static void main (String args[]) { - java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); - logln("expected=1901-04-05 05:08:13.1234567"); - logln(" result="+t); - } - ==== Here is the output of the test on Solaris or NT ==== expected=1901-04-05 05:08:13.1234567 result=1901-04-05 05:08:13.1234567 @@ -77,6 +71,7 @@ expected=1901-04-05 05:08:13.1234567 result=1901-04-05 06:08:13.1234567 */ + @Test public void Test4031502() { // This bug actually occurs on Windows NT as well, and doesn't // require the host zone to be set; it can be set in Java. @@ -88,7 +83,7 @@ cal.clear(); cal.set(1900, 15, 5, 5, 8, 13); if (cal.get(HOUR) != 5) { - logln(zone.getID() + " " + System.out.println(zone.getID() + " " + //zone.useDaylightTime() + " " + cal.get(DST_OFFSET) / (60 * 60 * 1000) + " " + zone.getRawOffset() / (60 * 60 * 1000) @@ -97,10 +92,11 @@ } } if (bad) { - errln("TimeZone problems with GC"); + fail("TimeZone problems with GC"); } } + @Test public void Test4035301() { GregorianCalendar c = new GregorianCalendar(98, 8, 7); GregorianCalendar d = new GregorianCalendar(98, 8, 7); @@ -110,10 +106,11 @@ || c.before(c) || !c.equals(c) || !c.equals(d)) { - errln("Fail"); + fail("Fail"); } } + @Test public void Test4040996() { String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000); SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]); @@ -125,97 +122,100 @@ calendar.set(DAY_OF_MONTH, 18); calendar.set(SECOND, 30); - logln("MONTH: " + calendar.get(MONTH)); - logln("DAY_OF_MONTH: " + System.out.println("MONTH: " + calendar.get(MONTH)); + System.out.println("DAY_OF_MONTH: " + calendar.get(DAY_OF_MONTH)); - logln("MINUTE: " + calendar.get(MINUTE)); - logln("SECOND: " + calendar.get(SECOND)); + System.out.println("MINUTE: " + calendar.get(MINUTE)); + System.out.println("SECOND: " + calendar.get(SECOND)); calendar.add(SECOND, 6); //This will print out todays date for MONTH and DAY_OF_MONTH //instead of the date it was set to. //This happens when adding MILLISECOND or MINUTE also - logln("MONTH: " + calendar.get(MONTH)); - logln("DAY_OF_MONTH: " + System.out.println("MONTH: " + calendar.get(MONTH)); + System.out.println("DAY_OF_MONTH: " + calendar.get(DAY_OF_MONTH)); - logln("MINUTE: " + calendar.get(MINUTE)); - logln("SECOND: " + calendar.get(SECOND)); + System.out.println("MINUTE: " + calendar.get(MINUTE)); + System.out.println("SECOND: " + calendar.get(SECOND)); if (calendar.get(MONTH) != 3 || calendar.get(DAY_OF_MONTH) != 18 || calendar.get(SECOND) != 36) { - errln("Fail: Calendar.add misbehaves"); + fail("Fail: Calendar.add misbehaves"); } } + @Test public void Test4051765() { Calendar cal = Calendar.getInstance(); cal.setLenient(false); cal.set(DAY_OF_WEEK, 0); try { cal.getTime(); - errln("Fail: DAY_OF_WEEK 0 should be disallowed"); + fail("Fail: DAY_OF_WEEK 0 should be disallowed"); } catch (IllegalArgumentException e) { return; } } /* User error - no bug here + @Test public void Test4059524() { // Create calendar for April 10, 1997 GregorianCalendar calendar = new GregorianCalendar(); // print out a bunch of interesting things - logln("ERA: " + calendar.get(calendar.ERA)); - logln("YEAR: " + calendar.get(calendar.YEAR)); - logln("MONTH: " + calendar.get(calendar.MONTH)); - logln("WEEK_OF_YEAR: " + + System.out.println("ERA: " + calendar.get(calendar.ERA)); + System.out.println("YEAR: " + calendar.get(calendar.YEAR)); + System.out.println("MONTH: " + calendar.get(calendar.MONTH)); + System.out.println("WEEK_OF_YEAR: " + calendar.get(calendar.WEEK_OF_YEAR)); - logln("WEEK_OF_MONTH: " + + System.out.println("WEEK_OF_MONTH: " + calendar.get(calendar.WEEK_OF_MONTH)); - logln("DATE: " + calendar.get(calendar.DATE)); - logln("DAY_OF_MONTH: " + + System.out.println("DATE: " + calendar.get(calendar.DATE)); + System.out.println("DAY_OF_MONTH: " + calendar.get(calendar.DAY_OF_MONTH)); - logln("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); - logln("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); - logln("DAY_OF_WEEK_IN_MONTH: " + + System.out.println("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); + System.out.println("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); + System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); - logln("AM_PM: " + calendar.get(calendar.AM_PM)); - logln("HOUR: " + calendar.get(calendar.HOUR)); - logln("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); - logln("MINUTE: " + calendar.get(calendar.MINUTE)); - logln("SECOND: " + calendar.get(calendar.SECOND)); - logln("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); - logln("ZONE_OFFSET: " + System.out.println("AM_PM: " + calendar.get(calendar.AM_PM)); + System.out.println("HOUR: " + calendar.get(calendar.HOUR)); + System.out.println("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); + System.out.println("MINUTE: " + calendar.get(calendar.MINUTE)); + System.out.println("SECOND: " + calendar.get(calendar.SECOND)); + System.out.println("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); + System.out.println("ZONE_OFFSET: " + (calendar.get(calendar.ZONE_OFFSET)/(60*60*1000))); - logln("DST_OFFSET: " + System.out.println("DST_OFFSET: " + (calendar.get(calendar.DST_OFFSET)/(60*60*1000))); calendar = new GregorianCalendar(1997,3,10); calendar.getTime(); - logln("April 10, 1997"); - logln("ERA: " + calendar.get(calendar.ERA)); - logln("YEAR: " + calendar.get(calendar.YEAR)); - logln("MONTH: " + calendar.get(calendar.MONTH)); - logln("WEEK_OF_YEAR: " + + System.out.println("April 10, 1997"); + System.out.println("ERA: " + calendar.get(calendar.ERA)); + System.out.println("YEAR: " + calendar.get(calendar.YEAR)); + System.out.println("MONTH: " + calendar.get(calendar.MONTH)); + System.out.println("WEEK_OF_YEAR: " + calendar.get(calendar.WEEK_OF_YEAR)); - logln("WEEK_OF_MONTH: " + + System.out.println("WEEK_OF_MONTH: " + calendar.get(calendar.WEEK_OF_MONTH)); - logln("DATE: " + calendar.get(calendar.DATE)); - logln("DAY_OF_MONTH: " + + System.out.println("DATE: " + calendar.get(calendar.DATE)); + System.out.println("DAY_OF_MONTH: " + calendar.get(calendar.DAY_OF_MONTH)); - logln("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); - logln("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); - logln("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); - logln("AM_PM: " + calendar.get(calendar.AM_PM)); - logln("HOUR: " + calendar.get(calendar.HOUR)); - logln("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); - logln("MINUTE: " + calendar.get(calendar.MINUTE)); - logln("SECOND: " + calendar.get(calendar.SECOND)); - logln("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); - logln("ZONE_OFFSET: " + System.out.println("DAY_OF_YEAR: " + calendar.get(calendar.DAY_OF_YEAR)); + System.out.println("DAY_OF_WEEK: " + calendar.get(calendar.DAY_OF_WEEK)); + System.out.println("DAY_OF_WEEK_IN_MONTH: " + calendar.get(calendar.DAY_OF_WEEK_IN_MONTH)); + System.out.println("AM_PM: " + calendar.get(calendar.AM_PM)); + System.out.println("HOUR: " + calendar.get(calendar.HOUR)); + System.out.println("HOUR_OF_DAY: " + calendar.get(calendar.HOUR_OF_DAY)); + System.out.println("MINUTE: " + calendar.get(calendar.MINUTE)); + System.out.println("SECOND: " + calendar.get(calendar.SECOND)); + System.out.println("MILLISECOND: " + calendar.get(calendar.MILLISECOND)); + System.out.println("ZONE_OFFSET: " + (calendar.get(calendar.ZONE_OFFSET)/(60*60*1000))); // in hours - logln("DST_OFFSET: " + System.out.println("DST_OFFSET: " + (calendar.get(calendar.DST_OFFSET)/(60*60*1000))); // in hours } */ + @Test public void Test4059654() { GregorianCalendar gc = new GregorianCalendar(); @@ -231,10 +231,11 @@ @SuppressWarnings("deprecation") Date exp = new Date(97, 3, 1, 0, 0, 0); if (!cd.equals(exp)) { - errln("Fail: Calendar.set broken. Got " + cd + " Want " + exp); + fail("Fail: Calendar.set broken. Got " + cd + " Want " + exp); } } + @Test public void Test4061476() { SimpleDateFormat fmt = new SimpleDateFormat("ddMMMyy", Locale.UK); Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"), @@ -246,14 +247,15 @@ } catch (Exception e) { } cal.set(HOUR_OF_DAY, 13); - logln("Hour: " + cal.get(HOUR_OF_DAY)); + System.out.println("Hour: " + cal.get(HOUR_OF_DAY)); cal.add(HOUR_OF_DAY, 6); - logln("Hour: " + cal.get(HOUR_OF_DAY)); + System.out.println("Hour: " + cal.get(HOUR_OF_DAY)); if (cal.get(HOUR_OF_DAY) != 19) { - errln("Fail: Want 19 Got " + cal.get(HOUR_OF_DAY)); + fail("Fail: Want 19 Got " + cal.get(HOUR_OF_DAY)); } } + @Test public void Test4070502() { @SuppressWarnings("deprecation") Date d = getAssociatedDate(new Date(98, 0, 30)); @@ -261,7 +263,7 @@ cal.setTime(d); if (cal.get(DAY_OF_WEEK) == SATURDAY || cal.get(DAY_OF_WEEK) == SUNDAY) { - errln("Fail: Want weekday Got " + d); + fail("Fail: Want weekday Got " + d); } } @@ -289,6 +291,7 @@ return cal.getTime(); } + @Test public void Test4071197() { dowTest(false); dowTest(true); @@ -303,29 +306,31 @@ int dow = cal.get(DAY_OF_WEEK); int min = cal.getMinimum(DAY_OF_WEEK); int max = cal.getMaximum(DAY_OF_WEEK); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (min != SUNDAY || max != SATURDAY) { - errln("FAIL: Min/max bad"); + fail("FAIL: Min/max bad"); } if (dow < min || dow > max) { - errln("FAIL: Day of week " + dow + " out of range"); + fail("FAIL: Day of week " + dow + " out of range"); } if (dow != SUNDAY) { - errln("FAIL: Day of week should be SUNDAY Got " + dow); + fail("FAIL: Day of week should be SUNDAY Got " + dow); } } @SuppressWarnings("deprecation") + @Test public void Test4071385() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date(98, JUNE, 24)); cal.set(MONTH, NOVEMBER); // change a field - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(new Date(98, NOVEMBER, 24))) { - errln("Fail"); + fail("Fail"); } } + @Test public void Test4073929() { GregorianCalendar foo1 = new GregorianCalendar(1997, 8, 27); foo1.add(DAY_OF_MONTH, +1); @@ -335,10 +340,11 @@ if (testyear != 1997 || testmonth != 8 || testday != 28) { - errln("Fail: Calendar not initialized"); + fail("Fail: Calendar not initialized"); } } + @Test public void Test4083167() { TimeZone saveZone = TimeZone.getDefault(); try { @@ -351,7 +357,7 @@ + cal.get(SECOND) * 1000L + cal.get(MILLISECOND); - logln("Current time: " + firstDate.toString()); + System.out.println("Current time: " + firstDate.toString()); for (int validity = 0; validity < 30; validity++) { Date lastDate = new Date(firstDate.getTime() @@ -362,7 +368,7 @@ + cal.get(SECOND) * 1000L + cal.get(MILLISECOND); if (firstMillisInDay != millisInDay) { - errln("Day has shifted " + lastDate); + fail("Day has shifted " + lastDate); } } } finally { @@ -370,6 +376,7 @@ } } + @Test public void Test4086724() { SimpleDateFormat date; TimeZone saveZone = TimeZone.getDefault(); @@ -387,12 +394,12 @@ Date now = cal.getTime(); String formattedDate = date.format(now); if (!formattedDate.equals(summerTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } int weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 40) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -400,12 +407,12 @@ now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -413,12 +420,12 @@ now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -426,12 +433,12 @@ now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { - errln("Wrong display name \"" + formattedDate + fail("Wrong display name \"" + formattedDate + "\" for <" + now + ">"); } weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 2) { - errln("Wrong week-of-year " + weekOfYear + fail("Wrong week-of-year " + weekOfYear + " for <" + now + ">"); } @@ -441,6 +448,7 @@ } } + @Test public void Test4092362() { GregorianCalendar cal1 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); /*cal1.set( Calendar.YEAR, 1997 ); @@ -450,8 +458,8 @@ cal1.set( Calendar.MINUTE, 20 ); cal1.set( Calendar.SECOND, 40 ); */ - logln(" Cal1 = " + cal1.getTime().getTime()); - logln(" Cal1 time in ms = " + cal1.get(MILLISECOND)); + System.out.println(" Cal1 = " + cal1.getTime().getTime()); + System.out.println(" Cal1 time in ms = " + cal1.get(MILLISECOND)); for (int k = 0; k < 100; k++); GregorianCalendar cal2 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); @@ -462,21 +470,23 @@ cal2.set( Calendar.MINUTE, 20 ); cal2.set( Calendar.SECOND, 40 ); */ - logln(" Cal2 = " + cal2.getTime().getTime()); - logln(" Cal2 time in ms = " + cal2.get(MILLISECOND)); + System.out.println(" Cal2 = " + cal2.getTime().getTime()); + System.out.println(" Cal2 time in ms = " + cal2.get(MILLISECOND)); if (!cal1.equals(cal2)) { - errln("Fail: Milliseconds randomized"); + fail("Fail: Milliseconds randomized"); } } + @Test public void Test4095407() { GregorianCalendar a = new GregorianCalendar(1997, NOVEMBER, 13); int dow = a.get(DAY_OF_WEEK); if (dow != THURSDAY) { - errln("Fail: Want THURSDAY Got " + dow); + fail("Fail: Want THURSDAY Got " + dow); } } + @Test public void Test4096231() { TimeZone GMT = TimeZone.getTimeZone("GMT"); TimeZone PST = TimeZone.getTimeZone("PST"); @@ -485,19 +495,19 @@ Calendar cal1 = new GregorianCalendar(PST); cal1.setTime(new Date(880698639000L)); int p; - logln("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); + System.out.println("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); cal1.setTimeZone(GMT); // Issue 1: Changing the timezone doesn't change the // represented time. int h1, h2; - logln("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); + System.out.println("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); cal1.setTime(new Date(880698639000L)); - logln("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); + System.out.println("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); // Note: This test had a bug in it. It wanted h1!=h2, when // what was meant was h1!=p. Fixed this concurrent with fix // to 4177484. if (p == h1 || h1 != h2) { - errln("Fail: Hour same in different zones"); + fail("Fail: Hour same in different zones"); } Calendar cal2 = new GregorianCalendar(GMT); @@ -513,11 +523,11 @@ cal1.get(SECOND)); long t1, t2, t3, t4; - logln("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); + System.out.println("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); cal3.set(year, month, day, hr, min, sec); - logln("RPST 1 is: " + (t2 = cal3.getTime().getTime())); + System.out.println("RPST 1 is: " + (t2 = cal3.getTime().getTime())); cal3.setTimeZone(GMT); - logln("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); + System.out.println("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); cal3.set(cal1.get(YEAR), cal1.get(MONTH), cal1.get(DAY_OF_MONTH), @@ -527,40 +537,42 @@ // Issue 2: Calendar continues to use the timezone in its // constructor for set() conversions, regardless // of calls to setTimeZone() - logln("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); + System.out.println("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); if (t1 == t2 || t1 != t4 || t2 != t3) { - errln("Fail: Calendar zone behavior faulty"); + fail("Fail: Calendar zone behavior faulty"); } } + @Test public void Test4096539() { int[] y = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int x = 0; x < 12; x++) { GregorianCalendar gc = new GregorianCalendar(1997, x, y[x]); int m1, m2; - log((m1 = gc.get(MONTH) + 1) + "/" + System.out.println((m1 = gc.get(MONTH) + 1) + "/" + gc.get(DATE) + "/" + gc.get(YEAR) + " + 1mo = "); gc.add(MONTH, 1); - logln((m2 = gc.get(MONTH) + 1) + "/" + System.out.println((m2 = gc.get(MONTH) + 1) + "/" + gc.get(DATE) + "/" + gc.get(YEAR) ); int m = (m1 % 12) + 1; if (m2 != m) { - errln("Fail: Want " + m + " Got " + m2); + fail("Fail: Want " + m + " Got " + m2); } } } + @Test public void Test4100311() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -568,16 +580,17 @@ cal.set(YEAR, 1997); cal.set(DAY_OF_YEAR, 1); Date d = cal.getTime(); // Should be Jan 1 - logln(d.toString()); + System.out.println(d.toString()); if (cal.get(DAY_OF_YEAR) != 1) { - errln("Fail: DAY_OF_YEAR not set"); + fail("Fail: DAY_OF_YEAR not set"); } } + @Test public void Test4103271() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -594,7 +607,7 @@ testCal.setMinimalDaysInFirstWeek(minDays); testCal.setFirstDayOfWeek(firstDay); testDesc = ("Test" + String.valueOf(firstDay) + String.valueOf(minDays)); - logln(testDesc + " => 1st day of week=" + System.out.println(testDesc + " => 1st day of week=" + String.valueOf(firstDay) + ", minimum days in first week=" + String.valueOf(minDays)); @@ -609,7 +622,7 @@ calWOY = String.valueOf(actWOY); output = testDesc + " - " + sdf.format(d) + "\t"; output = output + "\t" + calWOY; - logln(output); + System.out.println(output); fail = true; } } @@ -626,18 +639,18 @@ 1, 1, 1, 1, 1, 1, 1}; testCal.setFirstDayOfWeek(SUNDAY); for (int j = 0; j < DATA.length; j += 22) { - logln("Minimal days in first week = " + DATA[j] + System.out.println("Minimal days in first week = " + DATA[j] + " Week starts on Sunday"); testCal.setMinimalDaysInFirstWeek(DATA[j]); testCal.set(1997, DECEMBER, 21); for (int i = 0; i < 21; ++i) { int woy = testCal.get(WEEK_OF_YEAR); - log("\t" + testCal.getTime() + " " + woy); + System.out.println("\t" + testCal.getTime() + " " + woy); if (woy != DATA[j + 1 + i]) { - log(" ERROR"); + System.out.println(" ERROR"); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } // Now compute the time from the fields, and make sure we @@ -648,10 +661,10 @@ testCal.set(WEEK_OF_YEAR, DATA[j + 1 + i]); testCal.set(DAY_OF_WEEK, (i % 7) + SUNDAY); if (!testCal.getTime().equals(save)) { - logln(" Parse failed: " + testCal.getTime()); + System.out.println(" Parse failed: " + testCal.getTime()); fail = true; } else { - logln(" Passed"); + System.out.println(" Passed"); } testCal.setTime(save); @@ -682,12 +695,12 @@ testCal.set(YEAR, y); testCal.set(WEEK_OF_YEAR, woy); testCal.set(DAY_OF_WEEK, dow); - log(y + "-W" + woy + "-DOW" + dow); + System.out.println(y + "-W" + woy + "-DOW" + dow); if (!testCal.getTime().equals(exp)) { - logln(" FAILED expect: " + exp + "\n got: " + testCal.getTime()); + System.out.println(" FAILED expect: " + exp + "\n got: " + testCal.getTime()); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } } @@ -714,14 +727,14 @@ } else { testCal.roll(WEEK_OF_YEAR, amount); } - log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + System.out.println((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + amount + ")\t " + before + "\n\t\t => " + testCal.getTime()); if (!after.equals(testCal.getTime())) { - logln("\tFAIL\n\t\texp: " + after); + System.out.println("\tFAIL\n\t\texp: " + after); fail = true; } else { - logln(" OK"); + System.out.println(" OK"); } testCal.setTime(after); @@ -730,22 +743,23 @@ } else { testCal.roll(WEEK_OF_YEAR, -amount); } - log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + System.out.println((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + (-amount) + ") " + after + "\n\t\t => " + testCal.getTime()); if (!before.equals(testCal.getTime())) { - logln("\tFAIL\n\t\texp: " + before); + System.out.println("\tFAIL\n\t\texp: " + before); fail = true; } else { - logln("\tOK"); + System.out.println("\tOK"); } } if (fail) { - errln("Fail: Week of year misbehaving"); + fail("Fail: Week of year misbehaving"); } } + @Test public void Test4106136() { Locale saveLocale = Locale.getDefault(); try { @@ -758,7 +772,7 @@ NumberFormat.getAvailableLocales().length}; for (int j = 0; j < n.length; ++j) { if (n[j] == 0) { - errln("Fail: No locales for " + locales[i]); + fail("Fail: No locales for " + locales[i]); } } } @@ -768,6 +782,7 @@ } @SuppressWarnings("deprecation") + @Test public void Test4108764() { Date d00 = new Date(97, MARCH, 15, 12, 00, 00); Date d01 = new Date(97, MARCH, 15, 12, 00, 56); @@ -779,42 +794,43 @@ cal.setTime(d11); cal.clear(MINUTE); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d01)) { - errln("Fail: clear(MINUTE) broken"); + fail("Fail: clear(MINUTE) broken"); } cal.set(SECOND, 0); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d00)) { - errln("Fail: set(SECOND, 0) broken"); + fail("Fail: set(SECOND, 0) broken"); } cal.setTime(d11); cal.set(SECOND, 0); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d10)) { - errln("Fail: set(SECOND, 0) broken #2"); + fail("Fail: set(SECOND, 0) broken #2"); } cal.clear(MINUTE); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(d00)) { - errln("Fail: clear(MINUTE) broken #2"); + fail("Fail: clear(MINUTE) broken #2"); } cal.clear(); - logln(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); if (!cal.getTime().equals(epoch)) { - errln("Fail: clear() broken Want " + epoch); + fail("Fail: clear() broken Want " + epoch); } } @SuppressWarnings("deprecation") + @Test public void Test4114578() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -849,28 +865,28 @@ int amt = (int) DATA[i + 2]; long expectedChange = DATA[i + 3]; - log(date.toString()); + System.out.println(date.toString()); cal.setTime(date); switch ((int) DATA[i + 1]) { case ADD: - log(" add (HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); + System.out.println(" add (HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); cal.add(HOUR, amt); break; case ROLL: - log(" roll(HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); + System.out.println(" roll(HOUR," + (amt < 0 ? "" : "+") + amt + ")= "); cal.roll(HOUR, amt); break; } - log(cal.getTime().toString()); + System.out.println(cal.getTime().toString()); long change = cal.getTime().getTime() - date.getTime(); if (change != expectedChange) { fail = true; - logln(" FAIL"); + System.out.println(" FAIL"); } else { - logln(" OK"); + System.out.println(" OK"); } } } finally { @@ -878,29 +894,31 @@ } if (fail) { - errln("Fail: roll/add misbehaves around DST onset/cease"); + fail("Fail: roll/add misbehaves around DST onset/cease"); } } /** * Make sure maximum for HOUR field is 11, not 12. */ + @Test public void Test4118384() { Calendar cal = Calendar.getInstance(); if (cal.getMaximum(HOUR) != 11 || cal.getLeastMaximum(HOUR) != 11 || cal.getActualMaximum(HOUR) != 11) { - errln("Fail: maximum of HOUR field should be 11"); + fail("Fail: maximum of HOUR field should be 11"); } } /** * Check isLeapYear for BC years. */ + @Test public void Test4125881() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -910,10 +928,10 @@ for (int y = -20; y <= 10; ++y) { cal.set(ERA, y < 1 ? GregorianCalendar.BC : GregorianCalendar.AD); cal.set(YEAR, y < 1 ? 1 - y : y); - logln(y + " = " + fmt.format(cal.getTime()) + " " + System.out.println(y + " = " + fmt.format(cal.getTime()) + " " + cal.isLeapYear(y)); if (cal.isLeapYear(y) != ((y + 40) % 4 == 0)) { - errln("Leap years broken"); + fail("Leap years broken"); } } } @@ -922,10 +940,11 @@ * Prove that GregorianCalendar is proleptic (it used to cut off * at 45 BC, and not have leap years before then). */ + @Test public void Test4125892() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -939,7 +958,7 @@ cal.add(DATE, 1); if (cal.get(DATE) != 29 || !cal.isLeapYear(-80)) { // -80 == 81 BC - errln("Calendar not proleptic"); + fail("Calendar not proleptic"); } } @@ -948,6 +967,7 @@ * Calendar needs a good implementation that subclasses can override, * and GregorianCalendar should use that implementation. */ + @Test public void Test4136399() { /* Note: This test is actually more strict than it has to be. * Technically, there is no requirement that unequal objects have @@ -961,24 +981,24 @@ Calendar a = Calendar.getInstance(); Calendar b = (Calendar) a.clone(); if (a.hashCode() != b.hashCode()) { - errln("Calendar hash code unequal for cloned objects"); + fail("Calendar hash code unequal for cloned objects"); } b.setMinimalDaysInFirstWeek(7 - a.getMinimalDaysInFirstWeek()); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores minimal days in first week"); + fail("Calendar hash code ignores minimal days in first week"); } b.setMinimalDaysInFirstWeek(a.getMinimalDaysInFirstWeek()); b.setFirstDayOfWeek((a.getFirstDayOfWeek() % 7) + 1); // Next day if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores first day of week"); + fail("Calendar hash code ignores first day of week"); } b.setFirstDayOfWeek(a.getFirstDayOfWeek()); b.setLenient(!a.isLenient()); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores lenient setting"); + fail("Calendar hash code ignores lenient setting"); } b.setLenient(a.isLenient()); @@ -986,36 +1006,37 @@ // of a reference -- this is true as of this writing b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset() + 60 * 60 * 1000); if (a.hashCode() == b.hashCode()) { - errln("Calendar hash code ignores zone"); + fail("Calendar hash code ignores zone"); } b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset()); GregorianCalendar c = new GregorianCalendar(); GregorianCalendar d = (GregorianCalendar) c.clone(); if (c.hashCode() != d.hashCode()) { - errln("GregorianCalendar hash code unequal for clones objects"); + fail("GregorianCalendar hash code unequal for clones objects"); } Date cutover = c.getGregorianChange(); d.setGregorianChange(new Date(cutover.getTime() + 24 * 60 * 60 * 1000)); if (c.hashCode() == d.hashCode()) { - errln("GregorianCalendar hash code ignores cutover"); + fail("GregorianCalendar hash code ignores cutover"); } } /** * GregorianCalendar.equals() ignores cutover date */ + @Test public void Test4141665() { GregorianCalendar cal = new GregorianCalendar(); GregorianCalendar cal2 = (GregorianCalendar) cal.clone(); Date cut = cal.getGregorianChange(); Date cut2 = new Date(cut.getTime() + 100 * 24 * 60 * 60 * 1000L); // 100 days later if (!cal.equals(cal2)) { - errln("Cloned GregorianCalendars not equal"); + fail("Cloned GregorianCalendars not equal"); } cal2.setGregorianChange(cut2); if (cal.equals(cal2)) { - errln("GregorianCalendar.equals() ignores cutover"); + fail("GregorianCalendar.equals() ignores cutover"); } } @@ -1023,16 +1044,17 @@ * Bug states that ArrayIndexOutOfBoundsException is thrown by GregorianCalendar.roll() * when IllegalArgumentException should be. */ + @Test public void Test4142933() { GregorianCalendar calendar = new GregorianCalendar(); try { calendar.roll(-1, true); - errln("Test failed, no exception trown"); + fail("Test failed, no exception trown"); } catch (IllegalArgumentException e) { // OK: Do nothing // logln("Test passed"); } catch (Exception e) { - errln("Test failed. Unexpected exception is thrown: " + e); + fail("Test failed. Unexpected exception is thrown: " + e); e.printStackTrace(); } } @@ -1044,6 +1066,7 @@ * report to therefore only check the behavior of a calendar with a zero raw * offset zone. */ + @Test public void Test4145158() { GregorianCalendar calendar = new GregorianCalendar(); @@ -1058,13 +1081,14 @@ int era2 = calendar.get(ERA); if (year1 == year2 && era1 == era2) { - errln("Fail: Long.MIN_VALUE or Long.MAX_VALUE wrapping around"); + fail("Fail: Long.MIN_VALUE or Long.MAX_VALUE wrapping around"); } } /** * Maximum value for YEAR field wrong. */ + @Test public void Test4145983() { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeZone(TimeZone.getTimeZone("GMT")); @@ -1074,7 +1098,7 @@ int year = calendar.get(YEAR); int maxYear = calendar.getMaximum(YEAR); if (year > maxYear) { - errln("Failed for " + DATES[i].getTime() + " ms: year=" + fail("Failed for " + DATES[i].getTime() + " ms: year=" + year + ", maxYear=" + maxYear); } } @@ -1086,6 +1110,7 @@ * report test was written. In reality the bug is restricted to the DAY_OF_YEAR * field. - liu 6/29/98 */ + @Test public void Test4147269() { final String[] fieldName = { "ERA", @@ -1121,7 +1146,7 @@ calendar.getTime(); // Force time computation // We expect an exception to be thrown. If we fall through // to the next line, then we have a bug. - errln("Test failed with field " + fieldName[field] + fail("Test failed with field " + fieldName[field] + ", date before: " + date + ", date after: " + calendar.getTime() + ", value: " + value + " (max = " + max + ")"); @@ -1135,6 +1160,7 @@ * doesn't behave as a pure Julian calendar. * CANNOT REPRODUCE THIS BUG */ + @Test public void Test4149677() { TimeZone[] zones = {TimeZone.getTimeZone("GMT"), TimeZone.getTimeZone("PST"), @@ -1145,11 +1171,11 @@ // Make sure extreme values don't wrap around calendar.setTime(new Date(Long.MIN_VALUE)); if (calendar.get(ERA) != GregorianCalendar.BC) { - errln("Fail: Date(Long.MIN_VALUE) has an AD year in " + zones[i]); + fail("Fail: Date(Long.MIN_VALUE) has an AD year in " + zones[i]); } calendar.setTime(new Date(Long.MAX_VALUE)); if (calendar.get(ERA) != GregorianCalendar.AD) { - errln("Fail: Date(Long.MAX_VALUE) has a BC year in " + zones[i]); + fail("Fail: Date(Long.MAX_VALUE) has a BC year in " + zones[i]); } calendar.setGregorianChange(new Date(Long.MAX_VALUE)); @@ -1157,9 +1183,9 @@ boolean is100Leap = calendar.isLeapYear(100); if (!is100Leap) { - errln("test failed with zone " + zones[i].getID()); - errln(" cutover date is Date(Long.MAX_VALUE)"); - errln(" isLeapYear(100) returns: " + is100Leap); + fail("test failed with zone " + zones[i].getID() + + "\n cutover date is Date(Long.MAX_VALUE)" + + "\n isLeapYear(100) returns: " + is100Leap); } } } @@ -1168,6 +1194,7 @@ * Calendar and Date HOUR broken. If HOUR is out-of-range, Calendar * and Date classes will misbehave. */ + @Test public void Test4162587() { TimeZone savedTz = TimeZone.getDefault(); TimeZone tz = TimeZone.getTimeZone("PST"); @@ -1178,29 +1205,29 @@ try { for (int i = 0; i < 5; ++i) { if (i > 0) { - logln("---"); + System.out.println("---"); } cal.clear(); cal.set(1998, APRIL, 5, i, 0); d = cal.getTime(); String s0 = d.toString(); - logln("0 " + i + ": " + s0); + System.out.println("0 " + i + ": " + s0); cal.clear(); cal.set(1998, APRIL, 4, i + 24, 0); d = cal.getTime(); String sPlus = d.toString(); - logln("+ " + i + ": " + sPlus); + System.out.println("+ " + i + ": " + sPlus); cal.clear(); cal.set(1998, APRIL, 6, i - 24, 0); d = cal.getTime(); String sMinus = d.toString(); - logln("- " + i + ": " + sMinus); + System.out.println("- " + i + ": " + sMinus); if (!s0.equals(sPlus) || !s0.equals(sMinus)) { - errln("Fail: All three lines must match"); + fail("Fail: All three lines must match"); } } } finally { @@ -1211,27 +1238,29 @@ /** * Adding 12 months behaves differently from adding 1 year */ + @Test public void Test4165343() { GregorianCalendar calendar = new GregorianCalendar(1996, FEBRUARY, 29); Date start = calendar.getTime(); - logln("init date: " + start); + System.out.println("init date: " + start); calendar.add(MONTH, 12); Date date1 = calendar.getTime(); - logln("after adding 12 months: " + date1); + System.out.println("after adding 12 months: " + date1); calendar.setTime(start); calendar.add(YEAR, 1); Date date2 = calendar.getTime(); - logln("after adding one year : " + date2); + System.out.println("after adding one year : " + date2); if (date1.equals(date2)) { - logln("Test passed"); + System.out.println("Test passed"); } else { - errln("Test failed"); + fail("Test failed"); } } /** * GregorianCalendar.getActualMaximum() does not account for first day of week. */ + @Test public void Test4166109() { /* Test month: * @@ -1249,7 +1278,7 @@ GregorianCalendar calendar = new GregorianCalendar(Locale.US); calendar.set(1998, MARCH, 1); calendar.setMinimalDaysInFirstWeek(1); - logln("Date: " + calendar.getTime()); + System.out.println("Date: " + calendar.getTime()); int firstInMonth = calendar.get(DAY_OF_MONTH); @@ -1258,7 +1287,7 @@ int returned = calendar.getActualMaximum(field); int expected = (31 + ((firstInMonth - firstInWeek + 7) % 7) + 6) / 7; - logln("First day of week = " + firstInWeek + System.out.println("First day of week = " + firstInWeek + " getActualMaximum(WEEK_OF_MONTH) = " + returned + " expected = " + expected + ((returned == expected) ? " ok" : " FAIL")); @@ -1268,7 +1297,7 @@ } } if (!passed) { - errln("Test failed"); + fail("Test failed"); } } @@ -1279,6 +1308,7 @@ * setGregorianChange didn't change object's date. But it was * changed. See 4928615. */ + @Test public void Test4167060() { int field = YEAR; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy G", @@ -1293,7 +1323,7 @@ String[] id = {"Hybrid", "Gregorian", "Julian"}; for (int k = 0; k < 3; ++k) { - logln("--- " + id[k] + " ---"); + System.out.println("--- " + id[k] + " ---"); for (int j = 0; j < dates.length; ++j) { GregorianCalendar calendar = new GregorianCalendar(); @@ -1308,8 +1338,8 @@ Date dateBefore = calendar.getTime(); int maxYear = calendar.getActualMaximum(field); - logln("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); - logln("date before: " + format.format(dateBefore)); + System.out.println("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); + System.out.println("date before: " + format.format(dateBefore)); int[] years = {2000, maxYear - 1, maxYear, maxYear + 1}; @@ -1320,12 +1350,12 @@ int newYear = calendar.get(field); calendar.setTime(dateBefore); // restore calendar for next use - logln(" Year " + years[i] + (valid ? " ok " : " bad") + System.out.println(" Year " + years[i] + (valid ? " ok " : " bad") + " => " + format.format(dateAfter)); if (valid && newYear != years[i]) { - errln(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); + fail(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); } else if (!valid && newYear == years[i]) { - errln(" FAIL: " + newYear + " should be invalid"); + fail(" FAIL: " + newYear + " should be invalid"); } } } @@ -1336,10 +1366,11 @@ * Calendar.roll broken * This bug relies on the TimeZone bug 4173604 to also be fixed. */ + @Test public void Test4173516() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1365,11 +1396,11 @@ cal.roll(HOUR, 0x7F000000); cal.roll(HOUR, -0x7F000000); if (cal.getTime().getTime() != 0) { - errln("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); + fail("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); } for (int op = 0; op < 2; ++op) { - logln("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); + System.out.println("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); for (int field = 0; field < FIELD_COUNT; ++field) { if (field != ZONE_OFFSET @@ -1395,7 +1426,7 @@ || cal.get(MINUTE) != fields[4] || cal.get(SECOND) != fields[5] || cal.get(MILLISECOND) != fields[6]) { - errln("Field " + field + fail("Field " + field + " (" + fieldNames[field] + ") FAIL, expected " + fields[0] @@ -1417,7 +1448,7 @@ cal.set(fields[0], fields[1], fields[2], fields[3], fields[4], fields[5]); cal.set(MILLISECOND, fields[6]); - errln(cal.get(YEAR) + fail(cal.get(YEAR) + "/" + (cal.get(MONTH) + 1) + "/" + cal.get(DATE) + " " + cal.get(HOUR_OF_DAY) @@ -1435,7 +1466,7 @@ long t = cal.getTime().getTime(); long delta = t - prev; prev = t; - errln((op == 0 ? "add(" : "roll(") + fail((op == 0 ? "add(" : "roll(") + fieldNames[field] + ", " + (i < limit ? "+" : "-") + "1) => " + cal.get(YEAR) @@ -1457,6 +1488,7 @@ } } + @Test public void Test4174361() { GregorianCalendar calendar = new GregorianCalendar(1996, 1, 29); @@ -1470,13 +1502,14 @@ int d2 = calendar.get(DAY_OF_MONTH); if (d1 != d2) { - errln("adding months to Feb 29 broken"); + fail("adding months to Feb 29 broken"); } } /** * Calendar does not update field values when setTimeZone is called. */ + @Test public void Test4177484() { TimeZone PST = TimeZone.getTimeZone("PST"); TimeZone EST = TimeZone.getTimeZone("EST"); @@ -1488,7 +1521,7 @@ cal.setTimeZone(EST); int h2 = cal.get(HOUR_OF_DAY); if (h1 == h2) { - errln("FAIL: Fields not updated after setTimeZone"); + fail("FAIL: Fields not updated after setTimeZone"); } // getTime() must NOT change when time zone is changed. @@ -1500,13 +1533,14 @@ cal.setTimeZone(EST); Date est10 = cal.getTime(); if (!pst10.equals(est10)) { - errln("FAIL: setTimeZone changed time"); + fail("FAIL: setTimeZone changed time"); } } /** * Week of year is wrong at the start and end of the year. */ + @Test public void Test4197699() { GregorianCalendar cal = new GregorianCalendar(); cal.setFirstDayOfWeek(MONDAY); @@ -1523,14 +1557,14 @@ int expWOY = DATA[i++]; int actWOY = cal.get(WEEK_OF_YEAR); if (expWOY == actWOY) { - logln("Ok: " + fmt.format(cal.getTime())); + System.out.println("Ok: " + fmt.format(cal.getTime())); } else { - errln("FAIL: " + fmt.format(cal.getTime()) + fail("FAIL: " + fmt.format(cal.getTime()) + ", expected WOY=" + expWOY); cal.add(DATE, -8); for (int j = 0; j < 14; ++j) { cal.add(DATE, 1); - logln(fmt.format(cal.getTime())); + System.out.println(fmt.format(cal.getTime())); } } } @@ -1549,6 +1583,7 @@ * WEEK_OF_YEAR + DAY_OF_WEEK */ @SuppressWarnings("deprecation") + @Test public void Test4209071() { Calendar cal = Calendar.getInstance(Locale.US); @@ -1625,7 +1660,7 @@ Date act = cal.getTime(); if (!act.equals(exp)) { - errln("FAIL: Test " + (i / 2) + " got " + act + fail("FAIL: Test " + (i / 2) + " got " + act + ", want " + exp + " (see test/java/util/Calendar/CalendarRegression.java"); } @@ -1649,13 +1684,14 @@ cal.set(YEAR, 1997); Date actual = cal.getTime(); if (!actual.equals(DATA[i + 1])) { - errln("FAIL: Sunday " + DATA[i] + fail("FAIL: Sunday " + DATA[i] + " of Jan 1997 -> " + actual + ", want " + DATA[i + 1]); } } } + @Test public void Test4288792() throws Exception { TimeZone savedTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); @@ -1678,7 +1714,7 @@ cal.add(DATE, 1); int WOY = cal.get(WEEK_OF_YEAR); if (WOY != maxWeek) { - errln(cal.getTime() + ",got=" + WOY + fail(cal.getTime() + ",got=" + WOY + ",expected=" + maxWeek + ",min=" + j1 + ",first=" + j); } @@ -1687,7 +1723,7 @@ cal.add(DATE, 1); int WOY = cal.get(WEEK_OF_YEAR); if (WOY != 1) { - errln(cal.getTime() + ",got=" + WOY + fail(cal.getTime() + ",got=" + WOY + ",expected=1,min=" + j1 + ",first" + j); } } @@ -1698,6 +1734,7 @@ } } + @Test public void Test4328747() throws Exception { Calendar c = Calendar.getInstance(Locale.US); c.clear(); @@ -1718,7 +1755,7 @@ // Bug gives 1965 11 19 if ((result.get(YEAR) != 1966) || (result.get(MONTH) != 0) || (result.get(DATE) != 1)) { - errln("deserialized Calendar returned wrong date field(s): " + fail("deserialized Calendar returned wrong date field(s): " + result.get(YEAR) + "/" + result.get(MONTH) + "/" + result.get(DATE) + ", expected 1966/0/1"); } @@ -1728,6 +1765,7 @@ * Test whether Calendar can be serialized/deserialized correctly * even if invalid/customized TimeZone is used. */ + @Test public void Test4413980() { TimeZone savedTimeZone = TimeZone.getDefault(); try { @@ -1751,18 +1789,18 @@ if (!c.equals(t.readObject())) { pass = false; - logln("Calendar instance which uses TimeZone <" + System.out.println("Calendar instance which uses TimeZone <" + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("Calendar instance which uses TimeZone <" + System.out.println("Calendar instance which uses TimeZone <" + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { - errln("Fail: Calendar serialization/equality bug"); + fail("Fail: Calendar serialization/equality bug"); } } catch (IOException | ClassNotFoundException e) { - errln("Fail: " + e); + fail("Fail: " + e); e.printStackTrace(); } finally { TimeZone.setDefault(savedTimeZone); @@ -1772,6 +1810,7 @@ /** * 4546637: Incorrect WEEK_OF_MONTH after changing First Day Of Week */ + @Test public void Test4546637() { GregorianCalendar day = new GregorianCalendar(2001, NOVEMBER, 04); day.setMinimalDaysInFirstWeek(1); @@ -1779,13 +1818,14 @@ day.setFirstDayOfWeek(MONDAY); if (day.get(WEEK_OF_MONTH) != 1) { - errln("Fail: 2001/11/4 must be the first week of the month."); + fail("Fail: 2001/11/4 must be the first week of the month."); } } /** * 4623997: GregorianCalendar returns bad WEEK_OF_YEAR */ + @Test public void Test4623997() { GregorianCalendar cal = new GregorianCalendar(2000, JANUARY, 1); @@ -1795,7 +1835,7 @@ cal.setMinimalDaysInFirstWeek(4); if (cal.get(WEEK_OF_YEAR) != 52) { - errln("Fail: 2000/1/1 must be the 52nd week of the year."); + fail("Fail: 2000/1/1 must be the 52nd week of the year."); } } @@ -1805,11 +1845,12 @@ *

    Need to use SimpleDateFormat to test because a call to * get(int) changes internal states of a Calendar. */ + @Test public void Test4685354() { Locale locale = Locale.getDefault(); if (!TestUtils.usesAsciiDigits(locale) || !TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1831,7 +1872,7 @@ calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); + fail("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); } // The same thing must work with ZONE_OFFSET set @@ -1847,7 +1888,7 @@ calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("DAY_OF_MONTH: expected: " + expected + ", got: " + s); + fail("DAY_OF_MONTH: expected: " + expected + ", got: " + s); } expected = "1999/12/24"; // 0th week of 2000 @@ -1867,7 +1908,7 @@ calendar.set(WEEK_OF_YEAR, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); + fail("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); } // change the state back calendar.clear(); @@ -1879,7 +1920,7 @@ calendar.set(WEEK_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); + fail("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); } // Make sure the time fields work correctly. @@ -1903,7 +1944,7 @@ // time should be back to 22:59:59. s = df.format(calendar.getTime()); if (!expected.equals(s)) { - errln("MINUTE: expected: " + expected + ", got: " + s); + fail("MINUTE: expected: " + expected + ", got: " + s); } } @@ -1913,10 +1954,11 @@ *

    Need to use SimpleDateFormat to test because a call to * get(int) changes internal states of a Calendar. */ + @Test public void Test4655637() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -1935,7 +1977,7 @@ String expected = "2001/01/08"; String s = df.format(cal.getTime()); if (!expected.equals(s)) { - errln("expected: " + expected + ", got: " + s); + fail("expected: " + expected + ", got: " + s); } } @@ -1947,6 +1989,7 @@ * *

    This test case throws ArrayIndexOutOfBoundsException without the fix. */ + @Test public void Test4683492() { Calendar cal = new GregorianCalendar(2002, 3, 29, 10, 0, 0); cal.set(DAY_OF_WEEK, FRIDAY); @@ -1956,13 +1999,14 @@ String expected = "2003/01/31"; String s = df.format(cal.getTime()); if (!expected.equals(s)) { - errln("expected: " + expected + ", got: " + s); + fail("expected: " + expected + ", got: " + s); } } /** * 4080631: Calendar.hashCode is amazingly bad */ + @Test public void Test4080631() { Calendar cal = Calendar.getInstance(); int h1 = cal.hashCode(); @@ -1971,16 +2015,16 @@ Calendar cal2 = (Calendar) cal.clone(); cal.add(MILLISECOND, +1); int h3 = cal.hashCode(); - logln("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); + System.out.println("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); if (h1 == h2 || h1 == h3 || h2 == h3) { - errln("hash code is poor: hashCode=" + h1); + fail("hash code is poor: hashCode=" + h1); } h2 = cal2.hashCode(); cal.add(MILLISECOND, -1); int h4 = cal.hashCode(); - logln("hash code: h2=" + h2 + ", h4=" + h4); + System.out.println("hash code: h2=" + h2 + ", h4=" + h4); if (cal.equals(cal2) && h2 != h4) { - errln("broken hash code: h2=" + h2 + ", h4=" + h4); + fail("broken hash code: h2=" + h2 + ", h4=" + h4); } int x = cal.getFirstDayOfWeek() + 3; if (x > SATURDAY) { @@ -1988,9 +2032,9 @@ } cal.setFirstDayOfWeek(x); int h5 = cal.hashCode(); - logln("hash code: h4=" + h4 + ", h5=" + h5); + System.out.println("hash code: h4=" + h4 + ", h5=" + h5); if (h4 == h5) { - errln("has code is poor with first day of week param: hashCode=" + h4); + fail("has code is poor with first day of week param: hashCode=" + h4); } } @@ -1998,6 +2042,7 @@ * 4125161: RFE: GregorianCalendar needs more era names (BCE and CE) */ /* + @Test public void Test4125161() throws Exception { Class gc = GregorianCalendar.class; Field f; @@ -2005,86 +2050,89 @@ f = gc.getDeclaredField("BCE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("BCE: wrong modifiers: " + mod); + fail("BCE: wrong modifiers: " + mod); } f = gc.getDeclaredField("CE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("CE: wrong modifiers: " + mod); + fail("CE: wrong modifiers: " + mod); } if (GregorianCalendar.BCE != GregorianCalendar.BC || GregorianCalendar.CE != GregorianCalendar.AD) { - errln("Wrong BCE and/or CE values"); + fail("Wrong BCE and/or CE values"); } } */ /** * 4167995: GregorianCalendar.setGregorianChange() not to spec */ + @Test public void Test4167995() { Koyomi gc = new Koyomi(TimeZone.getTimeZone("GMT")); - logln("Hybrid: min date"); + System.out.println("Hybrid: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Hybrid: max date"); + System.out.println("Hybrid: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MIN_VALUE)); - logln("Gregorian: min date"); + System.out.println("Gregorian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292275056, MAY, 16, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Gregorian: max date"); + System.out.println("Gregorian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MAX_VALUE)); - logln("Julian: min date"); + System.out.println("Julian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Julian: max date"); + System.out.println("Julian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292272993, JANUARY, 4, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } } /** * 4340146: Calendar.equals modifies state */ + @Test public void Test4340146() { Koyomi cal = new Koyomi(); cal.clear(); cal.set(2003, OCTOBER, 32); cal.equals(new Koyomi()); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } new Koyomi().equals(cal); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4639407: GregorianCalendar doesn't work in non-lenient due to timezone bounds checking */ + @Test public void Test4639407() { // The following operations in non-lenient mode shouldn't // throw IllegalArgumentException. @@ -2100,6 +2148,7 @@ /** * 4652815: rolling week-of-year back hundreds of weeks changes year */ + @Test public void Test4652815() { Koyomi cal = new Koyomi(Locale.US); testRoll(cal, 2003, SEPTEMBER, 29); @@ -2112,18 +2161,18 @@ cal.clear(); cal.set(year, month, dayOfMonth); cal.getTime(); // normalize fields - logln("Roll backwards from " + cal.toDateString()); + System.out.println("Roll backwards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, -i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } - logln("Roll forewards from " + cal.toDateString()); + System.out.println("Roll forewards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, +i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } @@ -2131,47 +2180,50 @@ /** * 4652830: GregorianCalendar roll behaves unexpectedly for dates in BC era */ + @Test public void Test4652830() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); - logln("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); + System.out.println("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); cal.set(ERA, GregorianCalendar.BC); cal.set(9, FEBRUARY, 28); if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln(" wrong actual max of DAY_OF_YEAR: got " + fail(" wrong actual max of DAY_OF_YEAR: got " + cal.getActualMaximum(DAY_OF_YEAR) + " expected " + 366); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4740554: GregorianCalendar.getActualMaximum is inconsistent with normalization */ + @Test public void Test4740554() { - logln("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); + System.out.println("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); Koyomi cal = new Koyomi(Locale.US); cal.clear(); cal.set(1999, FEBRUARY + 12, 1); if (!cal.checkActualMaximum(DAY_OF_YEAR, 366)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4936355: GregorianCalendar causes overflow/underflow with time of day calculation */ + @Test public void Test4936355() { Koyomi cal = new Koyomi(TimeZone.getTimeZone("GMT")); cal.clear(); @@ -2213,7 +2265,7 @@ long time2 = cal.getTimeInMillis(); if ((time + expectedDelta) != time2) { String s = value == Integer.MAX_VALUE ? "Integer.MAX_VALUE" : "Integer.MIN_VALUE"; - errln("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + fail("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + ", expected " + (time + expectedDelta)); } } @@ -2222,6 +2274,7 @@ * 4722650: Calendar.equals can throw an exception in non-lenient * (piggy-back tests for compareTo() which is new in 1.5) */ + @Test public void Test4722650() { Calendar cal1 = new GregorianCalendar(); cal1.clear(); @@ -2233,26 +2286,26 @@ cal2.set(2003, OCTOBER, 31); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/31)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/31)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/31)"); + fail("cal1 and cal2 should represent the same time. (2003/10/31)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1.set(2003, OCTOBER, 32); cal2.set(2003, OCTOBER, 32); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/32)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/32)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/32)"); + fail("cal1 and cal2 should represent the same time. (2003/10/32)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1 = Calendar.getInstance(new Locale("th", "TH")); @@ -2260,48 +2313,49 @@ cal2 = Calendar.getInstance(Locale.US); cal2.setTimeInMillis(0L); if (cal1.equals(cal2)) { - errln("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); + fail("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); + fail("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); } } /** * 4738710: API: Calendar comparison methods should be improved */ + @Test public void Test4738710() { Calendar cal0 = new GregorianCalendar(2003, SEPTEMBER, 30); Comparable cal1 = new GregorianCalendar(2003, OCTOBER, 1); Calendar cal2 = new GregorianCalendar(2003, OCTOBER, 2); if (!(cal1.compareTo(cal0) > 0)) { - errln("!(cal1 > cal0)"); + fail("!(cal1 > cal0)"); } if (!(cal1.compareTo(cal2) < 0)) { - errln("!(cal1 < cal2)"); + fail("!(cal1 < cal2)"); } if (cal1.compareTo(new GregorianCalendar(2003, OCTOBER, 1)) != 0) { - errln("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); + fail("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); } if (cal0.after(cal2)) { - errln("cal0 shouldn't be after cal2"); + fail("cal0 shouldn't be after cal2"); } if (cal2.before(cal0)) { - errln("cal2 shouldn't be before cal0"); + fail("cal2 shouldn't be before cal0"); } if (cal0.after(0)) { - errln("cal0.after() returned true with an Integer."); + fail("cal0.after() returned true with an Integer."); } if (cal0.before(0)) { - errln("cal0.before() returned true with an Integer."); + fail("cal0.before() returned true with an Integer."); } if (cal0.after(null)) { - errln("cal0.after() returned true with null."); + fail("cal0.after() returned true with null."); } if (cal0.before(null)) { - errln("cal0.before() returned true with null."); + fail("cal0.before() returned true with null."); } } @@ -2309,6 +2363,7 @@ * 4633646: Setting WEEK_OF_MONTH to 1 results in incorrect date */ @SuppressWarnings("deprecation") + @Test public void Test4633646() { Koyomi cal = new Koyomi(Locale.US); cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); @@ -2334,15 +2389,15 @@ cal.set(WEEK_OF_MONTH, 1); if (cal.isLenient()) { if (!cal.checkDate(2001, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 6)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } else { try { Date d = cal.getTime(); - errln("didn't throw IllegalArgumentException in non-lenient"); + fail("didn't throw IllegalArgumentException in non-lenient"); } catch (IllegalArgumentException e) { } } @@ -2352,6 +2407,7 @@ * 4846659: Calendar: Both set() and roll() don't work for AM_PM time field * (Partially fixed only roll as of 1.5) */ + @Test public void Test4846659() { Koyomi cal = new Koyomi(); cal.clear(); @@ -2360,7 +2416,7 @@ // Test roll() cal.roll(AM_PM, +1); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("roll: AM_PM didn't change to PM"); + fail("roll: AM_PM didn't change to PM"); } cal.clear(); @@ -2369,7 +2425,7 @@ // Test set() cal.set(AM_PM, PM); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("set: AM_PM didn't change to PM"); + fail("set: AM_PM didn't change to PM"); } cal.clear(); @@ -2378,13 +2434,14 @@ cal.set(AM_PM, PM); cal.set(HOUR, 9); if (!cal.checkFieldValue(HOUR_OF_DAY, 9 + 12)) { - errln("set: both AM_PM and HOUT didn't change to PM"); + fail("set: both AM_PM and HOUT didn't change to PM"); } } /** * 4822110: GregorianCalendar.get() returns an incorrect date after setFirstDayOfWeek() */ + @Test public void Test4822110() { Koyomi cal = new Koyomi(Locale.US); // June 2003 @@ -2401,17 +2458,18 @@ cal.setFirstDayOfWeek(MONDAY); // Now 6/2 to 6/8 should be the 2nd week of June. Sunday of // that week is 6/8. - logln("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); + System.out.println("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); cal.set(DAY_OF_WEEK, SUNDAY); - logln("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); + System.out.println("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); if (!cal.checkDate(2003, JUNE, 8)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4973919: Inconsistent GregorianCalendar hashCode before and after serialization */ + @Test public void Test4966499() throws Exception { GregorianCalendar date1 = new GregorianCalendar(2004, JANUARY, 7); @@ -2428,10 +2486,10 @@ GregorianCalendar date2 = (GregorianCalendar) ois.readObject(); if (!date1.equals(date2)) { - errln("date1.equals(date2) != true"); + fail("date1.equals(date2) != true"); } if (date1.hashCode() != date2.hashCode()) { - errln("inconsistent hashCode() value (before=0x" + fail("inconsistent hashCode() value (before=0x" + Integer.toHexString(date1.hashCode()) + ", after=0x" + Integer.toHexString(date2.hashCode()) + ")"); } @@ -2440,54 +2498,56 @@ /** * 4980088: GregorianCalendar.getActualMaximum doesn't throw exception */ + @Test public void Test4980088() { GregorianCalendar cal = new GregorianCalendar(); try { int x = cal.getMaximum(100); - errln("getMaximum(100) didn't throw an exception."); + fail("getMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getLeastMaximum(100); - errln("getLeastMaximum(100) didn't throw an exception."); + fail("getLeastMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMaximum(100); - errln("getActualMaximum(100) didn't throw an exception."); + fail("getActualMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getMinimum(100); - errln("getMinimum(100) didn't throw an exception."); + fail("getMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getGreatestMinimum(100); - errln("getGreatestMinimum(100) didn't throw an exception."); + fail("getGreatestMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMinimum(100); - errln("getActualMinimum(100) didn't throw an exception."); + fail("getActualMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } } /** * 4965624: GregorianCalendar.isLeapYear(1000) returns incorrect value */ + @Test public void Test4965624() { // 5013094: This test case needs to use "GMT" to specify // Gregorian cutover dates. @@ -2509,7 +2569,7 @@ GregorianCalendar cal = new GregorianCalendar(); cal.setGregorianChange(d); if (cal.isLeapYear(1000) != expected) { - errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + fail("isLeapYear(1000) returned " + cal.isLeapYear(1000) + " with cutover date (Julian) " + d); } }); @@ -2532,16 +2592,17 @@ /** * 5006864: Define the minimum value of DAY_OF_WEEK_IN_MONTH as 1 */ + @Test public void Test5006864() { GregorianCalendar cal = new GregorianCalendar(); int min = cal.getMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } min = cal.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/CalendarTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/CalendarTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ * @summary test for Calendar * @library /java/text/testlib * @modules java.base/java.util:+open - * @run main CalendarTest + * @run junit CalendarTest * @key randomness */ @@ -48,18 +48,19 @@ import static java.util.Calendar.*; -public class CalendarTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class CalendarTest { static final int ONE_DAY = 24 * 60 * 60 * 1000; static final int EPOCH_JULIAN = 2440588; - public static void main(String argv[]) throws Exception { - new CalendarTest().run(argv); - } - /** * Test the behavior of the GregorianCalendar around the changeover. */ + @Test public void TestGregorianChangeover() { TimeZone savedZone = TimeZone.getDefault(); /* @@ -97,10 +98,10 @@ int dom = cal.get(DATE); int dow = cal.get(DAY_OF_WEEK); - logln("Changeover " + (i >= 0 ? "+" : "") + i + System.out.println("Changeover " + (i >= 0 ? "+" : "") + i + " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); if (y != 1582 || mon != MON[j] || dom != DOM[j] || dow != DOW[j]) { - errln(" Fail: Above line is wrong"); + fail(" Fail: Above line is wrong"); } } } finally { @@ -114,6 +115,7 @@ * (first day of week, minimal days in first week). */ @SuppressWarnings("deprecation") + @Test public void TestMapping() { TimeZone saveZone = TimeZone.getDefault(); int[] DATA = { @@ -160,9 +162,9 @@ + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } // Test Julian computation @@ -184,9 +186,9 @@ + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } } @@ -212,16 +214,17 @@ int month2 = cal.get(MONTH); int dom2 = cal.get(DAY_OF_MONTH); if (y != year2 || m != month2 || dom2 != d) { - errln("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + fail("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + year2 + "-" + (month2 + 1) + "-" + dom2); } } @SuppressWarnings("deprecation") + @Test public void TestGenericAPI() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -235,7 +238,7 @@ Calendar cal = Calendar.getInstance((SimpleTimeZone) zone.clone()); if (!zone.equals(cal.getTimeZone())) { - errln("FAIL: Calendar.getTimeZone failed"); + fail("FAIL: Calendar.getTimeZone failed"); } Calendar cal2 = Calendar.getInstance(cal.getTimeZone()); @@ -244,27 +247,27 @@ cal2.setTime(when); if (!(cal.equals(cal2))) { - errln("FAIL: Calendar.operator== failed"); + fail("FAIL: Calendar.operator== failed"); } // if ((*cal != *cal2)) errln("FAIL: Calendar.operator!= failed"); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal2.setTime(new Date(when.getTime() + 1000)); if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal.roll(SECOND, true); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // Roll back to January @@ -272,20 +275,20 @@ if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // C++ only /* TimeZone z = cal.orphanTimeZone(); if (z.getID(str) != tzid || z.getRawOffset() != tzoffset) - errln("FAIL: orphanTimeZone failed"); + fail("FAIL: orphanTimeZone failed"); */ for (int i = 0; i < 2; ++i) { boolean lenient = (i > 0); cal.setLenient(lenient); if (lenient != cal.isLenient()) { - errln("FAIL: setLenient/isLenient failed"); + fail("FAIL: setLenient/isLenient failed"); } // Later: Check for lenient behavior } @@ -294,26 +297,26 @@ for (i = SUNDAY; i <= SATURDAY; ++i) { cal.setFirstDayOfWeek(i); if (cal.getFirstDayOfWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i <= 7; ++i) { cal.setMinimalDaysInFirstWeek(i); if (cal.getMinimalDaysInFirstWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i < FIELD_COUNT; ++i) { if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) { - errln("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); + fail("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); } if (cal.getLeastMaximum(i) > cal.getMaximum(i)) { - errln("FAIL: getLeastMaximum larger than getMaximum for field " + i); + fail("FAIL: getLeastMaximum larger than getMaximum for field " + i); } if (cal.getMinimum(i) >= cal.getMaximum(i)) { - errln("FAIL: getMinimum not less than getMaximum for field " + i); + fail("FAIL: getMinimum not less than getMaximum for field " + i); } } @@ -321,22 +324,22 @@ cal.clear(); cal.set(1984, 5, 24); if (cal.getTime().getTime() != new Date(84, 5, 24).getTime()) { - errln("FAIL: Calendar.set(3 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); + fail("FAIL: Calendar.set(3 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); } cal.clear(); cal.set(1985, 3, 2, 11, 49); if (cal.getTime().getTime() != new Date(85, 3, 2, 11, 49).getTime()) { - errln("FAIL: Calendar.set(5 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); + fail("FAIL: Calendar.set(5 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); } cal.clear(); cal.set(1995, 9, 12, 1, 39, 55); if (cal.getTime().getTime() != new Date(95, 9, 12, 1, 39, 55).getTime()) { - errln("FAIL: Calendar.set(6 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); + fail("FAIL: Calendar.set(6 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); } cal.getTime(); @@ -349,17 +352,17 @@ case MINUTE: case SECOND: if (!cal.isSet(i)) { - errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); } break; default: if (cal.isSet(i)) { - errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); } } cal.clear(i); if (cal.isSet(i)) { - errln("FAIL: Calendar.clear/isSet failed"); + fail("FAIL: Calendar.clear/isSet failed"); } } @@ -368,7 +371,7 @@ Locale[] loc = Calendar.getAvailableLocales(); long count = loc.length; if (count < 1 || loc == null) { - errln("FAIL: getAvailableLocales failed"); + fail("FAIL: getAvailableLocales failed"); } else { for (i = 0; i < count; ++i) { cal = Calendar.getInstance(loc[i]); @@ -399,13 +402,13 @@ gc = new GregorianCalendar(1998, 10, 14, 21, 43); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhm) failed"); + fail("FAIL: new GregorianCalendar(ymdhm) failed"); } // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhms) failed"); + fail("FAIL: new GregorianCalendar(ymdhms) failed"); } // C++ only: @@ -417,6 +420,7 @@ } // Verify Roger Webster's bug + @Test public void TestRog() { GregorianCalendar gc = new GregorianCalendar(); @@ -432,12 +436,13 @@ if (gc.get(YEAR) != year || gc.get(MONTH) != month || gc.get(DATE) != (date + i)) { - errln("FAIL: Date " + gc.getTime() + " wrong"); + fail("FAIL: Date " + gc.getTime() + " wrong"); } } } // Verify DAY_OF_WEEK + @Test public void TestDOW943() { dowTest(false); dowTest(true); @@ -453,18 +458,19 @@ int min = cal.getMinimum(DAY_OF_WEEK); int max = cal.getMaximum(DAY_OF_WEEK); if (dow < min || dow > max) { - errln("FAIL: Day of week " + dow + " out of range"); + fail("FAIL: Day of week " + dow + " out of range"); } if (dow != SUNDAY) { - errln("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); + fail("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); } if (min != SUNDAY || max != SATURDAY) { - errln("FAIL: Min/max bad"); + fail("FAIL: Min/max bad"); } } // Verify that the clone method produces distinct objects with no // unintentionally shared fields. + @Test public void TestClonesUnique908() { Calendar c = Calendar.getInstance(); Calendar d = (Calendar) c.clone(); @@ -472,31 +478,33 @@ d.set(MILLISECOND, 456); if (c.get(MILLISECOND) != 123 || d.get(MILLISECOND) != 456) { - errln("FAIL: Clones share fields"); + fail("FAIL: Clones share fields"); } } // Verify effect of Gregorian cutoff value @SuppressWarnings("deprecation") + @Test public void TestGregorianChange768() { boolean b; GregorianCalendar c = new GregorianCalendar(); - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be FALSE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be FALSE)"); if (b != false) { - errln("FAIL"); + fail("FAIL"); } c.setGregorianChange(new Date(0, 0, 1)); // Jan 1 1900 - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be TRUE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be TRUE)"); if (b != true) { - errln("FAIL"); + fail("FAIL"); } } // Test the correct behavior of the disambiguation algorithm. + @Test public void TestDisambiguation765() throws Exception { Locale savedLocale = Locale.getDefault(); try { @@ -562,7 +570,7 @@ c.set(WEEK_OF_MONTH, 1); verify765("1997 Tuesday in week 0 of June = ", c, 1997, JUNE, 3); } catch (IllegalArgumentException ex) { - errln("FAIL: Exception seen: " + ex.getMessage()); + fail("FAIL: Exception seen: " + ex.getMessage()); // ex.printStackTrace(log); } @@ -596,9 +604,9 @@ if (c.get(YEAR) == year && c.get(MONTH) == month && c.get(DATE) == day) { - logln("PASS: " + msg + c.getTime()); + System.out.println("PASS: " + msg + c.getTime()); } else { - errln("FAIL: " + msg + c.getTime() + fail("FAIL: " + msg + c.getTime() + "; expected " + year + "/" + (month + 1) + "/" + day); } @@ -607,17 +615,18 @@ // Called when e expected to be non-null void verify765(String msg, IllegalArgumentException e) { if (e == null) { - errln("FAIL: No IllegalArgumentException for " + msg); + fail("FAIL: No IllegalArgumentException for " + msg); } else { - logln("PASS: " + msg + "IllegalArgument as expected"); + System.out.println("PASS: " + msg + "IllegalArgument as expected"); } } // Test the behavior of GMT vs. local time + @Test public void TestGMTvsLocal4064654() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -645,7 +654,7 @@ gmtcal.set(MILLISECOND, 0); date = gmtcal.getTime(); - logln("date = " + date); + System.out.println("date = " + date); Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); @@ -658,7 +667,7 @@ cal.get(DAY_OF_WEEK), cal.get(MILLISECOND)); - logln("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); + System.out.println("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); int utc = ((cal.get(HOUR_OF_DAY) * 60 + cal.get(MINUTE)) * 60 @@ -668,7 +677,7 @@ int expected = ((hr * 60 + mn) * 60 + sc) * 1000; if (utc != expected) { - errln("FAIL: Discrepancy of " + fail("FAIL: Discrepancy of " + (utc - expected) + " millis = " + ((utc - expected) / 1000 / 60 / 60.0) + " hr"); } @@ -676,6 +685,7 @@ // Verify that add and set work regardless of the order in which // they are called. + @Test public void TestAddSetOrder621() { @SuppressWarnings("deprecation") Date d = new Date(97, 4, 14, 13, 23, 45); @@ -699,13 +709,14 @@ String s2 = cal.getTime().toString(); if (s.equals(s2)) { - logln("Pass: " + s + " == " + s2); + System.out.println("Pass: " + s + " == " + s2); } else { - errln("FAIL: " + s + " != " + s2); + fail("FAIL: " + s + " != " + s2); } } // Verify that add works. + @Test public void TestAdd520() { int y = 1997, m = FEBRUARY, d = 1; GregorianCalendar temp = new GregorianCalendar(y, m, d); @@ -737,19 +748,20 @@ if (c.get(YEAR) != y || c.get(MONTH) != m || c.get(DATE) != d) { - errln("FAILURE: Expected YEAR/MONTH/DATE of " + fail("FAILURE: Expected YEAR/MONTH/DATE of " + y + "/" + (m + 1) + "/" + d + "; got " + c.get(YEAR) + "/" + (c.get(MONTH) + 1) + "/" + c.get(DATE)); } else { - logln("Confirmed: " + System.out.println("Confirmed: " + y + "/" + (m + 1) + "/" + d); } } // Verify that setting fields works. This test fails when an exception is thrown. + @Test public void TestFieldSet4781() { try { GregorianCalendar g = new GregorianCalendar(); @@ -763,16 +775,17 @@ // The following line will result in IllegalArgumentException because // it thinks the YEAR is set and it is NOT. if (g2.equals(g)) { - logln("Same"); + System.out.println("Same"); } else { - logln("Different"); + System.out.println("Different"); } } catch (IllegalArgumentException e) { - errln("Unexpected exception seen: " + e); + fail("Unexpected exception seen: " + e); } } // Test serialization of a Calendar object + @Test public void TestSerialize337() { Calendar cal = Calendar.getInstance(); @@ -800,15 +813,15 @@ File fl = new File(FILENAME); fl.delete(); } catch (IOException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } catch (ClassNotFoundException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } if (!ok) { - errln("Serialization of Calendar object failed."); + fail("Serialization of Calendar object failed."); } } static final String PREFIX = "abc"; @@ -816,6 +829,7 @@ static final String FILENAME = "tmp337.bin"; // Try to zero out the seconds field + @Test public void TestSecondsZero121() { Calendar cal = new GregorianCalendar(); // Initialize with current date/time @@ -825,11 +839,12 @@ Date d = cal.getTime(); String s = d.toString(); if (s.indexOf(":00 ") < 0) { - errln("Expected to see :00 in " + s); + fail("Expected to see :00 in " + s); } } // Try various sequences of add, set, and get method calls. + @Test public void TestAddSetGet0610() { // // Error case 1: @@ -840,13 +855,13 @@ { Calendar calendar = new GregorianCalendar(); calendar.set(1993, JANUARY, 4); - logln("1A) " + value(calendar)); + System.out.println("1A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("1B) " + v); - logln("--) 1993/0/5"); + System.out.println("1B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -858,13 +873,13 @@ // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("2A) " + value(calendar)); + System.out.println("2A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("2B) " + v); - logln("--) 1993/0/5"); + System.out.println("2B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -877,14 +892,14 @@ // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("3A) " + value(calendar)); + System.out.println("3A) " + value(calendar)); calendar.getTime(); calendar.add(DATE, 1); String v = value(calendar); - logln("3B) " + v); - logln("--) 1993/0/5"); + System.out.println("3B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -897,6 +912,7 @@ static String EXPECTED_0610 = "1993/0/5"; // Test that certain fields on a certain date are as expected. + @Test public void TestFields060() { int year = 1997; int month = OCTOBER; //october @@ -908,7 +924,7 @@ int field = EXPECTED_FIELDS[i++]; int expected = EXPECTED_FIELDS[i++]; if (calendar.get(field) != expected) { - errln("Expected field " + field + " to have value " + expected + fail("Expected field " + field + " to have value " + expected + "; received " + calendar.get(field) + " instead"); } } @@ -942,6 +958,7 @@ // Verify that the fields are as expected (mostly zero) at the epoch start. // Note that we adjust for the default timezone to get most things to zero. + @Test public void TestEpochStartFields() { String[][] lt = { {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ @@ -988,14 +1005,14 @@ boolean err = false; for (int i = 0; i < calendarFieldNames.length; ++i) { if ((val = c.get(i)) != EPOCH_FIELDS[i]) { - errln("Wrong value: " + val + fail("Wrong value: " + val + " for field(" + calendarFieldNames[i] + "), expected: " + EPOCH_FIELDS[i]); err = true; } } if (err) { - errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + fail("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + "\n\tLocale=" + l + "\n\tCalendar=" + c); } } @@ -1007,6 +1024,7 @@ // Verify that as you add days to the calendar (e.g., 24 day periods), // the day of the week shifts in the expected pattern. + @Test public void TestDOWProgression() { Calendar cal = new GregorianCalendar(1972, OCTOBER, 26); @@ -1020,66 +1038,68 @@ int DOW, newDOW = initialDOW; do { DOW = newDOW; - logln("DOW = " + DOW + " " + cur.getTime()); + System.out.println("DOW = " + DOW + " " + cur.getTime()); cur.add(DAY_OF_WEEK, delta); newDOW = cur.get(DAY_OF_WEEK); int expectedDOW = 1 + (DOW + delta - 1) % 7; if (newDOW != expectedDOW) { - errln("Day of week should be " + expectedDOW + fail("Day of week should be " + expectedDOW + " instead of " + newDOW + " on " + cur.getTime()); return; } } while (newDOW != initialDOW); } + @Test public void TestActualMinMax() { Calendar cal = new GregorianCalendar(1967, MARCH, 10); cal.setFirstDayOfWeek(SUNDAY); cal.setMinimalDaysInFirstWeek(3); if (cal.getActualMinimum(DAY_OF_MONTH) != 1) { - errln("Actual minimum date for 3/10/1967 should have been 1; got " + fail("Actual minimum date for 3/10/1967 should have been 1; got " + cal.getActualMinimum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_MONTH) != 31) { - errln("Actual maximum date for 3/10/1967 should have been 31; got " + fail("Actual maximum date for 3/10/1967 should have been 31; got " + cal.getActualMaximum(DAY_OF_MONTH)); } cal.set(MONTH, FEBRUARY); if (cal.getActualMaximum(DAY_OF_MONTH) != 28) { - errln("Actual maximum date for 2/10/1967 should have been 28; got " + fail("Actual maximum date for 2/10/1967 should have been 28; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 365) { - errln("Number of days in 1967 should have been 365; got " + fail("Number of days in 1967 should have been 365; got " + cal.getActualMaximum(DAY_OF_YEAR)); } cal.set(YEAR, 1968); if (cal.getActualMaximum(DAY_OF_MONTH) != 29) { - errln("Actual maximum date for 2/10/1968 should have been 29; got " + fail("Actual maximum date for 2/10/1968 should have been 29; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln("Number of days in 1968 should have been 366; got " + fail("Number of days in 1968 should have been 366; got " + cal.getActualMaximum(DAY_OF_YEAR)); } // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 52) { - errln("Number of weeks in 1968 should have been 52; got " + fail("Number of weeks in 1968 should have been 52; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } cal.set(YEAR, 1976); // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 53) { - errln("Number of weeks in 1976 should have been 53; got " + fail("Number of weeks in 1976 should have been 53; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } } + @Test public void TestRoll() { Calendar cal = new GregorianCalendar(1997, JANUARY, 31); @@ -1089,7 +1109,7 @@ Calendar cal2 = (Calendar) cal.clone(); cal2.roll(MONTH, i); if (cal2.get(DAY_OF_MONTH) != dayValues[i]) { - errln("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + fail("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " + ((i + 1) % 12) + "/" + cal2.get(DAY_OF_MONTH) + "/1997."); } @@ -1105,7 +1125,7 @@ cal2.roll(YEAR, i); if (cal2.get(DAY_OF_MONTH) != dayValues2[i] || cal2.get(MONTH) != monthValues[i]) { - errln("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + fail("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" + (1996 + i) + ", but actually yielded " + (cal2.get(MONTH) + 1) + "/" @@ -1118,17 +1138,17 @@ cal.roll(HOUR_OF_DAY, -2); int f = cal.get(HOUR_OF_DAY); if (f != 22) { - errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); + fail("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); } cal.roll(HOUR_OF_DAY, 5); f = cal.get(HOUR_OF_DAY); if (f != 3) { - errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR_OF_DAY, 21); f = cal.get(HOUR_OF_DAY); if (f != 0) { - errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + fail("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); } // Test rolling hour @@ -1136,23 +1156,24 @@ cal.roll(HOUR, -2); f = cal.get(HOUR); if (f != 10) { - errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); + fail("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); } cal.roll(HOUR, 5); f = cal.get(HOUR); if (f != 3) { - errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR, 9); f = cal.get(HOUR); if (f != 0) { - errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + fail("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); } } /* * Confirm that multiple calls to Calendar.set() works correctly. */ + @Test public void Test4374886() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -1171,7 +1192,7 @@ || cal.get(MONTH) != JANUARY || cal.get(DATE) != 22 || cal.get(DAY_OF_WEEK) != MONDAY) { - errln("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); + fail("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); } } finally { Locale.setDefault(savedLocale); @@ -1179,6 +1200,7 @@ } } + @Test public void TestClonedSharedZones() throws NoSuchFieldException, IllegalAccessException { Field zone = Calendar.class.getDeclaredField("zone"); zone.setAccessible(true); @@ -1191,13 +1213,13 @@ // c1 should have a shared zone if (!sharedZone.getBoolean(c1)) { - errln("Failed : c1.sharedZone == false"); + fail("Failed : c1.sharedZone == false"); } else { // c2 should have a shared zone too if (!sharedZone.getBoolean(c2)) { - errln("Failed : c2.sharedZone == false"); + fail("Failed : c2.sharedZone == false"); } else if (zone.get(c1) != zone.get(c2)) { - errln("Failed : c1.zone != c2.zone"); + fail("Failed : c1.zone != c2.zone"); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/FieldStateTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/FieldStateTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/FieldStateTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/FieldStateTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4860664 4916815 4867075 - * @library /java/text/testlib - * @build Koyomi - * @run main FieldStateTest + * @run junit/othervm FieldStateTest * @summary Unit tests for internal fields states. */ @@ -36,31 +34,30 @@ import static java.util.Calendar.*; -public class FieldStateTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); - - new FieldStateTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class FieldStateTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + + @Test public void TestFieldState() { Koyomi cal = new Koyomi(); - logln("Right after instantialtion:"); + System.out.println("Right after instantialtion:"); if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set date to 2003/10/31 after the instantiation:"); + System.out.println("Set date to 2003/10/31 after the instantiation:"); cal.set(2003, OCTOBER, 31); // let cal calculate the time cal.getTime(); @@ -70,18 +67,18 @@ // the fields have "computed". But we can't distinguish them // outside the package. if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Make sure that the correct date was produced. if (!cal.checkInternalDate(2003, OCTOBER, 31, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Change to Monday of the week, which is 2003/10/27:"); + System.out.println("Change to Monday of the week, which is 2003/10/27:"); cal.set(DAY_OF_WEEK, MONDAY); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 27)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // The same operation didn't work after calling clear() before @@ -89,28 +86,28 @@ // operations. After the instantiation, all the fields are set // to "computed". But after calling clear(), the state becomes // "unset". - logln("Set to 2003/10/31 after clear():"); + System.out.println("Set to 2003/10/31 after clear():"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(DAY_OF_WEEK, MONDAY); if (!cal.checkDate(2003, OCTOBER, 27, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); + System.out.println("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(WEEK_OF_YEAR, 51); if (!cal.checkFieldValue(WEEK_OF_YEAR, 51)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkDate(2003, DECEMBER, 19, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(MONTH, OCTOBER); @@ -118,32 +115,32 @@ cal.set(WEEK_OF_MONTH, 4); cal.getTime(); if (!cal.checkFieldValue(DAY_OF_MONTH, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 43)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(DAY_OF_WEEK, MONDAY); cal.set(WEEK_OF_YEAR, 43); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 20, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 4)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set day of week to SUNDAY and date to 2003/10/31. " + System.out.println("Set day of week to SUNDAY and date to 2003/10/31. " + "Then, getTime and set week of year to 43."); @SuppressWarnings("deprecation") @@ -161,15 +158,16 @@ cal.getTime(); cal.set(WEEK_OF_YEAR, 43); if (!cal.checkDate(2003, OCTOBER, 24, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /* * 4916815: REGRESSION: Problem with java.util.Calendar VM 1.4.2-b28 */ + @Test public void Test4916815() { - logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + System.out.println("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + "Set dayofweek to Sunday which should be 2003/9/21."); Koyomi cal = new Koyomi(); cal.clear(); @@ -183,13 +181,14 @@ // Sunday of the week should be 2003/9/21. cal2.set(DAY_OF_WEEK, SUNDAY); if (!cal2.checkDate(2003, SEPTEMBER, 21, SUNDAY)) { - errln(cal2.getMessage()); + fail(cal2.getMessage()); } } /* * 4867075: GregorianCalendar get() calls complete() internally, should getTime() too? */ + @Test public void Test4867075() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); @@ -209,7 +208,7 @@ cal.set(DAY_OF_WEEK, dayOfWeek); cal.getTime(); if (!cal.checkInternalDate(expectedYear, expectedMonth, expectedDayOfMonth, dayOfWeek)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/GregorianCutoverTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/GregorianCutoverTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/GregorianCutoverTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/GregorianCutoverTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4359204 4928615 4743587 4956232 6459836 6549953 - * @library /java/text/testlib - * @build Koyomi - * @run main GregorianCutoverTest + * @run junit/othervm GregorianCutoverTest * @summary Unit tests related to the Gregorian cutover support. */ @@ -36,25 +34,25 @@ import static java.util.GregorianCalendar.*; -public class GregorianCutoverTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - TimeZone tz = TimeZone.getDefault(); - Locale lc = Locale.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); +import static org.junit.jupiter.api.Assertions.fail; - new GregorianCutoverTest().run(args); - } finally { - TimeZone.setDefault(tz); - Locale.setDefault(lc); - } +public class GregorianCutoverTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + /** * 4359204: GregorianCalendar.get(cal.DAY_OF_YEAR) is inconsistent for year 1582 */ + @Test public void Test4359204() { Koyomi cal = new Koyomi(); @@ -100,79 +98,79 @@ checkContinuity(cal, DAY_OF_YEAR); checkContinuity(cal, WEEK_OF_YEAR); - logln("Default cutover"); + System.out.println("Default cutover"); cal = new Koyomi(); cal.set(1582, OCTOBER, 1); - logln(" roll --DAY_OF_MONTH from 1582/10/01"); + System.out.println(" roll --DAY_OF_MONTH from 1582/10/01"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH+10 from 1582/10/31"); + System.out.println(" roll DAY_OF_MONTH+10 from 1582/10/31"); cal.roll(DAY_OF_MONTH, +10); if (!cal.checkDate(1582, OCTOBER, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH-10 from 1582/10/20"); + System.out.println(" roll DAY_OF_MONTH-10 from 1582/10/20"); cal.roll(DAY_OF_MONTH, -10); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day further"); + System.out.println(" roll back one day further"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1582, OCTOBER, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // should handle the gap between 1969/12/22 (Julian) to 1970/1/5 (Gregorian) - logln("Cutover date is 1970/1/5"); + System.out.println("Cutover date is 1970/1/5"); @SuppressWarnings("deprecation") Date d1 = new Date(1970 - 1900, JANUARY, 5); cal.setGregorianChange(d1); cal.set(ERA, AD); cal.set(YEAR, 1970); - logln(" Set DAY_OF_YEAR to the 28th day of 1970"); + System.out.println(" Set DAY_OF_YEAR to the 28th day of 1970"); cal.set(DAY_OF_YEAR, 28); if (!cal.checkDate(1970, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1969/12/22 should be the 356th day of the year."); + System.out.println(" 1969/12/22 should be the 356th day of the year."); cal.set(1969, DECEMBER, 22); if (!cal.checkFieldValue(DAY_OF_YEAR, 356)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" Set DAY_OF_YEAR to autual maximum."); + System.out.println(" Set DAY_OF_YEAR to autual maximum."); int actualMaxDayOfYear = cal.getActualMaximum(DAY_OF_YEAR); if (actualMaxDayOfYear != 356) { - errln("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); + fail("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); } cal.set(DAY_OF_YEAR, actualMaxDayOfYear); if (!cal.checkDate(1969, DECEMBER, 22)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.set(1969, DECEMBER, 22); cal.roll(DAY_OF_YEAR, +1); - logln(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); + System.out.println(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); if (!cal.checkDate(1969, JANUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1970/1/5 should be the first day of the year."); + System.out.println(" 1970/1/5 should be the first day of the year."); cal.set(1970, JANUARY, 5); if (!cal.checkFieldValue(DAY_OF_YEAR, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll --DAY_OF_MONTH from 1970/1/5"); + System.out.println(" roll --DAY_OF_MONTH from 1970/1/5"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1970, JANUARY, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day of month"); + System.out.println(" roll back one day of month"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1970, JANUARY, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Test "missing" dates in non-lenient. @@ -180,22 +178,22 @@ cal.setLenient(false); try { // the next day of 1582/10/4 (Julian) is 1582/10/15 (Gregorian) - logln("1582/10/10 doesn't exit with the default cutover."); + System.out.println("1582/10/10 doesn't exit with the default cutover."); cal.set(1582, OCTOBER, 10); cal.getTime(); - errln(" Didn't throw IllegalArgumentException in non-lenient."); + fail(" Didn't throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } } private void checkContinuity(Koyomi cal, int field) { cal.getTime(); - logln(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); + System.out.println(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); int max = cal.getActualMaximum(field); for (int i = 1; i <= max; i++) { - logln(i + " " + cal.toDateString()); + System.out.println(i + " " + cal.toDateString()); if (!cal.checkFieldValue(field, i)) { - errln(" " + cal.toDateString() + ":\t" + cal.getMessage()); + fail(" " + cal.toDateString() + ":\t" + cal.getMessage()); } cal.add(field, +1); } @@ -204,92 +202,95 @@ /** * 4928615: GregorianCalendar returns wrong dates after setGregorianChange */ + @Test public void Test4928615() { Koyomi cal = new Koyomi(); - logln("Today is 2003/10/1 Gregorian."); + System.out.println("Today is 2003/10/1 Gregorian."); @SuppressWarnings("deprecation") Date x = new Date(2003 - 1900, 10 - 1, 1); cal.setTime(x); - logln(" Changing the cutover date to yesterday..."); + System.out.println(" Changing the cutover date to yesterday..."); cal.setGregorianChange(new Date(x.getTime() - (24 * 3600 * 1000))); if (!cal.checkDate(2003, OCTOBER, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" Changing the cutover date to tomorrow..."); + System.out.println(" Changing the cutover date to tomorrow..."); cal.setGregorianChange(new Date(x.getTime() + (24 * 3600 * 1000))); if (!cal.checkDate(2003, SEPTEMBER, 18)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 4743587: GregorianCalendar.getLeastMaximum() returns wrong values */ + @Test public void Test4743587() { Koyomi cal = new Koyomi(); Koyomi cal2 = (Koyomi) cal.clone(); - logln("getLeastMaximum should handle cutover year.\n" + System.out.println("getLeastMaximum should handle cutover year.\n" + " default cutover date"); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365 - 10)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52 - ((10 + 6) / 7))) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // Corrected for 4956232 if (!cal.checkLeastMaximum(DAY_OF_MONTH, 28)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_WEEK_IN_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // make sure that getLeastMaximum calls didn't affect the date if (!cal.equals(cal2)) { - errln(" getLeastMaximum calls modified the object."); + fail(" getLeastMaximum calls modified the object."); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" changing the date to 1582/10/20 for actual min/max tests"); + System.out.println(" changing the date to 1582/10/20 for actual min/max tests"); cal.set(1582, OCTOBER, 20); if (!cal.checkActualMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal = new Koyomi(); - logln("Change the cutover date to 1970/1/5."); + System.out.println("Change the cutover date to 1970/1/5."); @SuppressWarnings("deprecation") Date d = new Date(1970 - 1900, 0, 5); cal.setGregorianChange(d); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 356)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_MONTH, 22)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal.set(1970, JANUARY, 10); if (!cal.checkActualMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 6459836: (cal) GregorianCalendar set method provides wrong result */ + @Test public void Test6459836() { int hour = 13865672; Koyomi gc1 = new Koyomi(); @@ -297,19 +298,20 @@ gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour); if (!gc1.checkDate(1582, OCTOBER, 4)) { - errln("test case 1: " + gc1.getMessage()); + fail("test case 1: " + gc1.getMessage()); } gc1.clear(); gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour + 24); if (!gc1.checkDate(1582, OCTOBER, 15)) { - errln("test case 2: " + gc1.getMessage()); + fail("test case 2: " + gc1.getMessage()); } } /** * 6549953 (cal) WEEK_OF_YEAR and DAY_OF_YEAR calculation problems around Gregorian cutover */ + @Test public void Test6549953() { Koyomi cal = new Koyomi(); @@ -319,13 +321,13 @@ cal.checkFieldValue(WEEK_OF_YEAR, 42); cal.checkFieldValue(DAY_OF_WEEK, FRIDAY); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.clear(); cal.set(1582, OCTOBER, 1); cal.set(DAY_OF_YEAR, 292); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/JulianTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/JulianTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/JulianTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/JulianTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,20 +25,21 @@ * @test * @bug 5029449 * @summary Tests for the Julian calendar system (before the Gregorian cutover) - * @library /java/text/testlib + * @run junit JulianTest */ import static java.util.GregorianCalendar.*; -public class JulianTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new JulianTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class JulianTest { /* * 5029449: Regression: GregorianCalendar produces wrong Julian calendar dates in BC 1 */ + @Test public void Test5029449() { Koyomi cal = new Koyomi(); cal.clear(); @@ -46,7 +47,7 @@ // Date should be BC 1/12/31 if (!cal.checkFieldValue(ERA, BC) || !cal.checkDate(1, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/NonLenientTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/NonLenientTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/NonLenientTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/NonLenientTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ * @test * @bug 4147269 4266783 4726030 * @summary Make sure that validation is adequate in non-lenient mode. - * @library /java/text/testlib + * @run junit/othervm NonLenientTest */ import java.util.Date; @@ -35,22 +35,22 @@ import static java.util.Calendar.*; -public class NonLenientTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); - new NonLenientTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class NonLenientTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); } + + @Test public void TestValidationInNonLenient() { Koyomi cal = getNonLenient(); @@ -122,6 +122,7 @@ /** * 4266783: java.util.GregorianCalendar: incorrect validation in non-lenient */ + @Test public void Test4266783() { Koyomi cal = getNonLenient(); // 2003/1 has up to 5 weeks. @@ -135,6 +136,7 @@ /** * 4726030: GregorianCalendar doesn't check invalid dates in non-lenient */ + @Test public void Test4726030() { Koyomi cal = getNonLenient(); // Default year is 1970 in GregorianCalendar which isn't a leap year. @@ -146,6 +148,7 @@ /** * 4147269: java.util.GregorianCalendar.computeTime() works wrong when lenient is false */ + @Test public void Test4147269() { Koyomi calendar = getNonLenient(); Date date = (new GregorianCalendar(1996, 0, 3)).getTime(); @@ -157,7 +160,7 @@ calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (max = " + max + ")"); @@ -172,7 +175,7 @@ calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (min = " + min + ")"); @@ -187,7 +190,7 @@ try { cal.complete(); - errln(desc + " should throw IllegalArgumentException in non-lenient."); + fail(desc + " should throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } @@ -198,14 +201,14 @@ int[] afterFields = cal.getFields(); for (int i = 0; i < FIELD_COUNT; i++) { if (cal.isSet(i) && originalFields[i] != afterFields[i]) { - errln(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + fail(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + afterFields[i] + ", expected " + originalFields[i]); } } // In non-lenient, set state of fields shouldn't be modified. int afterSetFields = cal.getSetStateFields(); if (setFields != afterSetFields) { - errln(" complate() modified set states: before 0x" + toHex(setFields) + fail(" complate() modified set states: before 0x" + toHex(setFields) + ", after 0x" + toHex(afterSetFields)); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,10 +34,15 @@ import java.util.List; import java.util.Locale; import java.util.TimeZone; -import static java.util.Calendar.*; +import java.util.stream.Stream; + +import static java.util.Calendar.DAY_OF_YEAR; +import static java.util.Calendar.ERA; +import static java.util.Calendar.FEBRUARY; +import static java.util.Calendar.LONG; +import static java.util.Calendar.YEAR; import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import org.testng.annotations.DataProvider; @@ -91,19 +96,18 @@ } private static void testRun(String property, List javaParam) - throws Throwable{ - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASS_PATH) - .addToolArg("-Djdk.calendar.japanese.supplemental.era=" + property) - .addToolArg("SupplementalJapaneseEraTest"); - for (String para: javaParam) { - launcher.addToolArg(para); - } - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + throws Throwable { + List params = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASS_PATH, + "-Djdk.calendar.japanese.supplemental.era=" + property, + "SupplementalJapaneseEraTest"); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(params.stream(), javaParam.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); + System.out.println(property + ":pass"); if (exitCode != 0) { System.out.println(property + ":fail"); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4028518.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4028518.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4028518.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4028518.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,33 +24,30 @@ /* * @test * @bug 4028518 - * @summary Make sure cloned GregorianCalendar is unchanged by modifying its original. + * @summary Ensure cloned GregorianCalendar is unchanged when modifying its original. + * @run junit bug4028518 */ -import java.util.GregorianCalendar ; -import static java.util.Calendar.*; +import java.util.GregorianCalendar; + +import static java.util.Calendar.DAY_OF_MONTH; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotEquals; public class bug4028518 { - public static void main(String[] args) - { + /* + * Ensure modifying the original GregorianCalendar does not + * modify the cloned one as well + */ + @Test + public void clonedShouldNotChangeOriginalTest() { GregorianCalendar cal1 = new GregorianCalendar() ; GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ; - - printdate(cal1, "cal1: ") ; - printdate(cal2, "cal2 - cloned(): ") ; cal1.add(DAY_OF_MONTH, 1) ; - printdate(cal1, "cal1 after adding 1 day: ") ; - printdate(cal2, "cal2 should be unmodified: ") ; - if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) { - throw new RuntimeException("cloned GregorianCalendar modified"); - } - } - - private static void printdate(GregorianCalendar cal, String string) - { - System.out.println(string + (cal.get(MONTH) + 1) - + "/" + cal.get(DAY_OF_MONTH) - + "/" + cal.get(YEAR)) ; + assertNotEquals(cal1.get(DAY_OF_MONTH), cal2.get(DAY_OF_MONTH), + "Cloned calendar should not have same value as original"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4100311.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4100311.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4100311.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4100311.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,24 +24,29 @@ /* * @test * @bug 4100311 - * @summary Make sure set(DAY_OF_YEAR, 1) works. + * @summary Ensure set(DAY_OF_YEAR, 1) works. + * @run junit bug4100311 */ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Date; -public class bug4100311 -{ +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4100311 { + + // GregorianCalendar should be able to date to january 1st properly @SuppressWarnings("deprecation") - public static void main(String args[]) - { + @Test + public void dayOfYearIsOneTest() { GregorianCalendar cal = new GregorianCalendar(); cal.set(Calendar.YEAR, 1997); cal.set(Calendar.DAY_OF_YEAR, 1); - Date d = cal.getTime(); // Should be Jan 1 - if (d.getMonth() != 0 || d.getDate() != 1) { - throw new RuntimeException("Date isn't Jan 1"); - } + Date d = cal.getTime(); + assertEquals(0, d.getMonth(), "Date: "+d+" isn't January 1st"); + assertEquals(1, d.getDate(),"Date: "+d+" isn't January 1st"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4243802.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4243802.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4243802.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4243802.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,69 +25,86 @@ * @test * @bug 4243802 * @summary confirm that Calendar.setTimeInMillis() and - * getTimeInMillis() can be called from a user program. (They used to - * be protected methods.) - * @library /java/text/testlib + * getTimeInMillis() can be called from a user program. (They used to + * be protected methods.) + * @run junit bug4243802 */ -import java.util.*; - -public class bug4243802 extends IntlTest { +import java.util.Calendar; +import java.util.Locale; +import java.util.TimeZone; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4243802 { + + // Save JVM default Locale and TimeZone + private static final TimeZone savedTz = TimeZone.getDefault(); + private static final Locale savedLocale = Locale.getDefault(); + + // Set custom JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); + } - public static void main(String[] args) throws Exception { - new bug4243802().run(args); + // Restore JVM default Locale and TimeZone + @AfterAll + static void tearDownAll() { + Locale.setDefault(savedLocale); + TimeZone.setDefault(savedTz); } - /** - * 4243802: RFE: need way to set the date of a calendar without a Date object + /* + * Test getTimeInMillis() and setTimeInMillis(). Compare a Calendar + * set with a traditional date to one set using setTimeInMillis(), + * where both Calendars should be of equal times. */ - public void Test4243802() { - TimeZone saveZone = TimeZone.getDefault(); - Locale saveLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); - - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); - - cal1.clear(); - cal2.clear(); - cal1.set(2001, Calendar.JANUARY, 25, 1, 23, 45); - cal2.setTimeInMillis(cal1.getTimeInMillis()); - if ((cal2.get(Calendar.YEAR) != 2001) || - (cal2.get(Calendar.MONTH) != Calendar.JANUARY) || - (cal2.get(Calendar.DAY_OF_MONTH) != 25) || - (cal2.get(Calendar.HOUR_OF_DAY) != 1) || - (cal2.get(Calendar.MINUTE) != 23) || - (cal2.get(Calendar.SECOND) != 45) || - (cal2.get(Calendar.MILLISECOND) != 0)) { - errln("Failed: expected 1/25/2001 1:23:45.000" + - ", got " + (cal2.get(Calendar.MONTH)+1) + "/" + - cal2.get(Calendar.DAY_OF_MONTH) +"/" + - cal2.get(Calendar.YEAR) + " " + - cal2.get(Calendar.HOUR_OF_DAY) + ":" + - cal2.get(Calendar.MINUTE) + ":" + - cal2.get(Calendar.SECOND) + "." + - toMillis(cal2.get(Calendar.MILLISECOND))); - } - logln("Passed."); - } - finally { - Locale.setDefault(saveLocale); - TimeZone.setDefault(saveZone); - } + @Test + public void setCalendarWithoutDateTest() { + Calendar cal1 = Calendar.getInstance(); + Calendar cal2 = Calendar.getInstance(); + cal1.clear(); + cal2.clear(); + cal1.set(2001, Calendar.JANUARY, 25, 1, 23, 45); + // Build the second calendar using the getTimeInMillis of the first + cal2.setTimeInMillis(cal1.getTimeInMillis()); + + assertEquals(2001, cal2.get(Calendar.YEAR), getErrMsg(cal1)); + assertEquals(Calendar.JANUARY, cal2.get(Calendar.MONTH), getErrMsg(cal1)); + assertEquals(25, cal2.get(Calendar.DAY_OF_MONTH), getErrMsg(cal1)); + assertEquals(1, cal2.get(Calendar.HOUR_OF_DAY), getErrMsg(cal1)); + assertEquals(23, cal2.get(Calendar.MINUTE), getErrMsg(cal1)); + assertEquals(45, cal2.get(Calendar.SECOND), getErrMsg(cal1)); + assertEquals(0, cal2.get(Calendar.MILLISECOND), getErrMsg(cal1)); + } + + // Utility to build a long error message + private static String getErrMsg(Calendar cal) { + return "Failed: expected 1/25/2001 1:23:45.000" + + ", got " + (cal.get(Calendar.MONTH)+1) + "/" + + cal.get(Calendar.DAY_OF_MONTH) +"/" + + cal.get(Calendar.YEAR) + " " + + cal.get(Calendar.HOUR_OF_DAY) + ":" + + cal.get(Calendar.MINUTE) + ":" + + cal.get(Calendar.SECOND) + "." + + toMillis(cal.get(Calendar.MILLISECOND)); } - private String toMillis(int m) { - StringBuffer sb = new StringBuffer(); + // Utility to convert value to format of expected milisecond value + private static String toMillis(int m) { + StringBuilder sb = new StringBuilder(); if (m < 100) { sb.append('0'); } if (m < 10) { sb.append('0'); } - sb.append(m); - return sb.toString(); + return sb.append(m).toString(); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4316678.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4316678.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4316678.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4316678.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,49 +21,64 @@ * questions. */ -import java.io.*; -import java.util.*; -import java.text.*; - -/** +/* * @test * @bug 4316678 - * @summary test that Calendar's Serializasion works correctly. - * @library /java/text/testlib + * @summary test that Calendar's Serialization works correctly. + * @run junit bug4316678 */ -public class bug4316678 extends IntlTest { - public static void main(String[] args) throws Exception { - new bug4316678().run(args); +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4316678 { + + private static final String serializedData = "bug4316678.ser"; + + // Save JVM default TimeZone + private static final TimeZone savedTz = TimeZone.getDefault(); + + // Set custom JVM default TimeZone + @BeforeAll + static void initAll() { + TimeZone.setDefault(TimeZone.getTimeZone("PST")); } - public void Test4316678() throws Exception { - GregorianCalendar gc1; - GregorianCalendar gc2; - TimeZone saveZone = TimeZone.getDefault(); + // Restore JVM default Locale and TimeZone + @AfterAll + static void tearDownAll() { + TimeZone.setDefault(savedTz); + } - try { - TimeZone.setDefault(TimeZone.getTimeZone("PST")); + // Test that a serialized GregorianCalendar has the expected values + @Test + public void serializationTest() throws IOException, ClassNotFoundException { + GregorianCalendar gc1 = new GregorianCalendar(2000, Calendar.OCTOBER, 10); + GregorianCalendar gc2; + try (ObjectOutputStream out + = new ObjectOutputStream(new FileOutputStream(serializedData))) { + out.writeObject(gc1); + } - gc1 = new GregorianCalendar(2000, Calendar.OCTOBER, 10); - try (ObjectOutputStream out - = new ObjectOutputStream(new FileOutputStream("bug4316678.ser"))) { - out.writeObject(gc1); - } - - try (ObjectInputStream in - = new ObjectInputStream(new FileInputStream("bug4316678.ser"))) { - gc2 = (GregorianCalendar)in.readObject(); - } - - gc1.set(Calendar.DATE, 16); - gc2.set(Calendar.DATE, 16); - if (!gc1.getTime().equals(gc2.getTime())) { - errln("Invalid Time :" + gc2.getTime() + - ", expected :" + gc1.getTime()); - } - } finally { - TimeZone.setDefault(saveZone); + try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serializedData))) { + gc2 = (GregorianCalendar)in.readObject(); } + + gc1.set(Calendar.DATE, 16); + gc2.set(Calendar.DATE, 16); + assertEquals(gc2.getTime(), gc1.getTime(), + "Times should be equal after serialization"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4372743.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4372743.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4372743.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4372743.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,21 +25,107 @@ * @test * @bug 4372743 * @summary test that checks transitions of ERA and YEAR which are caused by add(MONTH). - * @library /java/text/testlib + * @run junit bug4372743 */ import java.util.GregorianCalendar; import java.util.TimeZone; +import java.util.stream.Stream; -import static java.util.GregorianCalendar.*; +import static java.util.GregorianCalendar.AD; +import static java.util.GregorianCalendar.APRIL; +import static java.util.GregorianCalendar.AUGUST; +import static java.util.GregorianCalendar.BC; +import static java.util.GregorianCalendar.DECEMBER; +import static java.util.GregorianCalendar.ERA; +import static java.util.GregorianCalendar.FEBRUARY; +import static java.util.GregorianCalendar.JANUARY; +import static java.util.GregorianCalendar.JULY; +import static java.util.GregorianCalendar.JUNE; +import static java.util.GregorianCalendar.MARCH; +import static java.util.GregorianCalendar.MAY; +import static java.util.GregorianCalendar.MONTH; +import static java.util.GregorianCalendar.NOVEMBER; +import static java.util.GregorianCalendar.OCTOBER; +import static java.util.GregorianCalendar.SEPTEMBER; +import static java.util.GregorianCalendar.YEAR; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4372743 { + + // Save JVM default timezone + private static final TimeZone savedTz = TimeZone.getDefault(); + + // Set custom JVM default timezone + @BeforeAll + static void initAll() { + TimeZone.setDefault(TimeZone.getTimeZone("PST")); + } + + // Restore JVM default timezone + @AfterAll + static void tearDownAll() { + TimeZone.setDefault(savedTz); + } + + /* + * Set GregorianCalendar to (March 3, A.D. 2) and test adding + * to the month field. Ensure that the added field is as expected. + */ + @ParameterizedTest + @MethodSource("A_D_Values") + public void A_D_Test(GregorianCalendar gc, int monthValue) { + for (int i = 0; i < tableSize; i+=(-monthValue)) { + check(gc, i); + gc.add(MONTH, monthValue); + } + } -public class bug4372743 extends IntlTest { + // Given in format: (A.D.) GregorianCalendar, amount to add + private static Stream A_D_Values() { + return Stream.of( + Arguments.of(new GregorianCalendar(2, MARCH, 3), -1), + Arguments.of(new GregorianCalendar(2, MARCH, 3), -7)); + } - public static void main(String[] args) throws Exception { - new bug4372743().run(args); + /* + * Set GregorianCalendar to (March 10, 2 B.C.) and test adding + * to the month field. Ensure that the added field is as expected. + */ + @ParameterizedTest + @MethodSource("B_C_Values") + public void B_C_Test(GregorianCalendar gc, int monthValue) { + gc.add(YEAR, -3); + for (int i = tableSize - 1; i >= 0; i-=monthValue) { + check(gc, i); + gc.add(MONTH, monthValue); + } } - private int[][] data = { + // Given in format: (B.C.) GregorianCalendar, amount to add + private static Stream B_C_Values() { + return Stream.of( + Arguments.of(new GregorianCalendar(2, OCTOBER, 10), 1), + Arguments.of(new GregorianCalendar(2, OCTOBER, 10), 8)); + } + + // Check golden data array with actual value + private void check(GregorianCalendar gc, int index) { + assertEquals(data[index][ERA], gc.get(ERA), "Invalid era"); + assertEquals(data[index][YEAR], gc.get(YEAR), "Invalid year"); + assertEquals(data[index][MONTH], gc.get(MONTH), "Invalid month"); + } + + // Expected ERA, YEAR, and MONTH combinations + private final int[][] data = { {AD, 2, MARCH}, {AD, 2, FEBRUARY}, {AD, 2, JANUARY}, @@ -70,61 +156,5 @@ {BC, 2, DECEMBER}, {BC, 2, NOVEMBER}, {BC, 2, OCTOBER}}; - private int tablesize = data.length; - - private void check(GregorianCalendar gc, int index) { - if (gc.get(ERA) != data[index][ERA]) { - errln("Invalid era :" + gc.get(ERA) - + ", expected :" + data[index][ERA]); - } - if (gc.get(YEAR) != data[index][YEAR]) { - errln("Invalid year :" + gc.get(YEAR) - + ", expected :" + data[index][YEAR]); - } - if (gc.get(MONTH) != data[index][MONTH]) { - errln("Invalid month :" + gc.get(MONTH) - + ", expected :" + data[index][MONTH]); - } - } - - public void Test4372743() { - GregorianCalendar gc; - TimeZone saveZone = TimeZone.getDefault(); - - try { - TimeZone.setDefault(TimeZone.getTimeZone("PST")); - - /* Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i++) { - check(gc, i); - gc.add(MONTH, -1); - } - - /* Again, Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i += 7) { - check(gc, i); - gc.add(MONTH, -7); - } - - /* Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(YEAR, -3); - for (int i = tablesize - 1; i >= 0; i--) { - check(gc, i); - gc.add(MONTH, 1); - } - - /* Again, Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(YEAR, -3); - for (int i = tablesize - 1; i >= 0; i -= 8) { - check(gc, i); - gc.add(MONTH, 8); - } - } finally { - TimeZone.setDefault(saveZone); - } - } + private final int tableSize = data.length; } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4401223.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4401223.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4401223.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4401223.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,73 +24,59 @@ /* * @test * @bug 4401223 - * @summary Make sure that GregorianCalendar doesn't cause IllegalArgumentException at some special situations which are related to the Leap Year. - * @library /java/text/testlib + * @summary Make sure that GregorianCalendar doesn't cause + * IllegalArgumentException at some special situations which are + * related to the Leap Year. + * @run junit bug4401223 */ import java.util.Date; import java.util.GregorianCalendar; -import static java.util.GregorianCalendar.*; - -public class bug4401223 extends IntlTest { - - public void Test4401223a() { - int status = 0; - String s = null; - - try { - @SuppressWarnings("deprecation") - Date date = new Date(2000 - 1900, FEBRUARY, 29); - GregorianCalendar gc = new GregorianCalendar(); +import static java.util.GregorianCalendar.DATE; +import static java.util.GregorianCalendar.DAY_OF_YEAR; +import static java.util.GregorianCalendar.DECEMBER; +import static java.util.GregorianCalendar.FEBRUARY; +import static java.util.GregorianCalendar.MONTH; +import static java.util.GregorianCalendar.YEAR; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4401223 { + + // Ensure IAE not thrown for date: 12-29-00 + @SuppressWarnings("deprecation") + @Test + public void checkExceptionTest() { + Date date = new Date(2000 - 1900, FEBRUARY, 29); + GregorianCalendar gc = new GregorianCalendar(); + assertDoesNotThrow(() -> { gc.setTime(date); gc.setLenient(false); gc.set(YEAR, 2001); - s = "02/29/00 & set(YEAR,2001) = " + gc.getTime().toString(); - } catch (Exception ex) { - status++; - s = "Exception occurred for 2/29/00 & set(YEAR,2001): " + ex; - } - if (status > 0) { - errln(s); - } else { - logln(s); - } + }, "Exception occurred for 2/29/00 & set(YEAR,2001)"); } - public void Test4401223b() { - int status = 0; - String s = null; - - try { - @SuppressWarnings("deprecation") - Date date = new Date(2000 - 1900, DECEMBER, 31); - GregorianCalendar gc = new GregorianCalendar(); + // Ensure IAE not thrown for date: 12-31-00. Validate expected values. + @SuppressWarnings("deprecation") + @Test + public void checkExceptionAndValuesTest() { + Date date = new Date(2000 - 1900, DECEMBER, 31); + GregorianCalendar gc = new GregorianCalendar(); + assertDoesNotThrow(() -> { gc.setTime(date); gc.setLenient(false); gc.set(YEAR, 2001); + }, "Exception occurred for 12/31/00 & set(YEAR,2001)"); - if (gc.get(YEAR) != 2001 - || gc.get(MONTH) != DECEMBER - || gc.get(DATE) != 31 - || gc.get(DAY_OF_YEAR) != 365) { - status++; - s = "Wrong Date : 12/31/00 & set(YEAR,2001) ---> " + gc.getTime().toString(); - } else { - s = "12/31/00 & set(YEAR,2001) = " + gc.getTime().toString(); - } - } catch (Exception ex) { - status++; - s = "Exception occurred for 12/31/00 & set(YEAR,2001) : " + ex; - } - if (status > 0) { - errln(s); - } else { - logln(s); - } - } + String errMsg = "Wrong date, got: " + gc.getTime(); - public static void main(String[] args) throws Exception { - new bug4401223().run(args); + assertEquals(2001, gc.get(YEAR), errMsg); + assertEquals(DECEMBER, gc.get(MONTH), errMsg); + assertEquals(31, gc.get(DATE), errMsg); + assertEquals(365, gc.get(DAY_OF_YEAR), errMsg); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4409072.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4409072.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4409072.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4409072.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,26 @@ * @bug 4409072 * @summary tests for set(), add(), and roll() with various week parameters. * @library /java/text/testlib - * @run main bug4409072 + * @run junit bug4409072 */ import java.util.*; import static java.util.Calendar.*; -public class bug4409072 extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new bug4409072().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class bug4409072 { /* Confirm some public methods' behavior in Calendar. * (e.g. add(), roll(), set()) */ + @Test public void Test4409072() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -411,7 +412,7 @@ if (cal.get(WEEK_OF_YEAR) != 22) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -420,7 +421,7 @@ ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -446,7 +447,7 @@ if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_MONTH=1)" + + fail("Failed : set(WEEK_OF_MONTH=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -470,7 +471,7 @@ if (cal.get(WEEK_OF_YEAR) != 1) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -479,7 +480,7 @@ ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -490,7 +491,7 @@ } if (noerror) { - logln("Passed : set() test"); + System.out.println("Passed : set() test"); } } @@ -525,7 +526,7 @@ if ((year != 2006) || (month != 0) || (date != 25)) { noerror = false; - errln("Failed : add(WEEK_OF_YEAR+1)" + + fail("Failed : add(WEEK_OF_YEAR+1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 1/25/2006" + ", MinFirstDOW=" + minDow + @@ -542,7 +543,7 @@ date = cal.get(DATE); if ((oldWOY - newWOY) != 3) { - errln("Failed : add(WEEK_OF_YEAR-1)" + + fail("Failed : add(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -550,7 +551,7 @@ ", WEEK_OF_YEAR=" + newWOY + " should be " + (oldWOY-3)); } else if ((year != 2005) || (month != 10) || (date != 16)) { - errln("Failed : add(-1)" + + fail("Failed : add(-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -560,7 +561,7 @@ } if (noerror) { - logln("Passed : add() test"); + System.out.println("Passed : add() test"); } } @@ -622,7 +623,7 @@ if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_MONTH-1)" + + fail("Failed : roll(WEEK_OF_MONTH-1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -649,7 +650,7 @@ if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR+1)" + + fail("Failed : roll(WEEK_OF_YEAR+1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -670,7 +671,7 @@ if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR-1)" + + fail("Failed : roll(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -680,7 +681,7 @@ } if (noerror) { - logln("Passed : roll() test"); + System.out.println("Passed : roll() test"); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4514831.java openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4514831.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Calendar/bug4514831.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Calendar/bug4514831.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,77 +24,99 @@ /* * @test * @bug 4514831 - * @summary Confirm that GregorianCalendar.roll() works properly during transition from Daylight Saving Time to Standard Time. + * @summary Confirm that GregorianCalendar.roll() works properly during + * transition from Daylight Saving Time to Standard Time. + * @run junit bug4514831 */ import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; -import static java.util.GregorianCalendar.*; +import static java.util.GregorianCalendar.DAY_OF_MONTH; +import static java.util.GregorianCalendar.DAY_OF_WEEK; +import static java.util.GregorianCalendar.DAY_OF_WEEK_IN_MONTH; +import static java.util.GregorianCalendar.DAY_OF_YEAR; +import static java.util.GregorianCalendar.OCTOBER; +import static java.util.GregorianCalendar.THURSDAY; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; public class bug4514831 { + // Data of 7 rolls in the form of a string for the respective field + private static final String expectedDayOfYearData = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; + private static final String expectedDayOfWeekData = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; + private static final String expectedDayOfWeekInMonthData = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; + private static final TimeZone savedTz = TimeZone.getDefault(); + private static final Locale savedLocale = Locale.getDefault(); + + // Save JVM default Locale and TimeZone + @BeforeAll + void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); + } + + // Restore JVM default Locale and TimeZone + @AfterAll + void tearDownAll() { + Locale.setDefault(savedLocale); + TimeZone.setDefault(savedTz); + } - public static void main(String[] args) { - Locale savedLocale = Locale.getDefault(); - TimeZone savedTimeZone = TimeZone.getDefault(); - boolean err = false; - - String golden_data1 = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; - String golden_data2 = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; - String golden_data3 = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; - - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); - - String test_roll = ""; - GregorianCalendar c_roll = new GregorianCalendar(2001, OCTOBER, 27); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_YEAR, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data1)) { - err = true; - System.err.println("Wrong roll(DAY_OF_YEAR) transition: got " - + test_roll + "expected " + golden_data1); - } - - test_roll = ""; - c_roll = new GregorianCalendar(2001, OCTOBER, 27); - c_roll.setFirstDayOfWeek(THURSDAY); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_WEEK, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data2)) { - err = true; - System.err.println("Wrong roll(DAY_OF_WEEK) transition: got " - + test_roll + "expected " + golden_data2); - } - - test_roll = ""; - c_roll = new GregorianCalendar(2001, OCTOBER, 1); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_WEEK_IN_MONTH, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data3)) { - err = true; - System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got " - + test_roll + "expected " + golden_data3); - } - } finally { - Locale.setDefault(savedLocale); - TimeZone.setDefault(savedTimeZone); + /* + * Test some roll values during transition (DAY_OF_YEAR field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfYearTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 27); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_YEAR, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); } + assertEquals(expectedDayOfYearData, actualRollData.toString(), + "Wrong roll(DAY_OF_YEAR) transition"); + } + + /* + * Test some roll values during transition (DAY_OF_WEEK field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfWeekTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 27); + cal.setFirstDayOfWeek(THURSDAY); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_WEEK, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); + } + assertEquals(expectedDayOfWeekData, actualRollData.toString(), + "Wrong roll(DAY_OF_WEEK) transition"); + } - if (err) { - throw new RuntimeException("Wrong roll() transition"); + /* + * Test some roll values during transition (DAY_OF_WEEK_IN_MONTH field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfWeekInMonthTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 1); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_WEEK_IN_MONTH, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); } + assertEquals(expectedDayOfWeekInMonthData, actualRollData.toString(), + "Wrong roll(DAY_OF_WEEK_IN_MONTH) transition"); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Date/DateRegression.java openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateRegression.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Date/DateRegression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateRegression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,22 @@ /* * @test * @bug 4023247 4027685 4032037 4072029 4073003 4118010 4120606 4133833 4136916 6274757 6314387 - * @library /java/text/testlib + * @run junit DateRegression */ import java.util.*; -@SuppressWarnings("deprecation") -public class DateRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DateRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +@SuppressWarnings("deprecation") +public class DateRegression { /** * @bug 4023247 */ + @Test public void Test4023247() { Date d1 = new Date(0); Date d2 = new Date(0); @@ -58,46 +59,49 @@ d2.setSeconds(0); if (d1.hashCode() != d2.hashCode()) - errln("Fail: Date hashCode misbehaves"); + fail("Fail: Date hashCode misbehaves"); } /** * @bug 4027685 */ + @Test public void Test4027685() { // Should be 01/16/97 00:00:00 Date nite = new Date("16-JAN-97 12:00 AM"); // Should be 01/16/97 12:00:00 Date noon = new Date("16-JAN-97 12:00 PM"); - logln("Midnight = " + nite + ", Noon = " + noon); + System.out.println("Midnight = " + nite + ", Noon = " + noon); if (!nite.equals(new Date(97, Calendar.JANUARY, 16, 0, 0)) || !noon.equals(new Date(97, Calendar.JANUARY, 16, 12, 0))) - errln("Fail: Nite/Noon confused"); + fail("Fail: Nite/Noon confused"); } /** * @bug 4032037 */ + @Test public void Test4032037() { Date ref = new Date(97, 1, 10); Date d = new Date(Date.parse("2/10/97")); - logln("Date.parse(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date(Date.parse("10 feb 1997")); - logln("Date.parse(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("2/10/97"); - logln("Date(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("10 feb 1997"); - logln("Date(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); } /** * @bug 4072029 */ + @Test public void Test4072029() { TimeZone saveZone = TimeZone.getDefault(); @@ -110,7 +114,7 @@ if (!s.equals(s2) || Math.abs(now.getTime() - now2.getTime()) > 60000 /*one min*/) { - errln("Fail: Roundtrip toString/parse"); + fail("Fail: Roundtrip toString/parse"); } } finally { @@ -121,16 +125,17 @@ /** * @bug 4073003 */ + @Test public void Test4073003() { Date d = new Date(Date.parse("01/02/1984")); if (!d.equals(new Date(84, 0, 2))) - errln("Fail: Want 1/2/1984 Got " + d); + fail("Fail: Want 1/2/1984 Got " + d); d = new Date(Date.parse("02/03/2012")); if (!d.equals(new Date(112, 1, 3))) - errln("Fail: Want 2/3/2012 Got " + d); + fail("Fail: Want 2/3/2012 Got " + d); d = new Date(Date.parse("03/04/15")); if (!d.equals(new Date(115, 2, 4))) - errln("Fail: Want 3/4/2015 Got " + d); + fail("Fail: Want 3/4/2015 Got " + d); } /** @@ -140,26 +145,28 @@ * NOTE: This turned out to be a user error (passing in 2000 instead * of 2000-1900 to the Date constructor). */ + @Test public void Test4118010() { Date d=new java.util.Date(2000-1900, Calendar.FEBRUARY, 29); int m=d.getMonth(); int date=d.getDate(); if (m != Calendar.FEBRUARY || date != 29) - errln("Fail: Want Feb 29, got " + d); + fail("Fail: Want Feb 29, got " + d); } /** * @bug 4120606 * Date objects share state after cloning. */ + @Test public void Test4120606() { Date d = new Date(98, Calendar.JUNE, 24); d.setMonth(Calendar.MAY); Date e = (Date)d.clone(); d.setMonth(Calendar.FEBRUARY); if (e.getMonth() != Calendar.MAY) { - errln("Cloned Date objects share state"); + fail("Cloned Date objects share state"); } } @@ -168,11 +175,12 @@ * Date constructor crashes with parameters out of range, when it should * normalize. */ + @Test public void Test4133833() { Date date = new java.util.Date(12,15,19); Date exp = new Date(1913-1900, Calendar.APRIL, 19); if (!date.equals(exp)) - errln("Fail: Want " + exp + + fail("Fail: Want " + exp + "; got " + date); } @@ -181,15 +189,17 @@ * Date.toString() throws exception in 1.2b4-E * CANNOT REPRODUCE this bug */ + @Test public void Test4136916() { Date time = new Date(); - logln(time.toString()); + System.out.println(time.toString()); } /** * @bug 6274757 * Date getTime and toString interaction for some time values */ + @Test public void Test6274757() { TimeZone savedTz = TimeZone.getDefault(); try { @@ -199,11 +209,11 @@ Calendar jdkCal = Calendar.getInstance(jdkGMT); jdkCal.clear(); jdkCal.set(1582, Calendar.OCTOBER, 15); - logln("JDK time: " + jdkCal.getTime().getTime() ); - logln("JDK time (str): " + jdkCal.getTime() ); - logln("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); + System.out.println("JDK time: " + jdkCal.getTime().getTime() ); + System.out.println("JDK time (str): " + jdkCal.getTime() ); + System.out.println("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); Date co = jdkCal.getTime(); - logln("Change over (Oct 15 1582) = " + co + " (" + + System.out.println("Change over (Oct 15 1582) = " + co + " (" + co.getTime() + ")"); long a = jdkCal.getTime().getTime(); Date c = jdkCal.getTime(); @@ -211,9 +221,9 @@ long b = c.getTime(); if (a != b) { - errln("ERROR: " + a + " != " + b); + fail("ERROR: " + a + " != " + b); } else { - logln(a + " = " + b); + System.out.println(a + " = " + b); } } finally { TimeZone.setDefault(savedTz); @@ -224,16 +234,17 @@ * @bug 6314387 * JCK6.0: api/java_util/Date/index.html#misc fails, mustang */ + @Test public void Test6314387() { Date d = new Date(Long.MAX_VALUE); int y = d.getYear(); if (y != 292277094) { - errln("yesr: got " + y + ", expected 292277094"); + fail("yesr: got " + y + ", expected 292277094"); } d = new Date(Long.MIN_VALUE); y = d.getYear(); if (y != 292267155) { - errln("yesr: got " + y + ", expected 292267155"); + fail("yesr: got " + y + ", expected 292267155"); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Date/DateTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Date/DateTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Date/DateTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,23 +25,24 @@ * @test * @bug 4143459 * @summary test Date - * @library /java/text/testlib + * @run junit DateTest */ import java.text.*; import java.util.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + @SuppressWarnings("deprecation") -public class DateTest extends IntlTest +public class DateTest { - public static void main(String[] args) throws Exception { - new DateTest().run(args); - } - /** * @bug 4143459 * Warning: Use TestDefaultZone() for complete testing of this bug. */ + @Test public void TestDefaultZoneLite() { // Note: This test is redundant with TestDefaultZone(). It was added by // request to provide a short&sweet test for this bug. It does not test @@ -57,7 +58,7 @@ d.setHours(6); TimeZone.setDefault(TimeZone.getTimeZone("PST")); if (d.getHours() != 22) { - errln("Fail: Date.setHours()/getHours() ignoring default zone"); + fail("Fail: Date.setHours()/getHours() ignoring default zone"); } } finally { TimeZone.setDefault(save); } @@ -66,6 +67,7 @@ /** * @bug 4143459 */ + @Test public void TestDefaultZone() { // Various problems can creep up, with the current implementation of Date, // when the default zone is changed. @@ -87,7 +89,7 @@ // sub-object (most Date objects), and a Date object with a Calendar // sub-object. We make two passes to cover the two cases. for (int pass=0; pass<2; ++pass) { - logln(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); + System.out.println(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); TimeZone.setDefault(GMT); d = new Date(refstr); @@ -96,7 +98,7 @@ d.setYear(d.getYear()); } if (d.getTime() != ref.getTime()) { - errln("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + + fail("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + " " + d.getTime() + " ms"); } @@ -104,7 +106,7 @@ d.getDay(), d.getHours(), d.getTimezoneOffset() }; for (int i=0; i PER_LOOP_LIMIT) - logln("WARNING: Date constructor/getYear slower than " + + System.out.println("WARNING: Date constructor/getYear slower than " + PER_LOOP_LIMIT + " ms"); } static double PER_LOOP_LIMIT = 3.0; @@ -150,6 +153,7 @@ /** * Verify that the Date(String) constructor works. */ + @Test public void TestParseOfGMT() { Date OUT = null; @@ -164,7 +168,7 @@ // logln("PASS"); } else { - errln( "Expected: " + + fail( "Expected: " + new Date( expectedVal ) + ": " + expectedVal + @@ -178,56 +182,58 @@ // Check out Date's behavior with large negative year values; bug 664 // As of the fix to bug 4056585, Date should work correctly with // large negative years. + @Test public void TestDateNegativeYears() { Date d1= new Date(80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); d1= new Date(-80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); boolean e = false; try { d1= new Date(-800000,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); } catch (IllegalArgumentException ex) { e = true; } - if (e) errln("FAIL: Saw exception for year -800000"); - else logln("Pass: No exception for year -800000"); + if (e) fail("FAIL: Saw exception for year -800000"); + else System.out.println("Pass: No exception for year -800000"); } // Verify the behavior of Date + @Test public void TestDate480() { TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("PST")); Date d1=new java.util.Date(97,8,13,10,8,13); - logln("d = "+d1); + System.out.println("d = "+d1); Date d2=new java.util.Date(97,8,13,30,8,13); // 20 hours later - logln("d+20h = "+d2); + System.out.println("d+20h = "+d2); double delta = (d2.getTime() - d1.getTime()) / 3600000; - logln("delta = " + delta + "h"); + System.out.println("delta = " + delta + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta); + if (delta != 20.0) fail("Expected delta of 20; got " + delta); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(1997,8,13,10,8,13); Date t1 = cal.getTime(); - logln("d = "+t1); + System.out.println("d = "+t1); cal.clear(); cal.set(1997,8,13,30,8,13); // 20 hours later Date t2 = cal.getTime(); - logln("d+20h = "+t2); + System.out.println("d+20h = "+t2); double delta2 = (t2.getTime() - t1.getTime()) / 3600000; - logln("delta = " + delta2 + "h"); + System.out.println("delta = " + delta2 + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta2); + if (delta != 20.0) fail("Expected delta of 20; got " + delta2); } finally { TimeZone.setDefault(save); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Date/TimestampTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Date/TimestampTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Date/TimestampTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Date/TimestampTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,23 +26,24 @@ * @bug 5008227 * @summary Make sure that changes to the Date class don't break java.sql.Timestamp. * @modules java.sql - * @library /java/text/testlib + * @run junit TimestampTest */ import java.util.*; import java.sql.Timestamp; -public class TimestampTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimestampTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimestampTest { /** * 5008227: java.sql.Timestamp.after() is not returning correct result * * Test before(), after(), equals(), compareTo() and getTime(). */ + @Test public void Test5008227() { long t = System.currentTimeMillis(); Timestamp ts1 = new Timestamp(t), ts2 = new Timestamp(t); @@ -88,28 +89,28 @@ boolean expectedResult = expected > 0; boolean result = ts1.after(ts2); if (result != expectedResult) { - errln("ts1.after(ts2) returned " + result + fail("ts1.after(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected < 0; result = ts1.before(ts2); if (result != expectedResult) { - errln("ts1.before(ts2) returned " + result + fail("ts1.before(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected == 0; result = ts1.equals(ts2); if (result != expectedResult) { - errln("ts1.equals(ts2) returned " + result + fail("ts1.equals(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } int x = ts1.compareTo(ts2); int y = (x > 0) ? 1 : (x < 0) ? -1 : 0; if (y != expected) { - errln("ts1.compareTo(ts2) returned " + x + ", expected " + fail("ts1.compareTo(ts2) returned " + x + ", expected " + relation(expected, "") + "0" + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } @@ -122,7 +123,7 @@ z = (n1 > n2) ? 1 : (n1 < n2) ? -1 : 0; } if (z != expected) { - errln("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + fail("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + relation(expected, "==") + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + /* + * @test + * @bug 8179071 8202537 8231273 8251317 + * @summary Test that language aliases of CLDR supplemental metadata are handled correctly. + * @modules jdk.localedata + * @run junit/othervm -Djava.locale.providers=CLDR AliasesShouldBeRecognizedInCLDR + */ + +/* + * This fix is dependent on a particular version of CLDR data. + */ + +import java.time.Month; +import java.time.format.TextStyle; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class AliasesShouldBeRecognizedInCLDR { + + /* + * Deprecated and Legacy tags. + * As of CLDR 38, language aliases for some legacy tags have been removed. + */ + private static final Set LegacyAliases = Set.of( + "zh-guoyu", "zh-min-nan", "i-klingon", "i-tsu", + "sgn-CH-DE", "mo", "i-tay", "scc", + "i-hak", "sgn-BE-FR", "i-lux", "tl", "zh-hakka", "i-ami", "aa-SAAHO", + "zh-xiang", "i-pwn", "sgn-BE-NL", "jw", "sh", "i-bnn"); + + // Ensure the display name for the given tag's January is correct + @ParameterizedTest + @MethodSource("shortJanuaryNames") + public void janDisplayNameTest(String tag, String expected) { + Locale target = Locale.forLanguageTag(tag); + Month day = Month.JANUARY; + TextStyle style = TextStyle.SHORT; + String actual = day.getDisplayName(style, target); + assertEquals(expected, actual); + } + + // Expected month format data for locales after language aliases replacement. + private static Stream shortJanuaryNames() { + return Stream.of( + Arguments.of("pa-PK", "\u0a1c\u0a28"), + Arguments.of("uz-AF", "yan"), + Arguments.of("sr-ME", "\u0458\u0430\u043d"), + Arguments.of("scc", "\u0458\u0430\u043d"), + Arguments.of("sh", "jan"), + Arguments.of("ha-Latn-NE", "Jan"), + Arguments.of("i-lux", "Jan.") + ); + } + + // getAvailableLocales() should not contain any deprecated or Legacy language tags + @Test + public void invalidTagsTest() { + Set invalidTags = new HashSet<>(); + Arrays.stream(Locale.getAvailableLocales()) + .map(Locale::toLanguageTag) + .forEach(tag -> {if(LegacyAliases.contains(tag)) {invalidTags.add(tag);}}); + assertTrue(invalidTags.isEmpty(), + "Deprecated and Legacy tags found " + invalidTags + " in AvailableLocales "); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4152725.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4152725.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4152725.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4152725.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 4152725 - * @summary Verify that the default locale can be specified from the - * command line. - * @run main/othervm -Duser.language=de -Duser.country=DE -Duser.variant=EURO - * Bug4152725 de_DE_EURO - * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant= - * Bug4152725 ja - * @run main/othervm -Duser.language=en -Duser.country=SG -Duser.variant= - * Bug4152725 en_SG - * @run main/othervm -Duser.language= -Duser.country=DE -Duser.variant=EURO - * Bug4152725 _DE_EURO - * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant=YOMI - * Bug4152725 ja__YOMI - * @run main/othervm -Duser.language= -Duser.country= -Duser.variant=EURO - * Bug4152725 __EURO - * @run main/othervm -Duser.language=de -Duser.region=DE_EURO - * Bug4152725 de_DE_EURO - */ - -import java.util.Locale; - -public class Bug4152725 { - - public static void main(String[] args) { - - if (args.length != 1) { - throw new RuntimeException("expected locale needs to be specified"); - } - - Locale locale = Locale.getDefault(); - - // don't use Locale.toString - it's bogus - String language = locale.getLanguage(); - String country = locale.getCountry(); - String variant = locale.getVariant(); - String localeID = null; - if (variant.length() > 0) { - localeID = language + "_" + country + "_" + variant; - } else if (country.length() > 0) { - localeID = language + "_" + country; - } else { - localeID = language; - } - - if (localeID.equals(args[0])) { - System.out.println("Correctly set from command line: " + localeID); - } else { - throw new RuntimeException("expected default locale: " + args[0] - + ", actual default locale: " + localeID); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4184873Test.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873Test.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4184873Test.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873Test.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - @test - @summary test that locale invariants are preserved across serialization - @library /java/text/testlib - @run main Bug4184873Test - @bug 4184873 -*/ -/* - * This file is available under and governed by the GNU General Public - * License version 2 only, as published by the Free Software Foundation. - * However, the following notice accompanied the original version of this - * file and, per its terms, should not be removed: - * - * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved - * - * Portions copyright (c) 2007 Sun Microsystems, Inc. - * All Rights Reserved. - * - * The original version of this source code and documentation - * is copyrighted and owned by Taligent, Inc., a wholly-owned - * subsidiary of IBM. These materials are provided under terms - * of a License Agreement between Taligent and Sun. This technology - * is protected by multiple US and International patents. - * - * This notice and attribution to Taligent may not be removed. - * Taligent is a registered trademark of Taligent, Inc. - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for NON-COMMERCIAL purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. Please refer to the file "copyright.html" - * for further important copyright and licensing information. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF - * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED - * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - */ - -import java.util.*; -import java.io.*; - -/** - * A Locale can never contain the following language codes: he, yi or id. - */ -public class Bug4184873Test extends IntlTest { - public static void main(String[] args) throws Exception { - if (args.length == 1 && args[0].equals("prepTest")) { - prepTest(); - } else { - new Bug4184873Test().run(args); - } - } - - public void testIt() throws Exception { - verify("he"); - verify("yi"); - verify("id"); - } - - private void verify(String lang) { - try { - ObjectInputStream in = getStream(lang); - if (in != null) { - final Locale loc = (Locale)in.readObject(); - final Locale expected = new Locale(lang, "XX"); - if (!(expected.equals(loc))) { - errln("Locale didn't maintain invariants for: "+lang); - errln(" got: "+loc); - errln(" excpeted: "+expected); - } else { - logln("Locale "+lang+" worked"); - } - in.close(); - } - } catch (Exception e) { - errln(e.toString()); - } - } - - private ObjectInputStream getStream(String lang) { - try { - final File f = new File(System.getProperty("test.src", "."), "Bug4184873_"+lang); - return new ObjectInputStream(new FileInputStream(f)); - } catch (Exception e) { - errln(e.toString()); - return null; - } - } - - /** - * Create serialized output files of the test locales. After they are created, these test - * files should be corrupted (by hand) to contain invalid locale name values. - */ - private static void prepTest() { - outputLocale("he"); - outputLocale("yi"); - outputLocale("id"); - } - - private static void outputLocale(String lang) { - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("Bug4184873_"+lang)); - out.writeObject(new Locale(lang, "XX")); - out.close(); - } catch (Exception e) { - System.out.println(e); - } - } - -} Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4184873_he and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_he differ Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4184873_id and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_id differ Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4184873_yi and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4184873_yi differ diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4210525.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4210525.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4210525.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4210525.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/** - @test - @summary Locale variant should not be uppercased - @run main Bug4210525 - @bug 4210525 -*/ - -import java.util.Locale; - -public class Bug4210525 { - - public static void main(String[] args) throws Exception { - String language = "en"; - String country = "US"; - String variant = "socal"; - - Locale aLocale = new Locale(language, country, variant); - - String localeVariant = aLocale.getVariant(); - if (localeVariant.equals(variant)) { - System.out.println("passed"); - } else { - System.out.println("failed"); - throw new Exception("Bug4210525 test failed."); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4316602.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4316602.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4316602.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4316602.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/** - @test - @summary Locale constructor should allow language-only argument - @bug 4316602 - @author joconner -*/ - -import java.util.Locale; - -public class Bug4316602 { - - public static void main(String[] args) throws Exception { - String language = "ja"; - Locale aLocale = new Locale(language); - if (aLocale.toString().equals(language)) { - System.out.println("passed"); - } else { - System.out.println("Bug4316602 failed"); - throw new Exception("Bug4316602 failed"); - } - } - -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4518797.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4518797.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug4518797.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug4518797.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 4518797 - * @summary Make sure that hashCode() and read/writeObject() are thread-safe. - * @run main Bug4518797 10 - */ - -import java.util.*; -import java.io.*; - -// Usage: java Bug4518797 [duration] -public class Bug4518797 { - static volatile boolean runrun = true; - static volatile String message = null; - - public static void main(String[] args) { - int duration = 180; - if (args.length == 1) { - duration = Math.max(5, Integer.parseInt(args[0])); - } - final Locale loc = new Locale("ja", "US"); - final int hashcode = loc.hashCode(); - - System.out.println("correct hash code: " + hashcode); - Thread t1 = new Thread(new Runnable() { - public void run() { - while (runrun) { - int hc = loc.hashCode(); - if (hc != hashcode) { - runrun = false; - message = "t1: wrong hashcode: " + hc; - } - } - } - }); - - Thread t2 = new Thread(new Runnable() { - public void run() { - // Repeat serialization and deserialization. And get the - // hash code from a deserialized Locale object. - while (runrun) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(loc); - byte[] b = baos.toByteArray(); - oos.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(b); - ObjectInputStream ois = new ObjectInputStream(bais); - Locale loc2 = (Locale) ois.readObject(); - int hc = loc2.hashCode(); - if (hc != hashcode) { - runrun = false; - message = "t2: wrong hashcode: " + hc; - } - } catch (IOException ioe) { - runrun = false; - throw new RuntimeException("t2: can't perform test", ioe); - } catch (ClassNotFoundException cnfe) { - runrun = false; - throw new RuntimeException("t2: can't perform test", cnfe); - } - } - } - }); - - t1.start(); - t2.start(); - try { - for (int i = 0; runrun && i < duration; i++) { - Thread.sleep(1000); - } - runrun = false; - t1.join(); - t2.join(); - } catch (InterruptedException e) { - } - if (message != null) { - throw new RuntimeException(message); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug6989440.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug6989440.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug6989440.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug6989440.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 6989440 - * @summary Verify ConcurrentModificationException is not thrown with multiple - * thread accesses. - * @modules java.base/sun.util.locale.provider - * @compile -XDignore.symbol.file=true Bug6989440.java - * @run main Bug6989440 - */ -import java.text.spi.DateFormatProvider; -import java.util.spi.LocaleNameProvider; -import java.util.spi.LocaleServiceProvider; -import java.util.spi.TimeZoneNameProvider; - -import sun.util.locale.provider.LocaleServiceProviderPool; - -public class Bug6989440 { - static volatile boolean failed; // false - static final int THREADS = 50; - - public static void main(String[] args) throws Exception { - Thread[] threads = new Thread[THREADS]; - for (int i=0; i cls; - private static int count; - - public TestThread(Class providerClass) { - cls = providerClass; - } - - public TestThread() { - int which = count++ % 3; - switch (which) { - case 0 : cls = LocaleNameProvider.class; break; - case 1 : cls = TimeZoneNameProvider.class; break; - case 2 : cls = DateFormatProvider.class; break; - default : throw new AssertionError("Should not reach here"); - } - } - - public void run() { - try { - LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(cls); - pool.getAvailableLocales(); - } catch (Exception e) { - System.out.println(e); - e.printStackTrace(); - failed = true; - } - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug7069824.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug7069824.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug7069824.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug7069824.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,468 +0,0 @@ -/* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 7069824 8042360 8032842 8175539 8210443 8242010 - * @summary Verify implementation for Locale matching. - * @run testng/othervm Bug7069824 - */ - -import java.util.*; -import java.util.Locale.*; -import static java.util.Locale.FilteringMode.*; -import static java.util.Locale.LanguageRange.*; -import static org.testng.Assert.*; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -public class Bug7069824 { - - @DataProvider(name = "LRConstructorData") - Object[][] LRConstructorData() { - return new Object[][] { - // Range, Weight - {"elvish", MAX_WEIGHT}, - {"de-DE", MAX_WEIGHT}, - {"de-Latn-DE-1996", MAX_WEIGHT}, - {"zh-Hant-CN-x-private1-private2", MAX_WEIGHT}, - {"ar", 0.8}, - {"en-US", 0.5}, - {"sr-Latn-BA", 0}, - {"ja", 1}, - }; - } - - @DataProvider(name = "LRConstructorNPEData") - Object[][] LRConstructorNPEData() { - return new Object[][] { - // Range, Weight - {null, MAX_WEIGHT}, - {null, 0.8}, - }; - } - - @DataProvider(name = "LRConstructorIAEData") - Object[][] LRConstructorIAEData() { - return new Object[][] { - // Range, Weight - {"ja", -0.8}, - {"Elvish", 3.0}, - {"-ja", MAX_WEIGHT}, - {"ja--JP", MAX_WEIGHT}, - {"en-US-", MAX_WEIGHT}, - {"a4r", MAX_WEIGHT}, - {"ar*", MAX_WEIGHT}, - {"ar-*EG", MAX_WEIGHT}, - {"abcdefghijklmn", MAX_WEIGHT}, - {"ja-J=", MAX_WEIGHT}, - {"ja-opqrstuvwxyz", MAX_WEIGHT}, - {"zh_CN", MAX_WEIGHT}, - {"1996-de-Latn", MAX_WEIGHT}, - // Testcase for 8042360 - {"en-Latn-1234567890", MAX_WEIGHT}, - }; - } - - @DataProvider(name = "LRParseData") - Object[][] LRParseData() { - return new Object[][] { - // Ranges, Expected result - {"Accept-Language: fr-FX, de-DE;q=0.5, fr-tp-x-FOO;q=0.1, " - + "en-X-tp;q=0.6, en-FR;q=0.7, de-de;q=0.8, iw;q=0.4, " - + "he;q=0.4, de-de;q=0.5, ja, in-tpp, in-tp;q=0.2", - List.of(new LanguageRange("fr-fx", 1.0), - new LanguageRange("fr-fr", 1.0), - new LanguageRange("ja", 1.0), - new LanguageRange("in-tpp", 1.0), - new LanguageRange("id-tpp", 1.0), - new LanguageRange("en-fr", 0.7), - new LanguageRange("en-fx", 0.7), - new LanguageRange("en-x-tp", 0.6), - new LanguageRange("de-de", 0.5), - new LanguageRange("de-dd", 0.5), - new LanguageRange("iw", 0.4), - new LanguageRange("he", 0.4), - new LanguageRange("in-tp", 0.2), - new LanguageRange("id-tl", 0.2), - new LanguageRange("id-tp", 0.2), - new LanguageRange("in-tl", 0.2), - new LanguageRange("fr-tp-x-foo", 0.1), - new LanguageRange("fr-tl-x-foo", 0.1))}, - {"Accept-Language: hak-CN;q=0.8, no-bok-NO;q=0.9, no-nyn, cmn-CN;q=0.1", - List.of(new LanguageRange("no-nyn", 1.0), - new LanguageRange("nn", 1.0), - new LanguageRange("no-bok-no", 0.9), - new LanguageRange("nb-no", 0.9), - new LanguageRange("hak-CN", 0.8), - new LanguageRange("zh-hakka-CN", 0.8), - new LanguageRange("i-hak-CN", 0.8), - new LanguageRange("zh-hak-CN", 0.8), - new LanguageRange("cmn-CN", 0.1), - new LanguageRange("zh-guoyu-CN", 0.1), - new LanguageRange("zh-cmn-CN", 0.1))}, - {"Accept-Language: rki;q=0.4, no-bok-NO;q=0.9, ccq;q=0.5", - List.of(new LanguageRange("no-bok-no", 0.9), - new LanguageRange("nb-no", 0.9), - new LanguageRange("rki", 0.4), - new LanguageRange("ybd", 0.4), - new LanguageRange("ccq", 0.4))}, - }; - } - - @DataProvider(name = "LRParseIAEData") - Object[][] LRParseIAEData() { - return new Object[][] { - // Ranges - {""}, - {"ja;q=3"}, - }; - } - - @DataProvider(name = "LRMapEquivalentsData") - Object[][] LRMapEquivalentsData() { - return new Object[][] { - // Ranges, Map, Expected result - {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), - new HashMap<>(), - LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4")}, - {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), - null, - LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4")}, - {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), - new LinkedHashMap>() { - { - put("ja", List.of("ja", "ja-Hira")); - put("zh", List.of("zh-Hans", "zh-Hans-CN", "zh-CN")); - put("zh-TW", List.of("zh-TW", "zh-Hant")); - put("es", null); - put("en", List.of()); - put("zh-HK", List.of("de")); - } - }, - List.of(new LanguageRange("zh-hans", 1.0), - new LanguageRange("zh-hans-cn", 1.0), - new LanguageRange("zh-cn", 1.0), - new LanguageRange("de", 1.0), - new LanguageRange("ar", 0.9), - new LanguageRange("zh-tw", 0.8), - new LanguageRange("zh-hant", 0.8), - new LanguageRange("ja-jp", 0.2), - new LanguageRange("ja-hira-jp", 0.2))}, - }; - } - - @DataProvider(name = "LFilterData") - Object[][] LFilterData() { - return new Object[][] { - // Range, LanguageTags, FilteringMode, Expected locales - {"ja-JP, fr-FR", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", - EXTENDED_FILTERING, "ja-JP-hepburn, ja-Latn-JP"}, - {"ja-*-JP, fr-FR", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", - EXTENDED_FILTERING, "ja-JP-hepburn, ja-Latn-JP"}, - {"ja-*-JP, fr-FR, de-de;q=0.2", "de-DE, en, ja-JP-hepburn, de-de, fr, he, ja-Latn-JP", - AUTOSELECT_FILTERING, "ja-JP-hepburn, ja-Latn-JP, de-DE"}, - {"ja-JP, fr-FR, de-de;q=0.2", "de-DE, en, ja-JP-hepburn, de-de, fr, he, ja-Latn-JP", - AUTOSELECT_FILTERING, "ja-JP-hepburn, de-DE"}, - {"en;q=0.2, ja-*-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", - IGNORE_EXTENDED_RANGES, "en"}, - {"en;q=0.2, ja-*-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", - MAP_EXTENDED_RANGES, "ja-JP-hepburn, en"}, - {"en;q=0.2, ja-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", - REJECT_EXTENDED_RANGES, "ja-JP-hepburn, en"}, - {"en;q=0.2, ja-*-JP, fr-JP", "", REJECT_EXTENDED_RANGES, ""}, - }; - } - - @DataProvider(name = "LFilterNPEData") - Object[][] LFilterNPEData() { - return new Object[][] { - // Range, LanguageTags, FilteringMode - {"en;q=0.2, ja-*-JP, fr-JP", null, REJECT_EXTENDED_RANGES}, - {null, "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", REJECT_EXTENDED_RANGES}, - }; - } - - @DataProvider(name = "LFilterTagsData") - Object[][] LFilterTagsData() { - return new Object[][] { - // Range, LanguageTags, FilteringMode, Expected language tags - {"en;q=0.2, *;q=0.6, ja", "de-DE, en, ja-JP-hepburn, fr-JP, he", - null, "de-DE, en, ja-JP-hepburn, fr-JP, he"}, - {"en;q=0.2, ja-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he", - null, "ja-JP-hepburn, en"}, - {"en;q=0.2, ja-JP, fr-JP, iw", "de-DE, he, en, ja-JP-hepburn, fr, he-IL", - null, "ja-JP-hepburn, he, he-IL, en"}, - {"en;q=0.2, ja-JP, fr-JP, he", "de-DE, en, ja-JP-hepburn, fr, iw-IL", - null, "ja-JP-hepburn, iw-IL, en"}, - {"de-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " - + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", - MAP_EXTENDED_RANGES, "de-DE, de-DE-x-goethe"}, - {"de-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " - + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", - EXTENDED_FILTERING, - "de-DE, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " - + "de-Latn-DE-1996, de-Deva-DE"}, - {"de-*-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " - + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", - EXTENDED_FILTERING, - "de-DE, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " - + "de-Latn-DE-1996, de-Deva-DE"}, - }; - } - - @DataProvider(name = "LLookupData") - Object[][] LLookupData() { - return new Object[][] { - // Range, LanguageTags, Expected locale - {"en;q=0.2, *-JP;q=0.6, iw", "de-DE, en, ja-JP-hepburn, fr-JP, he", "he"}, - {"en;q=0.2, *-JP;q=0.6, iw", "de-DE, he-IL, en, iw", "he"}, - {"en;q=0.2, ja-*-JP-x-foo;q=0.6, iw", "de-DE, fr, en, ja-Latn-JP", "ja-Latn-JP"}, - }; - } - - @DataProvider(name = "LLookupTagData") - Object[][] LLookupTagData() { - return new Object[][] { - // Range, LanguageTags, Expected language tag - {"en, *", "es, de, ja-JP", null}, - {"en;q=0.2, *-JP", "de-DE, en, ja-JP-hepburn, fr-JP, en-JP", "fr-JP"}, - {"en;q=0.2, ar-MO, iw", "de-DE, he, fr-JP", "he"}, - {"en;q=0.2, ar-MO, he", "de-DE, iw, fr-JP", "iw"}, - {"de-DE-1996;q=0.8, en;q=0.2, iw;q=0.9, zh-Hans-CN;q=0.7", "de-DE, zh-CN, he, iw, fr-JP", "iw"}, - {"de-DE-1996;q=0.8, en;q=0.2, he;q=0.9, zh-Hans-CN;q=0.7", "de-DE, zh-CN, he, iw, fr-JP", "he"}, - }; - } - - @Test - public void testLRConstants() { - assertEquals(MIN_WEIGHT, 0.0, " MIN_WEIGHT should be 0.0 but got " - + MIN_WEIGHT); - assertEquals(MAX_WEIGHT, 1.0, " MAX_WEIGHT should be 1.0 but got " - + MAX_WEIGHT); - } - - @Test(dataProvider = "LRConstructorData") - public void testLRConstructors(String range, double weight) { - LanguageRange lr; - if (weight == MAX_WEIGHT) { - lr = new LanguageRange(range); - } else { - lr = new LanguageRange(range, weight); - } - assertEquals(lr.getRange(), range.toLowerCase(Locale.ROOT), - " LR.getRange() returned unexpected value. Expected: " - + range.toLowerCase(Locale.ROOT) + ", got: " + lr.getRange()); - assertEquals(lr.getWeight(), weight, - " LR.getWeight() returned unexpected value. Expected: " - + weight + ", got: " + lr.getWeight()); - } - - @Test(dataProvider = "LRConstructorNPEData", expectedExceptions = NullPointerException.class) - public void testLRConstructorNPE(String range, double weight) { - if (weight == MAX_WEIGHT) { - new LanguageRange(range); - } else { - new LanguageRange(range, weight); - } - } - - @Test(dataProvider = "LRConstructorIAEData", expectedExceptions = IllegalArgumentException.class) - public void testLRConstructorIAE(String range, double weight) { - if (weight == MAX_WEIGHT) { - new LanguageRange(range); - } else { - new LanguageRange(range, weight); - } - } - - @Test - public void testLREquals() { - LanguageRange lr1 = new LanguageRange("ja", 1.0); - LanguageRange lr2 = new LanguageRange("ja"); - LanguageRange lr3 = new LanguageRange("ja", 0.1); - LanguageRange lr4 = new LanguageRange("en", 1.0); - - assertEquals(lr1, lr2, " LR(ja, 1.0).equals(LR(ja)) should return true."); - assertNotEquals(lr1, lr3, " LR(ja, 1.0).equals(LR(ja, 0.1)) should return false."); - assertNotEquals(lr1, lr4, " LR(ja, 1.0).equals(LR(en, 1.0)) should return false."); - assertNotNull(lr1, " LR(ja, 1.0).equals(null) should return false."); - assertNotEquals(lr1, "", " LR(ja, 1.0).equals(\"\") should return false."); - } - - @Test(dataProvider = "LRParseData") - public void testLRParse(String ranges, List expected) { - assertEquals(LanguageRange.parse(ranges), expected, - " LR.parse(" + ranges + ") test failed."); - } - - @Test(expectedExceptions = NullPointerException.class) - public void testLRParseNPE() { - LanguageRange.parse(null); - } - - @Test(dataProvider = "LRParseIAEData", expectedExceptions = IllegalArgumentException.class) - public void testLRParseIAE(String ranges) { - LanguageRange.parse(ranges); - } - - @Test(dataProvider = "LRMapEquivalentsData") - public void testLRMapEquivalents(List priorityList, - Map> map, List expected) { - assertEquals(LanguageRange.mapEquivalents(priorityList, map), expected, - " LR.mapEquivalents() test failed."); - } - - @Test(expectedExceptions = NullPointerException.class) - public void testLRMapEquivalentsNPE() { - LanguageRange.mapEquivalents(null, Map.of("ja", List.of("ja", "ja-Hira"))); - } - - @Test(dataProvider = "LFilterData") - public void testLFilter(String ranges, String tags, FilteringMode mode, String expectedLocales) { - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLocales(tags); - String actualLocales = - showLocales(Locale.filter(priorityList, tagList, mode)); - assertEquals(actualLocales, expectedLocales, showErrorMessage(" L.Filter(" + mode + ")", - ranges, tags, expectedLocales, actualLocales)); - } - - @Test(dataProvider = "LFilterNPEData", expectedExceptions = NullPointerException.class) - public void testLFilterNPE(String ranges, String tags, FilteringMode mode) { - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLocales(tags); - showLocales(Locale.filter(priorityList, tagList, mode)); - } - - @Test(expectedExceptions = IllegalArgumentException.class) - public void testLFilterIAE() { - String ranges = "en;q=0.2, ja-*-JP, fr-JP"; - String tags = "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP"; - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLocales(tags); - showLocales(Locale.filter(priorityList, tagList, REJECT_EXTENDED_RANGES)); - } - - @Test(dataProvider = "LFilterTagsData") - public void testLFilterTags(String ranges, String tags, FilteringMode mode, String expectedTags) { - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLanguageTags(tags); - String actualTags; - if (mode == null) { - actualTags = showLanguageTags(Locale.filterTags(priorityList, tagList)); - } else { - actualTags = showLanguageTags(Locale.filterTags(priorityList, tagList, mode)); - } - assertEquals(actualTags, expectedTags, - showErrorMessage(" L.FilterTags(" + (mode != null ? mode : "") + ")", - ranges, tags, expectedTags, actualTags)); - } - - @Test(dataProvider = "LLookupData") - public void testLLookup(String ranges, String tags, String expectedLocale) { - List priorityList = LanguageRange.parse(ranges); - List localeList = generateLocales(tags); - String actualLocale = - Locale.lookup(priorityList, localeList).toLanguageTag(); - assertEquals(actualLocale, expectedLocale, showErrorMessage(" L.Lookup()", - ranges, tags, expectedLocale, actualLocale)); - } - - @Test(dataProvider = "LLookupTagData") - public void testLLookupTag(String ranges, String tags, String expectedTag) { - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLanguageTags(tags); - String actualTag = Locale.lookupTag(priorityList, tagList); - assertEquals(actualTag, expectedTag, showErrorMessage(" L.LookupTag()", - ranges, tags, expectedTag, actualTag)); - } - - private static List generateLocales(String tags) { - if (tags == null) { - return null; - } - - List localeList = new ArrayList<>(); - if (tags.equals("")) { - return localeList; - } - String[] t = tags.split(", "); - for (String tag : t) { - localeList.add(Locale.forLanguageTag(tag)); - } - return localeList; - } - - private static List generateLanguageTags(String tags) { - List tagList = new ArrayList<>(); - String[] t = tags.split(", "); - for (String tag : t) { - tagList.add(tag); - } - return tagList; - } - - private static String showLanguageTags(List tags) { - StringBuilder sb = new StringBuilder(); - - Iterator itr = tags.iterator(); - if (itr.hasNext()) { - sb.append(itr.next()); - } - while (itr.hasNext()) { - sb.append(", "); - sb.append(itr.next()); - } - - return sb.toString().trim(); - } - - private static String showLocales(List locales) { - StringBuilder sb = new StringBuilder(); - - Iterator itr = locales.iterator(); - if (itr.hasNext()) { - sb.append(itr.next().toLanguageTag()); - } - while (itr.hasNext()) { - sb.append(", "); - sb.append(itr.next().toLanguageTag()); - } - - return sb.toString().trim(); - } - - private static String showErrorMessage(String methodName, - String priorityList, - String tags, - String expectedTags, - String actualTags) { - return "Incorrect " + methodName + " result." - + " Priority list : " + priorityList - + " Language tags : " + tags - + " Expected value : " + expectedTags - + " Actual value : " + actualTags; - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8004240.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8004240.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8004240.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8004240.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 8004240 - * @summary Verify that getAdapterPreference returns an unmodifiable list. - * @modules java.base/sun.util.locale.provider - * @compile -XDignore.symbol.file Bug8004240.java - * @run main Bug8004240 - */ - -import java.util.List; -import sun.util.locale.provider.LocaleProviderAdapter; - -public class Bug8004240 { - - public static void main(String[] args) { - List types = LocaleProviderAdapter.getAdapterPreference(); - - try { - types.set(0, null); - } catch (UnsupportedOperationException e) { - // success - return; - } - - throw new RuntimeException("LocaleProviderAdapter.getAdapterPrefence() returned a modifiable list."); - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8035133.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8035133.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8035133.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8035133.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 8035133 - * @summary Checks that the tags matching the range with quality weight q=0 - * e.g. en;q=0 must be elimited and must not be the part of output - */ - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - - -public class Bug8035133 { - - private static boolean err = false; - - public static void main(String[] args) { - - // checking Locale.lookup with de-ch;q=0 - checkLookup("en;q=0.1, *-ch;q=0.5, de-ch;q=0", - "de-ch, en, fr-ch", "fr-CH"); - - /* checking Locale.lookup with *;q=0 '*' should be ignored - * in lookup - */ - checkLookup("en;q=0.1, *-ch;q=0.5, *;q=0", - "de-ch, en, fr-ch", "de-CH"); - - // checking Locale.filter with fr-ch;q=0 in BASIC_FILTERING - checkFilter("en;q=0.1, fr-ch;q=0.0, de-ch;q=0.5", - "de-ch, en, fr-ch", "de-CH, en"); - - // checking Locale.filter with *;q=0 in BASIC_FILTERING - checkFilter("de-ch;q=0.6, *;q=0", "de-ch, fr-ch", ""); - - // checking Locale.filter with *;q=0 in BASIC_FILTERING - checkFilter("de-ch;q=0.6, de;q=0", "de-ch", ""); - - // checking Locale.filter with *;q=0.6, en;q=0 in BASIC_FILTERING - checkFilter("*;q=0.6, en;q=0", "de-ch, hi-in, en", "de-CH, hi-IN"); - - // checking Locale.filter with de-ch;q=0 in EXTENDED_FILTERING - checkFilter("en;q=0.1, *-ch;q=0.5, de-ch;q=0", - "de-ch, en, fr-ch", "fr-CH, en"); - - /* checking Locale.filter with *-ch;q=0 in EXTENDED_FILTERING which - * must make filter to return "" empty or no match - */ - checkFilter("de-ch;q=0.5, *-ch;q=0", "de-ch, fr-ch", ""); - - /* checking Locale.filter with *;q=0 in EXTENDED_FILTERING which - * must make filter to return "" empty or no match - */ - checkFilter("*-ch;q=0.5, *;q=0", "de-ch, fr-ch", ""); - - /* checking Locale.filter with *;q=0.6, *-Latn;q=0 in - * EXTENDED_FILTERING - */ - checkFilter("*;q=0.6, *-Latn;q=0", "de-ch, hi-in, en-Latn", - "de-CH, hi-IN"); - - if (err) { - throw new RuntimeException("[LocaleMatcher method(s) failed]"); - } - - } - - private static void checkLookup(String ranges, String tags, - String expectedLocale) { - - List priorityList = Locale.LanguageRange - .parse(ranges); - List localeList = generateLocales(tags); - Locale loc = Locale.lookup(priorityList, localeList); - String actualLocale - = loc.toLanguageTag(); - - if (!actualLocale.equals(expectedLocale)) { - System.err.println("Locale.lookup failed with ranges: " + ranges - + " Expected: " + expectedLocale - + " Actual: " + actualLocale); - err = true; - } - - } - - private static void checkFilter(String ranges, String tags, - String expectedLocales) { - - List priorityList = Locale.LanguageRange - .parse(ranges); - List localeList = generateLocales(tags); - String actualLocales = getLocalesAsString( - Locale.filter(priorityList, localeList)); - - if (!actualLocales.equals(expectedLocales)) { - System.err.println("Locale.filter failed with ranges: " + ranges - + " Expected: " + expectedLocales - + " Actual: " + actualLocales); - err = true; - } - - } - - private static List generateLocales(String tags) { - if (tags == null) { - return null; - } - - List localeList = new ArrayList<>(); - if (tags.equals("")) { - return localeList; - } - String[] t = tags.split(", "); - for (String tag : t) { - localeList.add(Locale.forLanguageTag(tag)); - } - return localeList; - } - - private static String getLocalesAsString(List locales) { - StringBuilder sb = new StringBuilder(); - - Iterator itr = locales.iterator(); - if (itr.hasNext()) { - sb.append(itr.next().toLanguageTag()); - } - while (itr.hasNext()) { - sb.append(", "); - sb.append(itr.next().toLanguageTag()); - } - - return sb.toString().trim(); - } - -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8135061.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8135061.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8135061.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8135061.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 8135061 - * @summary Checks that the Locale.lookup executes properly without throwing - * any exception for some specific language ranges - * @run main Bug8135061 - */ - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Locale.LanguageRange; - -public class Bug8135061 { - - public static void main(String[] args) { - - /* lookup should run without throwing any exception and - * return null as the language range does not match with the language - * tag - */ - List ranges = LanguageRange.parse("nv"); - Collection locales = Collections.singleton(Locale.ENGLISH); - - try { - Locale match = Locale.lookup(ranges, locales); - if (match != null) { - throw new RuntimeException("Locale.lookup returned non-null: " - + match); - } - } catch (Exception ex) { - throw new RuntimeException("[Locale.lookup failed on language" - + " range: " + ranges + " and language tags " - + locales + "]", ex); - } - - /* lookup should run without throwing any exception and - * return "nv" as the matching tag - */ - ranges = LanguageRange.parse("i-navajo"); - locales = Collections.singleton(new Locale("nv")); - - try { - Locale match = Locale.lookup(ranges, locales); - if (!match.toLanguageTag().equals("nv")) { - throw new RuntimeException("Locale.lookup returned unexpected" - + " result: " + match); - } - } catch (Exception ex) { - throw new RuntimeException("[Locale.lookup failed on language" - + " range: " + ranges + " and language tags " - + locales + "]", ex); - } - - } - -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8154797.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8154797.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8154797.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8154797.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 8154797 - * @modules java.base/sun.util.locale.provider - * java.base/sun.util.resources - * jdk.localedata - * @summary Test for checking HourFormat and GmtFormat resources are retrieved from - * COMPAT and CLDR Providers. -*/ - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; -import sun.util.locale.provider.LocaleProviderAdapter.Type; -import sun.util.locale.provider.LocaleProviderAdapter; - -public class Bug8154797 { - static Map expectedResourcesMap = new HashMap<>(); - static final String GMT_RESOURCE_KEY = "timezone.gmtFormat"; - static final String HMT_RESOURCE_KEY = "timezone.hourFormat"; - static final String GMT = "Gmt"; - static final String HMT = "Hmt"; - - static void generateExpectedValues() { - expectedResourcesMap.put("FR" + GMT, "UTC{0}"); - expectedResourcesMap.put("FR" + HMT, "+HH:mm;\u2212HH:mm"); - expectedResourcesMap.put("FI" + HMT, "+H.mm;-H.mm"); - expectedResourcesMap.put("FI" + GMT, "UTC{0}"); - /* For root locale, en_US, de_DE, hi_IN, ja_JP,Root locale resources - * should be returned. - */ - expectedResourcesMap.put(GMT, "GMT{0}"); //Root locale resource - expectedResourcesMap.put(HMT, "+HH:mm;-HH:mm"); //Root locale resource - } - - static void compareResources(Locale loc) { - String mapKeyHourFormat = HMT, mapKeyGmtFormat = GMT; - ResourceBundle compatBundle, cldrBundle; - compatBundle = LocaleProviderAdapter.forJRE().getLocaleResources(loc) - .getJavaTimeFormatData(); - cldrBundle = LocaleProviderAdapter.forType(Type.CLDR) - .getLocaleResources(loc).getJavaTimeFormatData(); - if (loc.getCountry() == "FR" || loc.getCountry() == "FI") { - mapKeyHourFormat = loc.getCountry() + HMT; - mapKeyGmtFormat = loc.getCountry() + GMT; - } - - if (!(expectedResourcesMap.get(mapKeyGmtFormat) - .equals(compatBundle.getString(GMT_RESOURCE_KEY)) - && expectedResourcesMap.get(mapKeyHourFormat) - .equals(compatBundle.getString(HMT_RESOURCE_KEY)) - && expectedResourcesMap.get(mapKeyGmtFormat) - .equals(cldrBundle.getString(GMT_RESOURCE_KEY)) - && expectedResourcesMap.get(mapKeyHourFormat) - .equals(cldrBundle.getString(HMT_RESOURCE_KEY)))) { - - throw new RuntimeException("Retrieved resource does not match with " - + " expected string for Locale " + compatBundle.getLocale()); - - } - - } - - public static void main(String args[]) { - Bug8154797.generateExpectedValues(); - Locale[] locArr = {new Locale("hi", "IN"), Locale.UK, new Locale("fi", "FI"), - Locale.ROOT, Locale.GERMAN, Locale.JAPANESE, - Locale.ENGLISH, Locale.FRANCE}; - for (Locale loc : locArr) { - Bug8154797.compareResources(loc); - } - } - -} - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8159420.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8159420.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8159420.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8159420.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,224 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -/* - * @test - * @bug 8159420 - * @summary Checks the proper execution of LanguageRange.parse() and - * other LocaleMatcher methods when used in the locales like - * Turkish, because the toLowerCase() method is invoked in the - * parse() and other LocaleMatcher methods. - * e.g. "HI-Deva".toLowerCase() in the Turkish locale returns - * "hı-deva", where 'ı' is the LATIN SMALL LETTER DOTLESS I character - * which is not allowed in the language ranges/tags. - * @compile -encoding utf-8 Bug8159420.java - * @run main Bug8159420 - */ - -import java.util.List; -import java.util.Locale; -import java.util.Locale.LanguageRange; -import java.util.Locale.FilteringMode; -import java.util.LinkedHashMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.ArrayList; -import static java.util.Locale.FilteringMode.EXTENDED_FILTERING; -import static java.util.Locale.FilteringMode.AUTOSELECT_FILTERING; - -public class Bug8159420 { - - static boolean err = false; - - public static void main(String[] args) { - - Locale origLocale = null; - try { - - origLocale = Locale.getDefault(); - Locale.setDefault(new Locale("tr", "TR")); - testParse(); - testFilter(EXTENDED_FILTERING); - testFilter(AUTOSELECT_FILTERING); - testLookup(); - testMapEquivalents(); - - if (err) { - throw new RuntimeException("[LocaleMatcher method(s) in turkish" - + " locale failed]"); - } - - } finally { - Locale.setDefault(origLocale); - } - - } - - /* Before the fix, the testParse() method was throwing - * IllegalArgumentException in Turkish Locale - */ - private static void testParse() { - String ranges = "HI-Deva, ja-hIrA-JP, RKI"; - try { - LanguageRange.parse(ranges); - } catch (Exception ex) { - System.err.println("[testParse() failed on range string: " - + ranges + "] due to "+ex); - err = true; - } - } - - /* Before the fix, the testFilter() method was returning empty list in - * Turkish Locale - */ - private static void testFilter(FilteringMode mode) { - - String ranges = "hi-IN, itc-Ital"; - String tags = "hi-IN, itc-Ital"; - List priorityList = LanguageRange.parse(ranges); - List tagList = generateLocales(tags); - String actualLocales = showLocales(Locale.filter(priorityList, tagList, mode)); - String expectedLocales = "hi-IN, itc-Ital"; - - if (!expectedLocales.equals(actualLocales)) { - System.err.println("testFilter(" + mode + ") failed on language ranges:" - + " [" + ranges + "] and language tags: [" + tags + "]"); - err = true; - } - } - - /* Before the fix, the testLookup() method was returning null in Turkish - * Locale - */ - private static void testLookup() { - boolean error = false; - String ranges = "hi-IN, itc-Ital"; - String tags = "hi-IN, itc-Ital"; - List priorityList = LanguageRange.parse(ranges); - List localeList = generateLocales(tags); - Locale actualLocale - = Locale.lookup(priorityList, localeList); - String actualLocaleString = ""; - - if (actualLocale != null) { - actualLocaleString = actualLocale.toLanguageTag(); - } else { - error = true; - } - - String expectedLocale = "hi-IN"; - - if (!expectedLocale.equals(actualLocaleString)) { - error = true; - } - - if (error) { - System.err.println("testLookup() failed on language ranges:" - + " [" + ranges + "] and language tags: [" + tags + "]"); - err = true; - } - - } - - /* Before the fix, testMapEquivalents() method was returning only "hi-in" - * in Turkish Locale - */ - private static void testMapEquivalents() { - - String ranges = "HI-IN"; - List priorityList = LanguageRange.parse(ranges); - HashMap> map = new LinkedHashMap<>(); - List equivalentList = new ArrayList<>(); - equivalentList.add("HI"); - equivalentList.add("HI-Deva"); - map.put("HI", equivalentList); - - List expected = new ArrayList<>(); - expected.add(new LanguageRange("hi-in")); - expected.add(new LanguageRange("hi-deva-in")); - List got - = LanguageRange.mapEquivalents(priorityList, map); - - if (!areEqual(expected, got)) { - System.err.println("testMapEquivalents() failed"); - err = true; - } - - } - - private static boolean areEqual(List expected, - List got) { - - boolean error = false; - if (expected.equals(got)) { - return !error; - } - - List cloneExpected = new ArrayList<>(expected); - cloneExpected.removeAll(got); - if (!cloneExpected.isEmpty()) { - error = true; - System.err.println("Found missing range(s): " + cloneExpected); - } - - // not creating the 'got' clone as the list will not be used after this - got.removeAll(expected); - if (!got.isEmpty()) { - error = true; - System.err.println("Found extra range(s): " + got); - } - return !error; - } - - private static List generateLocales(String tags) { - if (tags == null) { - return null; - } - - List localeList = new ArrayList<>(); - if (tags.equals("")) { - return localeList; - } - String[] t = tags.split(", "); - for (String tag : t) { - localeList.add(Locale.forLanguageTag(tag)); - } - return localeList; - } - - private static String showLocales(List locales) { - StringBuilder sb = new StringBuilder(); - - Iterator itr = locales.iterator(); - if (itr.hasNext()) { - sb.append(itr.next().toLanguageTag()); - } - while (itr.hasNext()) { - sb.append(", "); - sb.append(itr.next().toLanguageTag()); - } - - return sb.toString().trim(); - } - -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8166994.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8166994.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8166994.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8166994.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 8166884 - * @summary Checks the subsequent call to parse the same language ranges - * which must generate the same list of language ranges - * i.e. the priority list containing equivalents, as in the - * first call - */ - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - -public class Bug8166994 { - - public static void main(String[] args) { - List list = Arrays.asList("ccq-aa", "ybd-aa", "rki-aa"); - String ranges = "ccq-aa"; - testParseConsistency(list, ranges); - - // consecutive call to check the language range parse consistency - testParseConsistency(list, ranges); - - // another case with ranges consisting of multiple equivalents and - // single equivalents - list = Arrays.asList("gfx-xz", "oun-xz", "mwj-xz", "vaj-xz", - "taj-xy", "tsf-xy"); - ranges = "gfx-xz, taj-xy"; - testParseConsistency(list, ranges); - // consecutive call to check the language range parse consistency - testParseConsistency(list, ranges); - - } - - private static void testParseConsistency(List list, String ranges) { - List priorityList = parseRanges(ranges); - if (!list.equals(priorityList)) { - throw new RuntimeException("Failed to parse the language range [" - + ranges + "], Expected: " + list + " Found: " - + priorityList); - } - } - - private static List parseRanges(String s) { - return Locale.LanguageRange.parse(s).stream() - .map(Locale.LanguageRange::getRange) - .collect(Collectors.toList()); - } - -} - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8179071.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8179071.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/Bug8179071.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/Bug8179071.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - /* - * @test - * @bug 8179071 8202537 8231273 8251317 - * @summary Test that language aliases of CLDR supplemental metadata are handled correctly. - * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=CLDR Bug8179071 - */ - -/** - * This fix is dependent on a particular version of CLDR data. - */ - -import java.time.Month; -import java.time.format.TextStyle; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -public class Bug8179071 { - - // Deprecated and Legacy tags. - // As of CLDR 38, language aliases for some of the legacy tags have been removed. - private static final Set LegacyAliases = Set.of( - "zh-guoyu", "zh-min-nan", "i-klingon", "i-tsu", - "sgn-CH-DE", "mo", "i-tay", "scc", - "i-hak", "sgn-BE-FR", "i-lux", "tl", "zh-hakka", "i-ami", "aa-SAAHO", - "zh-xiang", "i-pwn", "sgn-BE-NL", "jw", "sh", "i-bnn"); - // expected month format data for locales after language aliases replacement. - private static final Map shortJanuaryNames = Map.of( "pa-PK", "\u0a1c\u0a28", - "uz-AF" , "yan", - "sr-ME", "\u0458\u0430\u043d", - "scc", "\u0458\u0430\u043d", - "sh", "jan", - "ha-Latn-NE", "Jan", - "i-lux", "Jan."); - - - private static void test(String tag, String expected) { - Locale target = Locale.forLanguageTag(tag); - Month day = Month.JANUARY; - TextStyle style = TextStyle.SHORT; - String actual = day.getDisplayName(style, target); - if (!actual.equals(expected)) { - throw new RuntimeException("failed for locale " + tag + " actual output " + actual +" does not match with " + expected); - } - } - - /** - * getAvailableLocales() should not contain any deprecated or Legacy language tags - */ - private static void checkInvalidTags() { - Set invalidTags = new HashSet<>(); - Arrays.asList(Locale.getAvailableLocales()).stream() - .map(loc -> loc.toLanguageTag()) - .forEach( tag -> {if(LegacyAliases.contains(tag)) {invalidTags.add(tag);}}); - if (!invalidTags.isEmpty()) { - throw new RuntimeException("failed: Deprecated and Legacy tags found " + invalidTags + " in AvailableLocales "); - } - } - - public static void main(String[] args) { - shortJanuaryNames.forEach(Bug8179071::test); - checkInvalidTags(); - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/CaseCheckVariant.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CaseCheckVariant.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/CaseCheckVariant.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CaseCheckVariant.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4210525 + * @summary Locale variant should not be case folded + * @run junit CaseCheckVariant + */ + +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CaseCheckVariant { + + static final String LANG = "en"; + static final String COUNTRY = "US"; + + /** + * When a locale is created with a given variant, ensure + * that the variant is not case normalized. + */ + @ParameterizedTest + @MethodSource("variants") + public void variantCaseTest(String variant) { + Locale aLocale = new Locale(LANG, COUNTRY, variant); + String localeVariant = aLocale.getVariant(); + assertEquals(localeVariant, variant); + } + + private static Stream variants() { + return Stream.of( + "socal", + "Norcal" + ); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/CompareProviderFormats.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CompareProviderFormats.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/CompareProviderFormats.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/CompareProviderFormats.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8154797 + * @modules java.base/sun.util.locale.provider + * java.base/sun.util.resources + * jdk.localedata + * @summary Test for checking HourFormat and GmtFormat resources are retrieved from + * COMPAT and CLDR Providers. + * @run junit CompareProviderFormats +*/ + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.stream.Stream; + +import sun.util.locale.provider.LocaleProviderAdapter.Type; +import sun.util.locale.provider.LocaleProviderAdapter; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class CompareProviderFormats { + static Map expectedResourcesMap = new HashMap<>(); + static final String GMT_RESOURCE_KEY = "timezone.gmtFormat"; + static final String HMT_RESOURCE_KEY = "timezone.hourFormat"; + static final String GMT = "Gmt"; + static final String HMT = "Hmt"; + + /** + * Fill the expectedResourcesMap with the desired key / values + */ + @BeforeAll + static void populateResourcesMap() { + expectedResourcesMap.put("FR" + GMT, "UTC{0}"); + expectedResourcesMap.put("FR" + HMT, "+HH:mm;\u2212HH:mm"); + expectedResourcesMap.put("FI" + HMT, "+H.mm;-H.mm"); + expectedResourcesMap.put("FI" + GMT, "UTC{0}"); + /* For root locale, en_US, de_DE, hi_IN, ja_JP, Root locale resources + * should be returned. + */ + expectedResourcesMap.put(GMT, "GMT{0}"); // Root locale resource + expectedResourcesMap.put(HMT, "+HH:mm;-HH:mm"); // Root locale resource + } + + /** + * For each locale, ensure that the returned resources for gmt and hmt match + * the expected resources for both COMPAT and CLDR + */ + @ParameterizedTest + @MethodSource("localeProvider") + public void compareResourcesTest(Locale loc) { + compareResources(loc); + } + + private void compareResources(Locale loc) { + String mapKeyHourFormat = HMT, mapKeyGmtFormat = GMT; + ResourceBundle compatBundle, cldrBundle; + compatBundle = LocaleProviderAdapter.forJRE().getLocaleResources(loc) + .getJavaTimeFormatData(); + cldrBundle = LocaleProviderAdapter.forType(Type.CLDR) + .getLocaleResources(loc).getJavaTimeFormatData(); + + if (loc.getCountry().equals("FR") || loc.getCountry().equals("FI")) { + mapKeyHourFormat = loc.getCountry() + HMT; + mapKeyGmtFormat = loc.getCountry() + GMT; + } + + if (!(expectedResourcesMap.get(mapKeyGmtFormat) + .equals(compatBundle.getString(GMT_RESOURCE_KEY)) + && expectedResourcesMap.get(mapKeyHourFormat) + .equals(compatBundle.getString(HMT_RESOURCE_KEY)) + && expectedResourcesMap.get(mapKeyGmtFormat) + .equals(cldrBundle.getString(GMT_RESOURCE_KEY)) + && expectedResourcesMap.get(mapKeyHourFormat) + .equals(cldrBundle.getString(HMT_RESOURCE_KEY)))) { + throw new RuntimeException("Retrieved resource does not match with " + + " expected string for Locale " + compatBundle.getLocale()); + } + } + + private static Stream localeProvider() { + return Stream.of( + new Locale("hi", "IN"), + Locale.UK, new Locale("fi", "FI"), + Locale.ROOT, Locale.GERMAN, Locale.JAPANESE, + Locale.ENGLISH, Locale.FRANCE + ); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/FilteringModeTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/FilteringModeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/FilteringModeTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/FilteringModeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,67 +25,61 @@ * @test * @bug 8210443 * @summary Check values() and valueOf(String name) of Locale.FilteringMode. - * @run main FilteringModeTest + * @run junit FilteringModeTest */ import java.util.Arrays; import java.util.List; import java.util.Locale.FilteringMode; import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class FilteringModeTest { - private static boolean err = false; - private static List modeNames = List.of("AUTOSELECT_FILTERING", - "EXTENDED_FILTERING", - "IGNORE_EXTENDED_RANGES", - "MAP_EXTENDED_RANGES", - "REJECT_EXTENDED_RANGES"); - - public static void main(String[] args) throws Exception { - testValues(); - testValueOf(); - - if (err) { - throw new RuntimeException("Failed."); - } + + private static final List expectedModeNames = List.of( + "AUTOSELECT_FILTERING", + "EXTENDED_FILTERING", + "IGNORE_EXTENDED_RANGES", + "MAP_EXTENDED_RANGES", + "REJECT_EXTENDED_RANGES" + ); + + // Ensure valueOf() exceptions are thrown + @Test + public void valueOfExceptionsTest() { + assertThrows(IllegalArgumentException.class, + () -> FilteringMode.valueOf("").name()); + assertThrows(NullPointerException.class, + () -> FilteringMode.valueOf(null).name()); } - private static void testValueOf() { - try { - FilteringMode.valueOf("").name(); - err = true; - System.err.println("IAE should be thrown for valueOf(\"\")."); - } catch (IllegalArgumentException ex) { - } - - try { - FilteringMode.valueOf(null).name(); - err = true; - System.err.println("NPE should be thrown for valueOf(null)."); - } catch (NullPointerException ex) { - } - - modeNames.forEach((expectedName) -> { - String name = FilteringMode.valueOf(expectedName).name(); - if (!expectedName.equals(name)) { - err = true; - System.err.println("FilteringMode.valueOf(" + expectedName - + ") returned unexpected value. Expected: " - + expectedName + ", got: " + name); - } - }); + // Ensure valueOf() returns expected results + @ParameterizedTest + @MethodSource("modes") + public void valueOfTest(String expectedName) { + String name = FilteringMode.valueOf(expectedName).name(); + assertEquals(expectedName, name); } - private static void testValues() { + private static Stream modes() { + return expectedModeNames.stream(); + } + + // Ensure values() returns expected results + @Test + public void valuesTest() { FilteringMode[] modeArray = FilteringMode.values(); - List modeNames2 = Arrays.stream(modeArray) + List actualNames = Arrays.stream(modeArray) .map(mode -> mode.name()) .collect(Collectors.toList()); - - if (!modeNames.equals(modeNames2)) { - err = true; - System.err.println("FilteringMode.values() returned unexpected value. Expected:" - + modeNames + " Got:" + modeNames2); - } + assertEquals(expectedModeNames, actualNames); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/GetAdapterPreference.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetAdapterPreference.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/GetAdapterPreference.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetAdapterPreference.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8004240 + * @summary Verify that getAdapterPreference returns an unmodifiable list. + * @modules java.base/sun.util.locale.provider + * @compile -XDignore.symbol.file GetAdapterPreference.java + * @run junit GetAdapterPreference + */ + +import java.util.List; +import sun.util.locale.provider.LocaleProviderAdapter; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class GetAdapterPreference { + + /** + * Test that the list returned from getAdapterPreference() + * cannot be modified. + */ + @Test + public void immutableTest() { + List types = LocaleProviderAdapter.getAdapterPreference(); + assertThrows(UnsupportedOperationException.class, () -> types.set(0, null), + "Trying to modify list returned from LocaleProviderAdapter.getAdapterPreference() did not throw UOE"); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/GetInstanceCheck.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetInstanceCheck.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/GetInstanceCheck.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/GetInstanceCheck.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6312358 + * @summary Verify that an NPE is thrown by invoking Locale.getInstance() with + * any argument being null. + * @modules java.base/java.util:open + * @run junit GetInstanceCheck + */ + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; + +public class GetInstanceCheck { + + static Method getInstanceMethod; + static final String NAME = "getInstance"; + + /** + * Initialize the non-public Locale.getInstance() method. + */ + @BeforeAll + static void initializeMethod() { + try { + // Locale.getInstance is not directly accessible. + getInstanceMethod = Locale.class.getDeclaredMethod( + NAME, String.class, String.class, String.class + ); + getInstanceMethod.setAccessible(true); + } catch (java.lang.NoSuchMethodException exc) { + // The test should fail if we can not test the desired method + fail(String.format("Tried to get the method '%s' which was not found," + + " further testing is not possible, failing test", NAME)); + } + } + + /** + * Exists as sanity check that Locale.getInstance() will not throw + * an NPE if no arguments are null. + */ + @ParameterizedTest + @MethodSource("passingArguments") + public void noNPETest(String language, String country, String variant) + throws IllegalAccessException { + try { + getInstanceMethod.invoke(null, language, country, variant); + } catch (InvocationTargetException exc) { + // Determine underlying exception + Throwable cause = exc.getCause(); + if (exc.getCause() instanceof NullPointerException) { + fail(String.format("%s should not be thrown when no args are null", cause)); + } else { + fail(String.format("%s unexpectedly thrown, when no exception should be thrown", cause)); + } + } + } + + /** + * Make sure the Locale.getInstance() method throws an NPE + * if any given argument is null. + */ + @ParameterizedTest + @MethodSource("failingArguments") + public void throwNPETest(String language, String country, String variant) + throws IllegalAccessException { + try { + getInstanceMethod.invoke(null, language, country, variant); + fail("Should NPE with any argument set to null"); + } catch (InvocationTargetException exc) { + // Determine underlying exception + Throwable cause = exc.getCause(); + if (cause instanceof NullPointerException) { + System.out.println("NPE successfully thrown"); + } else { + fail(cause + " is thrown, when NPE should have been thrown"); + } + } + } + + private static Stream passingArguments() { + return Stream.of( + Arguments.of("null", "GB", ""), + Arguments.of("en", "null", ""), + Arguments.of("en", "GB", "null") + ); + } + + private static Stream failingArguments() { + return Stream.of( + Arguments.of(null, "GB", ""), + Arguments.of("en", null, ""), + Arguments.of("en", "GB", null) + ); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 4518797 + * @summary Make sure that hashCode() and read/writeObject() are thread-safe. + * @run main HashCodeShouldBeThreadSafe 10 + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Locale; + +// Usage: java HashCodeShouldBeThreadSafe [duration] +public class HashCodeShouldBeThreadSafe { + static volatile boolean runrun = true; + static volatile String message = null; + + public static void main(String[] args) { + int duration = 180; + if (args.length == 1) { + duration = Math.max(5, Integer.parseInt(args[0])); + } + final Locale loc = new Locale("ja", "US"); + final int hashcode = loc.hashCode(); + + System.out.println("correct hash code: " + hashcode); + Thread t1 = new Thread(new Runnable() { + public void run() { + while (runrun) { + int hc = loc.hashCode(); + if (hc != hashcode) { + runrun = false; + message = "t1: wrong hashcode: " + hc; + } + } + } + }); + + Thread t2 = new Thread(new Runnable() { + public void run() { + // Repeat serialization and deserialization. And get the + // hash code from a deserialized Locale object. + while (runrun) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(loc); + byte[] b = baos.toByteArray(); + oos.close(); + ByteArrayInputStream bais = new ByteArrayInputStream(b); + ObjectInputStream ois = new ObjectInputStream(bais); + Locale loc2 = (Locale) ois.readObject(); + int hc = loc2.hashCode(); + if (hc != hashcode) { + runrun = false; + message = "t2: wrong hashcode: " + hc; + } + } catch (IOException ioe) { + runrun = false; + throw new RuntimeException("t2: can't perform test", ioe); + } catch (ClassNotFoundException cnfe) { + runrun = false; + throw new RuntimeException("t2: can't perform test", cnfe); + } + } + } + }); + + t1.start(); + t2.start(); + try { + for (int i = 0; runrun && i < duration; i++) { + Thread.sleep(1000); + } + runrun = false; + t1.join(); + t2.join(); + } catch (InterruptedException e) { + } + if (message != null) { + throw new RuntimeException(message); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/HashCodeTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/HashCodeTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/HashCodeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,28 +20,35 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 4944561 * @summary Test hashCode() to have less than 10% of hash code conflicts. * @modules jdk.localedata + * @run junit HashCodeTest */ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; + public class HashCodeTest { - public static void main(String[] args) { + // Ensure Locale.hashCode() has less than 10% conflicts + @Test + public void hashConflictsTest() { Locale[] locales = Locale.getAvailableLocales(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; Map map = new HashMap<>(locales.length); int conflicts = 0; - for (int i = 0; i < locales.length; i++) { - Locale loc = locales[i]; + for (Locale loc : locales) { int hc = loc.hashCode(); min = Math.min(hc, min); max = Math.max(hc, max); @@ -55,9 +62,7 @@ } System.out.println(locales.length + " locales: conflicts=" + conflicts + ", min=" + min + ", max=" + max + ", diff=" + (max - min)); - if (conflicts >= (locales.length / 10)) { - throw new RuntimeException("too many conflicts: " + conflicts - + " per " + locales.length + " locales"); - } + assertFalse(conflicts >= (locales.length / 10), + String.format("%s conflicts per %s locales", conflicts, locales.length)); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -25,9 +25,9 @@ * @test * @bug 8025703 8040211 8191404 8203872 8222980 8225435 8241082 8242010 8247432 * 8258795 8267038 8287180 8302512 8304761 8306031 8308021 8313702 8318322 - * 8327631 8332424 8334418 + * 8327631 8332424 8334418 8344589 * @summary Checks the IANA language subtag registry data update - * (LSR Revision: 2024-06-14) with Locale and Locale.LanguageRange + * (LSR Revision: 2024-11-19) with Locale and Locale.LanguageRange * class methods. * @run main LanguageSubtagRegistryTest */ diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4184873 + * @summary test that locale invariants are preserved across serialization. + * @run junit LegacyCodesClassInvariant + */ + +/* + * This file is available under and governed by the GNU General Public + * License version 2 only, as published by the Free Software Foundation. + * However, the following notice accompanied the original version of this + * file and, per its terms, should not be removed: + * + * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved + * + * Portions copyright (c) 2007 Sun Microsystems, Inc. + * All Rights Reserved. + * + * The original version of this source code and documentation + * is copyrighted and owned by Taligent, Inc., a wholly-owned + * subsidiary of IBM. These materials are provided under terms + * of a License Agreement between Taligent and Sun. This technology + * is protected by multiple US and International patents. + * + * This notice and attribution to Taligent may not be removed. + * Taligent is a registered trademark of Taligent, Inc. + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for NON-COMMERCIAL purposes and without + * fee is hereby granted provided that this copyright notice + * appears in all copies. Please refer to the file "copyright.html" + * for further important copyright and licensing information. + * + * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF + * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR + * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. + */ + +import java.io.File; +import java.io.FileInputStream; +import java.io.ObjectInputStream; +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * A Locale can never contain the following language codes: he, yi or id. + */ +public class LegacyCodesClassInvariant { + @Test + public void testIt() throws Exception { + verify("he"); + verify("yi"); + verify("id"); + } + + private void verify(String lang) { + try { + ObjectInputStream in = getStream(lang); + if (in != null) { + final Locale loc = (Locale)in.readObject(); + final Locale expected = new Locale(lang, "XX"); + assertEquals(expected, loc, + "Locale didn't maintain invariants for: "+lang); + in.close(); + } + } catch (Exception e) { + fail(e.toString()); + } + } + + private ObjectInputStream getStream(String lang) { + try { + final File f = new File(System.getProperty("test.src", "."), "LegacyCodesClassInvariant_"+lang); + return new ObjectInputStream(new FileInputStream(f)); + } catch (Exception e) { + fail(e.toString()); + return null; + } + } +} Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LegacyCodesClassInvariant_he and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_he differ Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LegacyCodesClassInvariant_id and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_id differ Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LegacyCodesClassInvariant_yi and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LegacyCodesClassInvariant_yi differ diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleConstructors.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleConstructors.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleConstructors.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleConstructors.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4316602 + * @author joconner + * @summary Verify all Locale constructors and of() methods + * @run junit LocaleConstructors + */ + +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * This class tests to ensure that the language, language/country, and + * language/country/variant Locale constructors + of() method are all allowed. + */ +public class LocaleConstructors { + + static final String LANG = "en"; + static final String COUNTRY = "US"; + static final String VAR = "socal"; + + // Test Locale constructor and .of() allow (language) argument(s) + @Test + public void langTest() { + Locale otherLocale = new Locale(LANG); + assertEquals(otherLocale.toString(), LANG); + } + + // Test Locale constructor and .of() allow (language, constructor) argument(s) + @Test + public void langCountryTest() { + Locale otherLocale = new Locale(LANG, COUNTRY); + assertEquals(otherLocale.toString(), String.format("%s_%s", + LANG, COUNTRY)); + } + + // Test Locale constructor and .of() allow + // (language, constructor, variant) argument(s) + @Test + public void langCountryVariantTest() { + Locale otherLocale = new Locale(LANG, COUNTRY, VAR); + assertEquals(otherLocale.toString(), String.format("%s_%s_%s", + LANG, COUNTRY, VAR)); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleEnhanceTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleEnhanceTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleEnhanceTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleEnhanceTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,24 +41,20 @@ import java.util.Locale.Builder; import java.util.Set; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @test * @bug 6875847 6992272 7002320 7015500 7023613 7032820 7033504 7004603 * 7044019 8008577 8176853 8255086 8263202 * @summary test API changes to Locale - * @library /java/text/testlib * @modules jdk.localedata * @compile LocaleEnhanceTest.java - * @run main/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest + * @run junit/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest */ -public class LocaleEnhanceTest extends IntlTest { - - public static void main(String[] args) throws Exception { - List argList = new ArrayList(); - argList.addAll(Arrays.asList(args)); - argList.add("-nothrow"); - new LocaleEnhanceTest().run(argList.toArray(new String[argList.size()])); - } +public class LocaleEnhanceTest { public LocaleEnhanceTest() { } @@ -83,6 +79,7 @@ * Ensure that Builder builds locales that have the expected * tag and java6 ID. Note the odd cases for the ID. */ + @Test public void testCreateLocaleCanonicalValid() { String[] valids = { "en-Latn-US-NewYork", "en_US_NewYork_#Latn", @@ -131,7 +128,7 @@ assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -146,6 +143,7 @@ * Note that 'New' and 'York' are invalid BCP47 variant subtags * because they are too short. */ + @Test public void testCreateLocaleMultipleVariants() { String[] valids = { @@ -188,7 +186,7 @@ assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -197,6 +195,7 @@ * Ensure that all these invalid formats are not recognized by * forLanguageTag. */ + @Test public void testCreateLocaleCanonicalInvalidSeparator() { String[] invalids = { // trailing separator @@ -240,6 +239,7 @@ * Ensure that all current locale ids parse. Use DateFormat as a proxy * for all current locale ids. */ + @Test public void testCurrentLocales() { Locale[] locales = java.text.DateFormat.getAvailableLocales(); Builder builder = new Builder(); @@ -266,6 +266,7 @@ /** * Ensure that all icu locale ids parse. */ + @Test public void testIcuLocales() throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader( @@ -282,6 +283,7 @@ /// Compatibility tests /// + @Test public void testConstructor() { // all the old weirdness still holds, no new weirdness String[][] tests = { @@ -320,6 +322,7 @@ /// Locale API tests. /// + @Test public void testGetScript() { // forLanguageTag normalizes case Locale locale = Locale.forLanguageTag("und-latn"); @@ -334,6 +337,7 @@ assertEquals("script is empty string", "", locale.getScript()); } + @Test public void testGetExtension() { // forLanguageTag does NOT normalize to hyphen Locale locale = Locale.forLanguageTag("und-a-some_ex-tension"); @@ -354,6 +358,7 @@ assertEquals("x", "y-z-blork", locale.getExtension('x')); } + @Test public void testGetExtensionKeys() { Locale locale = Locale.forLanguageTag("und-a-xx-yy-b-zz-ww"); Set result = locale.getExtensionKeys(); @@ -363,7 +368,7 @@ // result is not mutable try { result.add('x'); - errln("expected exception on add to extension key set"); + fail("expected exception on add to extension key set"); } catch (UnsupportedOperationException e) { // ok @@ -374,6 +379,7 @@ assertTrue("empty result", locale.getExtensionKeys().isEmpty()); } + @Test public void testGetUnicodeLocaleAttributes() { Locale locale = Locale.forLanguageTag("en-US-u-abc-def"); Set attributes = locale.getUnicodeLocaleAttributes(); @@ -386,6 +392,7 @@ assertTrue("empty attributes", attributes.isEmpty()); } + @Test public void testGetUnicodeLocaleType() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); assertEquals("collation", "japanese", locale.getUnicodeLocaleType("co")); @@ -413,6 +420,7 @@ new ExpectNPE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType(null); }}; } + @Test public void testGetUnicodeLocaleKeys() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); Set result = locale.getUnicodeLocaleKeys(); @@ -422,13 +430,14 @@ // result is not modifiable try { result.add("frobozz"); - errln("expected exception when add to locale key set"); + fail("expected exception when add to locale key set"); } catch (UnsupportedOperationException e) { // ok } } + @Test public void testPrivateUseExtension() { Locale locale = Locale.forLanguageTag("x-y-x-blork-"); assertEquals("blork", "y-x-blork", locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); @@ -437,6 +446,7 @@ assertEquals("no privateuse", null, locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); } + @Test public void testToLanguageTag() { // lots of normalization to test here // test locales created using the constructor @@ -502,6 +512,7 @@ } + @Test public void testForLanguageTag() { // forLanguageTag implements the 'Language-Tag' production of // BCP47, so it handles private use and legacy language tags, @@ -589,7 +600,7 @@ assertEquals(msg, test[2], locale.toLanguageTag()); } catch (IllegalArgumentException e) { - errln(msg + " caught exception: " + e); + fail(msg + " caught exception: " + e); } } @@ -607,6 +618,7 @@ assertEquals("Duplicated Unicode locake key followed by an extension", "1234", locale.getExtension('c')); } + @Test public void testGetDisplayScript() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -624,6 +636,7 @@ Locale.setDefault(oldLocale); } + @Test public void testGetDisplayScriptWithLocale() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -635,6 +648,7 @@ assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript(Locale.GERMANY)); } + @Test public void testGetDisplayName() { final Locale[] testLocales = { Locale.ROOT, @@ -688,6 +702,7 @@ /// Builder tests /// + @Test public void testBuilderSetLocale() { Builder builder = new Builder(); Builder lenientBuilder = new Builder(); @@ -730,6 +745,7 @@ }; } + @Test public void testBuilderSetLanguageTag() { String source = "eN-LaTn-Us-NewYork-A-Xx-B-Yy-X-1-2-3"; String target = "en-Latn-US-NewYork-a-xx-b-yy-x-1-2-3"; @@ -747,6 +763,7 @@ new BuilderILE() { public void call() { b.setLanguageTag("und-u-nu-thai-NU-chinese-xx-1234"); }}; } + @Test public void testBuilderSetLanguage() { // language is normalized to lower case String source = "eN"; @@ -792,6 +809,7 @@ assertEquals("eng", "eng", result); } + @Test public void testBuilderSetScript() { // script is normalized to title case String source = "lAtN"; @@ -828,6 +846,7 @@ assertEquals("4alpha", "Wxyz", builder.setScript("wxyz").build().getScript()); } + @Test public void testBuilderSetRegion() { // region is normalized to upper case String source = "uS"; @@ -865,6 +884,7 @@ assertEquals("3digit", "000", builder.setRegion("000").build().getCountry()); } + @Test public void testBuilderSetVariant() { // Variant case is not normalized in lenient variant mode String source = "NewYork"; @@ -917,6 +937,7 @@ new BuilderILE("abcde-fg") { public void call() { b.setVariant(arg); }}; } + @Test public void testBuilderSetExtension() { // upper case characters are normalized to lower case final char sourceKey = 'a'; @@ -1007,6 +1028,7 @@ assertEquals("duplicate keys", "und-u-nu-thai-xx-1234", result); } + @Test public void testBuilderAddUnicodeLocaleAttribute() { Builder builder = new Builder(); Locale locale = builder @@ -1038,6 +1060,7 @@ new BuilderILE("invalid attribute") { public void call() { b.addUnicodeLocaleAttribute("ca"); }}; } + @Test public void testBuildersetUnicodeLocaleKeyword() { // Note: most behavior is tested in testBuilderSetExtension Builder builder = new Builder(); @@ -1081,6 +1104,7 @@ new BuilderILE("ab", "abcdefghi") { public void call() { b.setUnicodeLocaleKeyword("ab", arg); }}; } + @Test public void testBuilderPrivateUseExtension() { // normalizes hyphens to underscore, case to lower String source = "c-B-a"; @@ -1096,6 +1120,7 @@ new BuilderILE("a--b") { public void call() { b.setExtension(Locale.PRIVATE_USE_EXTENSION, arg); }}; } + @Test public void testBuilderClear() { String monster = "en-latn-US-NewYork-a-bb-cc-u-co-japanese-x-z-y-x-x"; Builder builder = new Builder(); @@ -1108,14 +1133,17 @@ assertEquals("clear", "und", result); } + @Test public void testBuilderRemoveUnicodeAttribute() { // tested in testBuilderAddUnicodeAttribute } + @Test public void testBuilderBuild() { // tested in other test methods } + @Test public void testSerialize() { final Locale[] testLocales = { Locale.ROOT, @@ -1161,11 +1189,12 @@ assertEquals("roundtrip " + locale, locale, o); } catch (Exception e) { - errln(locale + " encountered exception:" + e.getLocalizedMessage()); + fail(locale + " encountered exception:" + e.getLocalizedMessage()); } } } + @Test public void testDeserialize6() { final String TESTFILEPREFIX = "java6locale_"; @@ -1184,10 +1213,10 @@ } if (dataDir == null) { - errln("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); + fail("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); return; } else if (!dataDir.isDirectory()) { - errln("'dataDir' is not a directory. dataDir: "+dataDir.toString()); + fail("'dataDir' is not a directory. dataDir: "+dataDir.toString()); return; } @@ -1219,11 +1248,12 @@ Object o = ois.readObject(); assertEquals("Deserialize Java 6 Locale " + locale, o, locale); } catch (Exception e) { - errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); + fail("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); } } } + @Test public void testBug7002320() { // forLanguageTag() and Builder.setLanguageTag(String) // should add a location extension for following two cases. @@ -1267,6 +1297,7 @@ } } + @Test public void testBug7023613() { String[][] testdata = { {"en-Latn", "en__#Latn"}, @@ -1286,6 +1317,7 @@ /* * 7033504: (lc) incompatible behavior change for ja_JP_JP and th_TH_TH locales */ + @Test public void testBug7033504() { checkCalendar(new Locale("ja", "JP", "jp"), "java.util.GregorianCalendar"); checkCalendar(new Locale("ja", "jp", "jp"), "java.util.GregorianCalendar"); @@ -1318,13 +1350,13 @@ private void assertTrue(String msg, boolean v) { if (!v) { - errln(msg + ": expected true"); + fail(msg + ": expected true"); } } private void assertFalse(String msg, boolean v) { if (v) { - errln(msg + ": expected false"); + fail(msg + ": expected false"); } } @@ -1336,7 +1368,7 @@ if (v != null) { v = "'" + v + "'"; } - errln(msg + ": expected " + e + " but got " + v); + fail(msg + ": expected " + e + " but got " + v); } } @@ -1345,19 +1377,19 @@ if (e != null) { e = "'" + e + "'"; } - errln(msg + ": expected not equal " + e); + fail(msg + ": expected not equal " + e); } } private void assertNull(String msg, Object o) { if (o != null) { - errln(msg + ": expected null but got '" + o + "'"); + fail(msg + ": expected null but got '" + o + "'"); } } private void assertNotNull(String msg, Object o) { if (o == null) { - errln(msg + ": expected non null"); + fail(msg + ": expected non null"); } } @@ -1383,7 +1415,7 @@ if (failMsg != null) { String msg = message(); msg = msg == null ? "" : msg + " "; - errln(msg + failMsg); + fail(msg + failMsg); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleMatchingTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleMatchingTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleMatchingTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleMatchingTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,476 @@ +/* + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 7069824 8042360 8032842 8175539 8210443 8242010 + * @summary Verify implementation for Locale matching. + * @run testng/othervm LocaleMatchingTest + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Locale.FilteringMode; +import java.util.Locale.LanguageRange; +import java.util.Map; + +import static java.util.Locale.FilteringMode.*; +import static java.util.Locale.LanguageRange.*; +import static org.testng.Assert.*; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class LocaleMatchingTest { + + @DataProvider(name = "LRConstructorData") + Object[][] LRConstructorData() { + return new Object[][] { + // Range, Weight + {"elvish", MAX_WEIGHT}, + {"de-DE", MAX_WEIGHT}, + {"de-Latn-DE-1996", MAX_WEIGHT}, + {"zh-Hant-CN-x-private1-private2", MAX_WEIGHT}, + {"ar", 0.8}, + {"en-US", 0.5}, + {"sr-Latn-BA", 0}, + {"ja", 1}, + }; + } + + @DataProvider(name = "LRConstructorNPEData") + Object[][] LRConstructorNPEData() { + return new Object[][] { + // Range, Weight + {null, MAX_WEIGHT}, + {null, 0.8}, + }; + } + + @DataProvider(name = "LRConstructorIAEData") + Object[][] LRConstructorIAEData() { + return new Object[][] { + // Range, Weight + {"ja", -0.8}, + {"Elvish", 3.0}, + {"-ja", MAX_WEIGHT}, + {"ja--JP", MAX_WEIGHT}, + {"en-US-", MAX_WEIGHT}, + {"a4r", MAX_WEIGHT}, + {"ar*", MAX_WEIGHT}, + {"ar-*EG", MAX_WEIGHT}, + {"abcdefghijklmn", MAX_WEIGHT}, + {"ja-J=", MAX_WEIGHT}, + {"ja-opqrstuvwxyz", MAX_WEIGHT}, + {"zh_CN", MAX_WEIGHT}, + {"1996-de-Latn", MAX_WEIGHT}, + // Testcase for 8042360 + {"en-Latn-1234567890", MAX_WEIGHT}, + }; + } + + @DataProvider(name = "LRParseData") + Object[][] LRParseData() { + return new Object[][] { + // Ranges, Expected result + {"Accept-Language: fr-FX, de-DE;q=0.5, fr-tp-x-FOO;q=0.1, " + + "en-X-tp;q=0.6, en-FR;q=0.7, de-de;q=0.8, iw;q=0.4, " + + "he;q=0.4, de-de;q=0.5, ja, in-tpp, in-tp;q=0.2", + List.of(new LanguageRange("fr-fx", 1.0), + new LanguageRange("fr-fr", 1.0), + new LanguageRange("ja", 1.0), + new LanguageRange("in-tpp", 1.0), + new LanguageRange("id-tpp", 1.0), + new LanguageRange("en-fr", 0.7), + new LanguageRange("en-fx", 0.7), + new LanguageRange("en-x-tp", 0.6), + new LanguageRange("de-de", 0.5), + new LanguageRange("de-dd", 0.5), + new LanguageRange("iw", 0.4), + new LanguageRange("he", 0.4), + new LanguageRange("in-tp", 0.2), + new LanguageRange("id-tl", 0.2), + new LanguageRange("id-tp", 0.2), + new LanguageRange("in-tl", 0.2), + new LanguageRange("fr-tp-x-foo", 0.1), + new LanguageRange("fr-tl-x-foo", 0.1))}, + {"Accept-Language: hak-CN;q=0.8, no-bok-NO;q=0.9, no-nyn, cmn-CN;q=0.1", + List.of(new LanguageRange("no-nyn", 1.0), + new LanguageRange("nn", 1.0), + new LanguageRange("no-bok-no", 0.9), + new LanguageRange("nb-no", 0.9), + new LanguageRange("hak-CN", 0.8), + new LanguageRange("zh-hakka-CN", 0.8), + new LanguageRange("i-hak-CN", 0.8), + new LanguageRange("zh-hak-CN", 0.8), + new LanguageRange("cmn-CN", 0.1), + new LanguageRange("zh-guoyu-CN", 0.1), + new LanguageRange("zh-cmn-CN", 0.1))}, + {"Accept-Language: rki;q=0.4, no-bok-NO;q=0.9, ccq;q=0.5", + List.of(new LanguageRange("no-bok-no", 0.9), + new LanguageRange("nb-no", 0.9), + new LanguageRange("rki", 0.4), + new LanguageRange("ybd", 0.4), + new LanguageRange("ccq", 0.4))}, + }; + } + + @DataProvider(name = "LRParseIAEData") + Object[][] LRParseIAEData() { + return new Object[][] { + // Ranges + {""}, + {"ja;q=3"}, + }; + } + + @DataProvider(name = "LRMapEquivalentsData") + Object[][] LRMapEquivalentsData() { + return new Object[][] { + // Ranges, Map, Expected result + {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), + new HashMap<>(), + LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4")}, + {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), + null, + LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4")}, + {LanguageRange.parse("zh, zh-TW;q=0.8, ar;q=0.9, EN, zh-HK, ja-JP;q=0.2, es;q=0.4"), + new LinkedHashMap>() { + { + put("ja", List.of("ja", "ja-Hira")); + put("zh", List.of("zh-Hans", "zh-Hans-CN", "zh-CN")); + put("zh-TW", List.of("zh-TW", "zh-Hant")); + put("es", null); + put("en", List.of()); + put("zh-HK", List.of("de")); + } + }, + List.of(new LanguageRange("zh-hans", 1.0), + new LanguageRange("zh-hans-cn", 1.0), + new LanguageRange("zh-cn", 1.0), + new LanguageRange("de", 1.0), + new LanguageRange("ar", 0.9), + new LanguageRange("zh-tw", 0.8), + new LanguageRange("zh-hant", 0.8), + new LanguageRange("ja-jp", 0.2), + new LanguageRange("ja-hira-jp", 0.2))}, + }; + } + + @DataProvider(name = "LFilterData") + Object[][] LFilterData() { + return new Object[][] { + // Range, LanguageTags, FilteringMode, Expected locales + {"ja-JP, fr-FR", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", + EXTENDED_FILTERING, "ja-JP-hepburn, ja-Latn-JP"}, + {"ja-*-JP, fr-FR", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", + EXTENDED_FILTERING, "ja-JP-hepburn, ja-Latn-JP"}, + {"ja-*-JP, fr-FR, de-de;q=0.2", "de-DE, en, ja-JP-hepburn, de-de, fr, he, ja-Latn-JP", + AUTOSELECT_FILTERING, "ja-JP-hepburn, ja-Latn-JP, de-DE"}, + {"ja-JP, fr-FR, de-de;q=0.2", "de-DE, en, ja-JP-hepburn, de-de, fr, he, ja-Latn-JP", + AUTOSELECT_FILTERING, "ja-JP-hepburn, de-DE"}, + {"en;q=0.2, ja-*-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", + IGNORE_EXTENDED_RANGES, "en"}, + {"en;q=0.2, ja-*-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", + MAP_EXTENDED_RANGES, "ja-JP-hepburn, en"}, + {"en;q=0.2, ja-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", + REJECT_EXTENDED_RANGES, "ja-JP-hepburn, en"}, + {"en;q=0.2, ja-*-JP, fr-JP", "", REJECT_EXTENDED_RANGES, ""}, + }; + } + + @DataProvider(name = "LFilterNPEData") + Object[][] LFilterNPEData() { + return new Object[][] { + // Range, LanguageTags, FilteringMode + {"en;q=0.2, ja-*-JP, fr-JP", null, REJECT_EXTENDED_RANGES}, + {null, "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP", REJECT_EXTENDED_RANGES}, + }; + } + + @DataProvider(name = "LFilterTagsData") + Object[][] LFilterTagsData() { + return new Object[][] { + // Range, LanguageTags, FilteringMode, Expected language tags + {"en;q=0.2, *;q=0.6, ja", "de-DE, en, ja-JP-hepburn, fr-JP, he", + null, "de-DE, en, ja-JP-hepburn, fr-JP, he"}, + {"en;q=0.2, ja-JP, fr-JP", "de-DE, en, ja-JP-hepburn, fr, he", + null, "ja-JP-hepburn, en"}, + {"en;q=0.2, ja-JP, fr-JP, iw", "de-DE, he, en, ja-JP-hepburn, fr, he-IL", + null, "ja-JP-hepburn, he, he-IL, en"}, + {"en;q=0.2, ja-JP, fr-JP, he", "de-DE, en, ja-JP-hepburn, fr, iw-IL", + null, "ja-JP-hepburn, iw-IL, en"}, + {"de-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " + + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", + MAP_EXTENDED_RANGES, "de-DE, de-DE-x-goethe"}, + {"de-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " + + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", + EXTENDED_FILTERING, + "de-DE, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " + + "de-Latn-DE-1996, de-Deva-DE"}, + {"de-*-DE", "de-DE, de-de, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " + + "de-Latn-DE-1996, de-Deva-DE, de, de-x-DE, de-Deva", + EXTENDED_FILTERING, + "de-DE, de-Latn-DE, de-Latf-DE, de-DE-x-goethe, " + + "de-Latn-DE-1996, de-Deva-DE"}, + }; + } + + @DataProvider(name = "LLookupData") + Object[][] LLookupData() { + return new Object[][] { + // Range, LanguageTags, Expected locale + {"en;q=0.2, *-JP;q=0.6, iw", "de-DE, en, ja-JP-hepburn, fr-JP, he", "he"}, + {"en;q=0.2, *-JP;q=0.6, iw", "de-DE, he-IL, en, iw", "he"}, + {"en;q=0.2, ja-*-JP-x-foo;q=0.6, iw", "de-DE, fr, en, ja-Latn-JP", "ja-Latn-JP"}, + }; + } + + @DataProvider(name = "LLookupTagData") + Object[][] LLookupTagData() { + return new Object[][] { + // Range, LanguageTags, Expected language tag + {"en, *", "es, de, ja-JP", null}, + {"en;q=0.2, *-JP", "de-DE, en, ja-JP-hepburn, fr-JP, en-JP", "fr-JP"}, + {"en;q=0.2, ar-MO, iw", "de-DE, he, fr-JP", "he"}, + {"en;q=0.2, ar-MO, he", "de-DE, iw, fr-JP", "iw"}, + {"de-DE-1996;q=0.8, en;q=0.2, iw;q=0.9, zh-Hans-CN;q=0.7", "de-DE, zh-CN, he, iw, fr-JP", "iw"}, + {"de-DE-1996;q=0.8, en;q=0.2, he;q=0.9, zh-Hans-CN;q=0.7", "de-DE, zh-CN, he, iw, fr-JP", "he"}, + }; + } + + @Test + public void testLRConstants() { + assertEquals(MIN_WEIGHT, 0.0, " MIN_WEIGHT should be 0.0 but got " + + MIN_WEIGHT); + assertEquals(MAX_WEIGHT, 1.0, " MAX_WEIGHT should be 1.0 but got " + + MAX_WEIGHT); + } + + @Test(dataProvider = "LRConstructorData") + public void testLRConstructors(String range, double weight) { + LanguageRange lr; + if (weight == MAX_WEIGHT) { + lr = new LanguageRange(range); + } else { + lr = new LanguageRange(range, weight); + } + assertEquals(lr.getRange(), range.toLowerCase(Locale.ROOT), + " LR.getRange() returned unexpected value. Expected: " + + range.toLowerCase(Locale.ROOT) + ", got: " + lr.getRange()); + assertEquals(lr.getWeight(), weight, + " LR.getWeight() returned unexpected value. Expected: " + + weight + ", got: " + lr.getWeight()); + } + + @Test(dataProvider = "LRConstructorNPEData", expectedExceptions = NullPointerException.class) + public void testLRConstructorNPE(String range, double weight) { + if (weight == MAX_WEIGHT) { + new LanguageRange(range); + } else { + new LanguageRange(range, weight); + } + } + + @Test(dataProvider = "LRConstructorIAEData", expectedExceptions = IllegalArgumentException.class) + public void testLRConstructorIAE(String range, double weight) { + if (weight == MAX_WEIGHT) { + new LanguageRange(range); + } else { + new LanguageRange(range, weight); + } + } + + @Test + public void testLREquals() { + LanguageRange lr1 = new LanguageRange("ja", 1.0); + LanguageRange lr2 = new LanguageRange("ja"); + LanguageRange lr3 = new LanguageRange("ja", 0.1); + LanguageRange lr4 = new LanguageRange("en", 1.0); + + assertEquals(lr1, lr2, " LR(ja, 1.0).equals(LR(ja)) should return true."); + assertNotEquals(lr1, lr3, " LR(ja, 1.0).equals(LR(ja, 0.1)) should return false."); + assertNotEquals(lr1, lr4, " LR(ja, 1.0).equals(LR(en, 1.0)) should return false."); + assertNotNull(lr1, " LR(ja, 1.0).equals(null) should return false."); + assertNotEquals(lr1, "", " LR(ja, 1.0).equals(\"\") should return false."); + } + + @Test(dataProvider = "LRParseData") + public void testLRParse(String ranges, List expected) { + assertEquals(LanguageRange.parse(ranges), expected, + " LR.parse(" + ranges + ") test failed."); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testLRParseNPE() { + LanguageRange.parse(null); + } + + @Test(dataProvider = "LRParseIAEData", expectedExceptions = IllegalArgumentException.class) + public void testLRParseIAE(String ranges) { + LanguageRange.parse(ranges); + } + + @Test(dataProvider = "LRMapEquivalentsData") + public void testLRMapEquivalents(List priorityList, + Map> map, List expected) { + assertEquals(LanguageRange.mapEquivalents(priorityList, map), expected, + " LR.mapEquivalents() test failed."); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testLRMapEquivalentsNPE() { + LanguageRange.mapEquivalents(null, Map.of("ja", List.of("ja", "ja-Hira"))); + } + + @Test(dataProvider = "LFilterData") + public void testLFilter(String ranges, String tags, FilteringMode mode, String expectedLocales) { + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLocales(tags); + String actualLocales = + showLocales(Locale.filter(priorityList, tagList, mode)); + assertEquals(actualLocales, expectedLocales, showErrorMessage(" L.Filter(" + mode + ")", + ranges, tags, expectedLocales, actualLocales)); + } + + @Test(dataProvider = "LFilterNPEData", expectedExceptions = NullPointerException.class) + public void testLFilterNPE(String ranges, String tags, FilteringMode mode) { + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLocales(tags); + showLocales(Locale.filter(priorityList, tagList, mode)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testLFilterIAE() { + String ranges = "en;q=0.2, ja-*-JP, fr-JP"; + String tags = "de-DE, en, ja-JP-hepburn, fr, he, ja-Latn-JP"; + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLocales(tags); + showLocales(Locale.filter(priorityList, tagList, REJECT_EXTENDED_RANGES)); + } + + @Test(dataProvider = "LFilterTagsData") + public void testLFilterTags(String ranges, String tags, FilteringMode mode, String expectedTags) { + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLanguageTags(tags); + String actualTags; + if (mode == null) { + actualTags = showLanguageTags(Locale.filterTags(priorityList, tagList)); + } else { + actualTags = showLanguageTags(Locale.filterTags(priorityList, tagList, mode)); + } + assertEquals(actualTags, expectedTags, + showErrorMessage(" L.FilterTags(" + (mode != null ? mode : "") + ")", + ranges, tags, expectedTags, actualTags)); + } + + @Test(dataProvider = "LLookupData") + public void testLLookup(String ranges, String tags, String expectedLocale) { + List priorityList = LanguageRange.parse(ranges); + List localeList = generateLocales(tags); + String actualLocale = + Locale.lookup(priorityList, localeList).toLanguageTag(); + assertEquals(actualLocale, expectedLocale, showErrorMessage(" L.Lookup()", + ranges, tags, expectedLocale, actualLocale)); + } + + @Test(dataProvider = "LLookupTagData") + public void testLLookupTag(String ranges, String tags, String expectedTag) { + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLanguageTags(tags); + String actualTag = Locale.lookupTag(priorityList, tagList); + assertEquals(actualTag, expectedTag, showErrorMessage(" L.LookupTag()", + ranges, tags, expectedTag, actualTag)); + } + + private static List generateLocales(String tags) { + if (tags == null) { + return null; + } + + List localeList = new ArrayList<>(); + if (tags.equals("")) { + return localeList; + } + String[] t = tags.split(", "); + for (String tag : t) { + localeList.add(Locale.forLanguageTag(tag)); + } + return localeList; + } + + private static List generateLanguageTags(String tags) { + List tagList = new ArrayList<>(); + String[] t = tags.split(", "); + for (String tag : t) { + tagList.add(tag); + } + return tagList; + } + + private static String showLanguageTags(List tags) { + StringBuilder sb = new StringBuilder(); + + Iterator itr = tags.iterator(); + if (itr.hasNext()) { + sb.append(itr.next()); + } + while (itr.hasNext()) { + sb.append(", "); + sb.append(itr.next()); + } + + return sb.toString().trim(); + } + + private static String showLocales(List locales) { + StringBuilder sb = new StringBuilder(); + + Iterator itr = locales.iterator(); + if (itr.hasNext()) { + sb.append(itr.next().toLanguageTag()); + } + while (itr.hasNext()) { + sb.append(", "); + sb.append(itr.next().toLanguageTag()); + } + + return sb.toString().trim(); + } + + private static String showErrorMessage(String methodName, + String priorityList, + String tags, + String expectedTags, + String actualTags) { + return "Incorrect " + methodName + " result." + + " Priority list : " + priorityList + + " Language tags : " + tags + + " Expected value : " + expectedTags + + " Actual value : " + actualTags; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleProvidersRun.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleProvidersRun.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleProvidersRun.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleProvidersRun.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * 8150432 8215913 8220227 8228465 8232871 8232860 8236495 8245241 * 8246721 8248695 8257964 8261919 * @summary tests for "java.locale.providers" system property + * @requires vm.flagless * @library /test/lib * @build LocaleProviders * providersrc.spi.src.tznp @@ -39,7 +40,6 @@ import java.util.Locale; -import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Utils; @@ -178,22 +178,18 @@ } private static void testRun(String prefList, String methodName, - String param1, String param2, String param3) throws Throwable{ - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASS_PATH) - .addToolArg("-Djava.util.logging.config.class=LocaleProviders$LogConfig") - .addToolArg("-Djava.locale.providers=" + prefList) - .addToolArg("--add-exports=java.base/sun.util.locale.provider=ALL-UNNAMED") - .addToolArg("LocaleProviders") - .addToolArg(methodName) - .addToolArg(param1) - .addToolArg(param2) - .addToolArg(param3); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + String param1, String param2, String param3) throws Throwable { + + // Build process (without VM flags) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", Utils.TEST_CLASS_PATH, + "-Djava.util.logging.config.class=LocaleProviders$LogConfig", + "-Djava.locale.providers=" + prefList, + "--add-exports=java.base/sun.util.locale.provider=ALL-UNNAMED", + "LocaleProviders", methodName, param1, param2, param3); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Unexpected exit code: " + exitCode); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 4152725 + * @summary Verify that the default locale can be specified from the + * command line. + * @run main/othervm -Duser.language=de -Duser.country=DE -Duser.variant=EURO + * LocaleShouldSetFromCLI de_DE_EURO + * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant= + * LocaleShouldSetFromCLI ja + * @run main/othervm -Duser.language=en -Duser.country=SG -Duser.variant= + * LocaleShouldSetFromCLI en_SG + * @run main/othervm -Duser.language= -Duser.country=DE -Duser.variant=EURO + * LocaleShouldSetFromCLI _DE_EURO + * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant=YOMI + * LocaleShouldSetFromCLI ja__YOMI + * @run main/othervm -Duser.language= -Duser.country= -Duser.variant=EURO + * LocaleShouldSetFromCLI __EURO + * @run main/othervm -Duser.language=de -Duser.region=DE_EURO + * LocaleShouldSetFromCLI de_DE_EURO + */ + +import java.util.Locale; + +public class LocaleShouldSetFromCLI { + + public static void main(String[] args) { + + if (args.length != 1) { + throw new RuntimeException("expected locale needs to be specified"); + } + + Locale locale = Locale.getDefault(); + + // don't use Locale.toString - it's bogus + String language = locale.getLanguage(); + String country = locale.getCountry(); + String variant = locale.getVariant(); + String localeID = null; + if (variant.length() > 0) { + localeID = language + "_" + country + "_" + variant; + } else if (country.length() > 0) { + localeID = language + "_" + country; + } else { + localeID = language; + } + + if (localeID.equals(args[0])) { + System.out.println("Correctly set from command line: " + localeID); + } else { + throw new RuntimeException("expected default locale: " + args[0] + + ", actual default locale: " + localeID); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LocaleTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LocaleTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,10 +27,9 @@ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 8170840 8255086 8263202 * @summary test Locales - * @library /java/text/testlib * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest - * @run main/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest */ /* * This file is available under and governed by the GNU General Public @@ -86,7 +85,11 @@ import java.util.Locale; import java.util.MissingResourceException; -public class LocaleTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class LocaleTest { public LocaleTest() { } @@ -191,52 +194,50 @@ { "English (United States)", "French (France)", "Croatian (Croatia)", "Greek (Greece)", "Norwegian (Norway,Nynorsk)", "Italian", "xx (YY)" }, }; - public static void main(String[] args) throws Exception { - new LocaleTest().run(args); - } - + @Test public void TestBasicGetters() { for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals(dataTable[VAR][i])) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus " + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus " + dataTable[VAR][i]); } if (!testLocale.toString().equals(dataTable[NAME][i])) { - errln(" Locale name mismatch: " + testLocale.toString() + " versus " + fail(" Locale name mismatch: " + testLocale.toString() + " versus " + dataTable[NAME][i]); } } - logln("Same thing without variant codes..."); + System.out.println("Same thing without variant codes..."); for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals("")) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); } } } + @Test public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { if (dataTable[LANG][i].equals("xx")) { @@ -244,20 +245,20 @@ } Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) { - errln(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + fail(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + " versus " + dataTable[LANG3][i]); } if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) { - errln(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + fail(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + " versus " + dataTable[CTRY3][i]); } /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) - errln(" LCID mismatch: " + testLocale.getLCID() + " versus " + fail(" LCID mismatch: " + testLocale.getLCID() + " versus " + dataTable[LCID][i]); */ } @@ -269,6 +270,7 @@ * between 1.1.5 and 1.1.6, but I included a new test for it anyway) * @bug 4052440 Stop falling back to the default locale. */ + @Test public void TestDisplayNames() { Locale saveDefault = Locale.getDefault(); Locale english = new Locale("en", "US"); @@ -277,29 +279,29 @@ Locale greek = new Locale("el", "GR"); Locale.setDefault(english); - logln("With default = en_US..."); - logln(" In default locale..."); + System.out.println("With default = en_US..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_EN, false); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, false); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, false); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, false); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, false); Locale.setDefault(french); - logln("With default = fr_FR..."); - logln(" In default locale..."); + System.out.println("With default = fr_FR..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_FR, true); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, true); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, true); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, true); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, true); Locale.setDefault(saveDefault); @@ -309,14 +311,14 @@ String language = Locale.getDefault().getLanguage(); if (defaultIsFrench && !language.equals("fr")) { - errln("Default locale should be French, but it's really " + language); + fail("Default locale should be French, but it's really " + language); } else if (!defaultIsFrench && !language.equals("en")) { - errln("Default locale should be English, but it's really " + language); + fail("Default locale should be English, but it's really " + language); } for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln(" Testing " + testLocale + "..."); + System.out.println(" Testing " + testLocale + "..."); String testLang; String testCtry; @@ -373,20 +375,21 @@ } if (!testLang.equals(expectedLang)) { - errln("Display language mismatch: " + testLang + " versus " + expectedLang); + fail("Display language mismatch: " + testLang + " versus " + expectedLang); } if (!testCtry.equals(expectedCtry)) { - errln("Display country mismatch: " + testCtry + " versus " + expectedCtry); + fail("Display country mismatch: " + testCtry + " versus " + expectedCtry); } if (!testVar.equals(expectedVar)) { - errln("Display variant mismatch: " + testVar + " versus " + expectedVar); + fail("Display variant mismatch: " + testVar + " versus " + expectedVar); } if (!testName.equals(expectedName)) { - errln("Display name mismatch: " + testName + " versus " + expectedName); + fail("Display name mismatch: " + testName + " versus " + expectedName); } } } + @Test public void TestSimpleObjectStuff() { Locale test1 = new Locale("aa", "AA"); Locale test2 = new Locale("aa", "AA"); @@ -394,19 +397,19 @@ Locale test4 = new Locale("zz", "ZZ"); if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) { - errln("Some of the test variables point to the same locale!"); + fail("Some of the test variables point to the same locale!"); } if (test3 == null) { - errln("clone() failed to produce a valid object!"); + fail("clone() failed to produce a valid object!"); } if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) { - errln("clone() or equals() failed: objects that should compare equal don't"); + fail("clone() or equals() failed: objects that should compare equal don't"); } if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) { - errln("equals() failed: objects that shouldn't compare equal do"); + fail("equals() failed: objects that shouldn't compare equal do"); } int hash1 = test1.hashCode(); @@ -414,13 +417,14 @@ int hash3 = test3.hashCode(); if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) { - errln("hashCode() failed: objects that should have the same hash code don't"); + fail("hashCode() failed: objects that should have the same hash code don't"); } } /** * @bug 4011756 4011380 */ + @Test public void TestISO3Fallback() { Locale test = new Locale("xx", "YY", ""); boolean gotException = false; @@ -432,7 +436,7 @@ gotException = true; } if (!gotException) { - errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); } gotException = false; @@ -442,13 +446,14 @@ gotException = true; } if (!gotException) { - errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); } } /** * @bug 4106155 4118587 7066203 7085757 */ + @Test public void TestGetLangsAndCountries() { // It didn't seem right to just do an exhaustive test of everything here, so I check // for the following things: @@ -463,7 +468,7 @@ "he", "id", "iu", "ug", "yi", "za"}; if (test.length != 188) { - errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length); + fail("Expected getISOLanguages() to return 188 languages; it returned " + test.length); } else { for (int i = 0; i < spotCheck1.length; i++) { int j; @@ -473,19 +478,19 @@ } } if (j == test.length || !test[j].equals(spotCheck1[i])) { - errln("Couldn't find " + spotCheck1[i] + " in language list."); + fail("Couldn't find " + spotCheck1[i] + " in language list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toLowerCase())) { - errln(test[i] + " is not all lower case."); + fail(test[i] + " is not all lower case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } @@ -494,7 +499,7 @@ if (test.length != 249) { - errln("Expected getISOCountries to return 249 countries; it returned " + test.length); + fail("Expected getISOCountries to return 249 countries; it returned " + test.length); } else { for (int i = 0; i < spotCheck2.length; i++) { int j; @@ -504,19 +509,19 @@ } } if (j == test.length || !test[j].equals(spotCheck2[i])) { - errln("Couldn't find " + spotCheck2[i] + " in country list."); + fail("Couldn't find " + spotCheck2[i] + " in country list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toUpperCase())) { - errln(test[i] + " is not all upper case."); + fail(test[i] + " is not all upper case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } } @@ -531,28 +536,29 @@ test[0] = "SUCKER!!!"; test = Locale.getISOCountries(); if (test[0].equals("SUCKER!!!")) { - errln("Changed internal country code list!"); + fail("Changed internal country code list!"); } test = Locale.getISOLanguages(); test[0] = "HAHAHAHA!!!"; test = Locale.getISOLanguages(); if (test[0].equals("HAHAHAHA!!!")) { // Fixed typo - errln("Changes internal language code list!"); + fail("Changes internal language code list!"); } } /** * @bug 4107014 */ + @Test public void TestGetAvailableLocales() { Locale[] locales = Locale.getAvailableLocales(); if (locales == null || locales.length == 0) { - errln("Locale.getAvailableLocales() returned no installed locales!"); + fail("Locale.getAvailableLocales() returned no installed locales!"); } else { - logln("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); + System.out.println("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); for (int i = 0; i < locales.length; i++) { - logln(locales[i].toString()); + System.out.println(locales[i].toString()); } } } @@ -560,11 +566,12 @@ /** * @bug 4135316 */ + @Test public void TestBug4135316() { Locale[] locales1 = Locale.getAvailableLocales(); Locale[] locales2 = Locale.getAvailableLocales(); if (locales1 == locales2) { - errln("Locale.getAvailableLocales() doesn't clone its internal storage!"); + fail("Locale.getAvailableLocales() doesn't clone its internal storage!"); } } @@ -573,27 +580,28 @@ */ /* test commented out pending API-change approval + @Test public void TestGetLanguagesForCountry() { String[] languages = Locale.getLanguagesForCountry("US"); if (!searchStringArrayFor("en", languages)) - errln("Didn't get en as a language for US"); + fail("Didn't get en as a language for US"); languages = Locale.getLanguagesForCountry("FR"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for FR"); + fail("Didn't get fr as a language for FR"); languages = Locale.getLanguagesForCountry("CH"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for CH"); + fail("Didn't get fr as a language for CH"); if (!searchStringArrayFor("it", languages)) - errln("Didn't get it as a language for CH"); + fail("Didn't get it as a language for CH"); if (!searchStringArrayFor("de", languages)) - errln("Didn't get de as a language for CH"); + fail("Didn't get de as a language for CH"); languages = Locale.getLanguagesForCountry("JP"); if (!searchStringArrayFor("ja", languages)) - errln("Didn't get ja as a language for JP"); + fail("Didn't get ja as a language for JP"); } */ @@ -606,6 +614,7 @@ /** * @bug 4110613 */ + @Test public void TestSerialization() throws ClassNotFoundException, OptionalDataException, IOException, StreamCorruptedException { ObjectOutputStream ostream; @@ -626,13 +635,14 @@ Locale test2 = (Locale) (istream.readObject()); if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) { - errln("Locale failed to deserialize correctly."); + fail("Locale failed to deserialize correctly."); } } /** * @bug 4118587 */ + @Test public void TestSimpleDisplayNames() { // This test is different from TestDisplayNames because TestDisplayNames checks // fallback behavior, combination of language and country names to form locale @@ -645,7 +655,7 @@ for (int i = 0; i < languageCodes.length; i++) { String test = (new Locale(languageCodes[i], "", "")).getDisplayLanguage(Locale.US); if (!test.equals(languageNames[i])) { - errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + fail("Got wrong display name for " + languageCodes[i] + ": Expected \"" + languageNames[i] + "\", got \"" + test + "\"."); } } @@ -654,6 +664,7 @@ /** * @bug 4118595 */ + @Test public void TestUninstalledISO3Names() { // This test checks to make sure getISO3Language and getISO3Country work right // even for locales that are not installed. @@ -663,7 +674,7 @@ for (int i = 0; i < iso2Languages.length; i++) { String test = (new Locale(iso2Languages[i], "", "")).getISO3Language(); if (!test.equals(iso3Languages[i])) { - errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + iso3Languages[i] + "\", got \"" + test + "\"."); } } @@ -674,7 +685,7 @@ for (int i = 0; i < iso2Countries.length; i++) { String test = (new Locale("", iso2Countries[i], "")).getISO3Country(); if (!test.equals(iso3Countries[i])) { - errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + iso3Countries[i] + "\", got \"" + test + "\"."); } } @@ -683,6 +694,7 @@ /** * @bug 4052404 4778440 8263202 */ + @Test public void TestChangedISO639Codes() { Locale hebrewOld = new Locale("iw", "IL", ""); Locale hebrewNew = new Locale("he", "IL", ""); @@ -693,28 +705,28 @@ if ("true".equalsIgnoreCase(System.getProperty("java.locale.useOldISOCodes"))) { if (!hebrewNew.getLanguage().equals("iw")) { - errln("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + fail("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishNew.getLanguage().equals("ji")) { - errln("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + fail("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianNew.getLanguage().equals("in")) { - errln("Got back wrong language code for new Indonesian: expected \"in\", got \"" + fail("Got back wrong language code for new Indonesian: expected \"in\", got \"" + indonesianNew.getLanguage() + "\""); } } else { if (!hebrewOld.getLanguage().equals("he")) { - errln("Got back wrong language code for old Hebrew: expected \"he\", got \"" + fail("Got back wrong language code for old Hebrew: expected \"he\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishOld.getLanguage().equals("yi")) { - errln("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + fail("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianOld.getLanguage().equals("id")) { - errln("Got back wrong language code for old Indonesian: expected \"id\", got \"" + fail("Got back wrong language code for old Indonesian: expected \"id\", got \"" + indonesianNew.getLanguage() + "\""); } } @@ -738,6 +750,7 @@ * 1999-11-19 joconner * */ + @Test public void TestAtypicalLocales() { Locale[] localesToTest = { new Locale("de", "CA"), new Locale("ja", "ZA"), @@ -783,27 +796,27 @@ for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.US); - logln(name); + System.out.println(name); if (!name.equals(englishDisplayNames[i])) { - errln("Lookup in English failed: expected \"" + englishDisplayNames[i] + fail("Lookup in English failed: expected \"" + englishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(new Locale("es", "ES")); - logln(name); + System.out.println(name); if (!name.equals(spanishDisplayNames[i])) { - errln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + fail("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.FRANCE); - logln(name); + System.out.println(name); if (!name.equals(frenchDisplayNames[i])) { - errln("Lookup in French failed: expected \"" + frenchDisplayNames[i] + fail("Lookup in French failed: expected \"" + frenchDisplayNames[i] + "\", got \"" + name + "\""); } } @@ -815,6 +828,7 @@ /** * @bug 4126371 */ + @Test public void TestNullDefault() { // why on earth anyone would ever try to do this is beyond me, but we should // definitely make sure we don't let them @@ -826,10 +840,10 @@ gotException = true; } if (Locale.getDefault() == null) { - errln("Locale.getDefault() allowed us to set default to NULL!"); + fail("Locale.getDefault() allowed us to set default to NULL!"); } if (!gotException) { - errln("Trying to set default locale to NULL didn't throw exception!"); + fail("Trying to set default locale to NULL didn't throw exception!"); } } @@ -838,15 +852,16 @@ * This would be better tested by the LocaleDataTest. Will move it when I * get the LocaleDataTest working again. */ + @Test public void TestThaiCurrencyFormat() { DecimalFormat thaiCurrency = (DecimalFormat) NumberFormat.getCurrencyInstance( new Locale("th", "TH")); if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) { - errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + fail("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + thaiCurrency.getPositivePrefix() + "\""); } if (!thaiCurrency.getPositiveSuffix().equals("")) { - errln("Thai currency suffix wrong: expected \"\", got \"" + fail("Thai currency suffix wrong: expected \"\", got \"" + thaiCurrency.getPositiveSuffix() + "\""); } } @@ -864,6 +879,7 @@ * DON'T ASSUME: Any specific countries support the Euro. Instead, * iterate through all locales. */ + @Test public void TestEuroSupport() { final String EURO_VARIANT = "EURO"; final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency @@ -877,10 +893,10 @@ String neg = nf.format(-271828.182845); if (pos.indexOf(EURO_CURRENCY) >= 0 && neg.indexOf(EURO_CURRENCY) >= 0) { - logln("Ok: " + loc.toString() + System.out.println("Ok: " + loc.toString() + ": " + pos + " / " + neg); } else { - errln("Fail: " + loc.toString() + fail("Fail: " + loc.toString() + " formats without " + EURO_CURRENCY + ": " + pos + " / " + neg + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); @@ -893,6 +909,7 @@ * @bug 4139504 * toString() doesn't work with language_VARIANT. */ + @Test public void TestToString() { Object[] DATA = { new Locale("xx", "", ""), "xx", @@ -907,7 +924,7 @@ Locale loc = (Locale) DATA[i]; String fmt = (String) DATA[i + 1]; if (!loc.toString().equals(fmt)) { - errln("Fail: Locale.toString(" + fmt + ")=>" + loc); + fail("Fail: Locale.toString(" + fmt + ")=>" + loc); } } } @@ -917,6 +934,7 @@ * Currency symbol in zh is wrong. We will test this at the NumberFormat * end to test the whole pipe. */ + @Test public void Test4105828() { Locale[] LOC = {Locale.CHINESE, new Locale("zh", "CN", ""), new Locale("zh", "TW", ""), new Locale("zh", "HK", "")}; @@ -924,7 +942,7 @@ NumberFormat fmt = NumberFormat.getPercentInstance(LOC[i]); String result = fmt.format(1); if (!result.equals("100%")) { - errln("Percent for " + LOC[i] + " should be 100%, got " + result); + fail("Percent for " + LOC[i] + " should be 100%, got " + result); } } } @@ -945,6 +963,7 @@ * is that something is wrong with the font mapping subsystem, but we can't * test that here. */ + @Test public void Test4139940() { Locale mylocale = new Locale("hu", "", ""); @SuppressWarnings("deprecation") @@ -954,7 +973,7 @@ // Make sure that o circumflex (\u00F4) is NOT there, and // o double acute (\u0151) IS. if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0) { - errln("Fail: Monday in Hungarian is wrong"); + fail("Fail: Monday in Hungarian is wrong"); } } @@ -962,10 +981,11 @@ * @bug 4143951 * Russian first day of week should be Monday. Confirmed. */ + @Test public void Test4143951() { Calendar cal = Calendar.getInstance(new Locale("ru", "", "")); if (cal.getFirstDayOfWeek() != Calendar.MONDAY) { - errln("Fail: First day of week in Russia should be Monday"); + fail("Fail: First day of week in Russia should be Monday"); } } @@ -974,6 +994,7 @@ * java.util.Locale.getISO3Country() works wrong for non ISO-3166 codes. * Should throw an exception for unknown locales */ + @Test public void Test4147315() { // Try with codes that are the wrong length but happen to match text // at a valid offset in the mapping table @@ -982,7 +1003,7 @@ try { String result = locale.getISO3Country(); - errln("ERROR: getISO3Country() returns: " + result + fail("ERROR: getISO3Country() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -994,6 +1015,7 @@ * Should throw an exception for unknown locales, except they have three * letter language codes. */ + @Test public void Test4147317() { // Try a three letter language code, and check whether it is // returned as is. @@ -1001,7 +1023,7 @@ String result = locale.getISO3Language(); if (!result.equals("aaa")) { - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than returning it as is"); } @@ -1012,7 +1034,7 @@ try { result = locale.getISO3Language(); - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -1021,6 +1043,7 @@ /* * @bug 4147552 4778440 8030696 */ + @Test public void Test4147552() { Locale[] locales = {new Locale("no", "NO"), new Locale("no", "NO", "B"), new Locale("no", "NO", "NY"), new Locale("nb", "NO"), @@ -1037,11 +1060,11 @@ for (int i = 0; i < locales.length; i++) { Locale loc = locales[i]; if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) { - errln("English display-name mismatch: expected " + fail("English display-name mismatch: expected " + englishDisplayNames[i] + ", got " + loc.getDisplayName()); } if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) { - errln("Norwegian display-name mismatch: expected " + fail("Norwegian display-name mismatch: expected " + norwegianDisplayNames[i] + ", got " + loc.getDisplayName(loc)); } @@ -1051,11 +1074,12 @@ /* * @bug 8030696 */ + @Test public void Test8030696() { List av = Arrays.asList(Locale.getAvailableLocales()); if (!av.contains(new Locale("nb", "NO")) || !av.contains(new Locale("nn", "NO"))) { - errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); + fail("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LookupOnValidRangeTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LookupOnValidRangeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/LookupOnValidRangeTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/LookupOnValidRangeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8135061 + * @summary Checks that the Locale.lookup executes properly without throwing + * any exception for some specific language ranges + * @run junit LookupOnValidRangeTest + */ + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Locale.LanguageRange; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class LookupOnValidRangeTest { + + /** + * Lookup should run without throwing any exception and return null as + * the language range does not match with the language tag. + */ + @Test + public void lookupReturnNullTest() { + List ranges = LanguageRange.parse("nv"); + Collection locales = Collections.singleton(Locale.ENGLISH); + try { + Locale match = Locale.lookup(ranges, locales); + assertNull(match); + } catch (Exception ex) { + throw new RuntimeException("[Locale.lookup failed on language" + + " range: " + ranges + " and language tags " + + locales + "]", ex); + } + } + + /** + * Lookup should run without throwing any exception and return "nv" + * as the matching tag. + */ + @Test + public void lookupReturnValueTest() { + List ranges = LanguageRange.parse("i-navajo"); + Collection locales = Collections.singleton(new Locale("nv")); + try { + Locale match = Locale.lookup(ranges, locales); + assertEquals(match.toLanguageTag(), "nv"); + } catch (Exception ex) { + throw new RuntimeException("[Locale.lookup failed on language" + + " range: " + ranges + " and language tags " + + locales + "]", ex); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8035133 + * @summary Checks that the tags matching the range with quality weight q=0 + * e.g. en;q=0 must be elimited and must not be the part of output + * @run junit MatchEmptyWeightCorrectly + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MatchEmptyWeightCorrectly { + + // Ensure weights with 'q=0' work as expected during lookup + @ParameterizedTest + @MethodSource("lookupProvider") + public void lookupTest(String ranges, String tags, + String expectedLocale) { + + List priorityList = Locale.LanguageRange + .parse(ranges); + List localeList = generateLocales(tags); + Locale loc = Locale.lookup(priorityList, localeList); + String actualLocale = loc.toLanguageTag(); + assertEquals(expectedLocale, actualLocale); + } + + private static Stream lookupProvider() { + return Stream.of( + // checking Locale.lookup with de-ch;q=0 + Arguments.of("en;q=0.1, *-ch;q=0.5, de-ch;q=0", + "de-ch, en, fr-ch", "fr-CH"), + // checking Locale.lookup with *;q=0 '*' should be ignored in lookup + Arguments.of("en;q=0.1, *-ch;q=0.5, *;q=0", + "de-ch, en, fr-ch", "de-CH") + ); + } + + // Ensure weights with 'q=0' work as expected during filtering + @ParameterizedTest + @MethodSource("filterProvider") + public void filterTest(String ranges, String tags, + String expectedLocales) { + + List priorityList = Locale.LanguageRange + .parse(ranges); + List localeList = generateLocales(tags); + String actualLocales = getLocalesAsString( + Locale.filter(priorityList, localeList)); + assertEquals(expectedLocales, actualLocales); + } + + private static Stream filterProvider() { + return Stream.of( + // checking Locale.filter with fr-ch;q=0 in BASIC_FILTERING + Arguments.of("en;q=0.1, fr-ch;q=0.0, de-ch;q=0.5", + "de-ch, en, fr-ch", "de-CH, en"), + // checking Locale.filter with *;q=0 in BASIC_FILTERING + Arguments.of("de-ch;q=0.6, *;q=0", "de-ch, fr-ch", ""), + // checking Locale.filter with *;q=0 in BASIC_FILTERING + Arguments.of("de-ch;q=0.6, de;q=0", "de-ch", ""), + // checking Locale.filter with *;q=0.6, en;q=0 in BASIC_FILTERING + Arguments.of("*;q=0.6, en;q=0", "de-ch, hi-in, en", "de-CH, hi-IN"), + // checking Locale.filter with de-ch;q=0 in EXTENDED_FILTERING + Arguments.of("en;q=0.1, *-ch;q=0.5, de-ch;q=0", + "de-ch, en, fr-ch", "fr-CH, en"), + /* checking Locale.filter with *-ch;q=0 in EXTENDED_FILTERING which + * must make filter to return "" empty or no match + */ + Arguments.of("de-ch;q=0.5, *-ch;q=0", "de-ch, fr-ch", ""), + /* checking Locale.filter with *;q=0 in EXTENDED_FILTERING which + * must make filter to return "" empty or no match + */ + Arguments.of("*-ch;q=0.5, *;q=0", "de-ch, fr-ch", ""), + /* checking Locale.filter with *;q=0.6, *-Latn;q=0 in + * EXTENDED_FILTERING + */ + Arguments.of("*;q=0.6, *-Latn;q=0", "de-ch, hi-in, en-Latn", + "de-CH, hi-IN") + ); + } + + private static List generateLocales(String tags) { + if (tags == null) { + return null; + } + + List localeList = new ArrayList<>(); + if (tags.equals("")) { + return localeList; + } + String[] t = tags.split(", "); + for (String tag : t) { + localeList.add(Locale.forLanguageTag(tag)); + } + return localeList; + } + + private static String getLocalesAsString(List locales) { + StringBuilder sb = new StringBuilder(); + + Iterator itr = locales.iterator(); + if (itr.hasNext()) { + sb.append(itr.next().toLanguageTag()); + } + while (itr.hasNext()) { + sb.append(", "); + sb.append(itr.next().toLanguageTag()); + } + + return sb.toString().trim(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6989440 + * @summary Verify ConcurrentModificationException is not thrown with multiple + * thread accesses. + * @modules java.base/sun.util.locale.provider + * @compile -XDignore.symbol.file=true ProviderPoolMultiThreadAccess.java + * @run junit ProviderPoolMultiThreadAccess + */ +import java.text.spi.DateFormatProvider; +import java.util.spi.LocaleNameProvider; +import java.util.spi.LocaleServiceProvider; +import java.util.spi.TimeZoneNameProvider; + +import sun.util.locale.provider.LocaleServiceProviderPool; + +import org.junit.jupiter.api.Test; + +public class ProviderPoolMultiThreadAccess { + static volatile boolean failed; // false + static final int THREADS = 50; + + /* Multiple instances of Locale Service Provider Pool calling + * getAvailableLocales() should not throw ConcurrentModificationException + */ + @Test + public void multiThreadAccessTest() throws Exception { + Thread[] threads = new Thread[THREADS]; + for (int i=0; i cls; + private static int count; + + public TestThread() { + int which = count++ % 3; + switch (which) { + case 0 -> cls = LocaleNameProvider.class; + case 1 -> cls = TimeZoneNameProvider.class; + case 2 -> cls = DateFormatProvider.class; + default -> throw new AssertionError("Should not reach here"); + } + } + + public void run() { + try { + LocaleServiceProviderPool pool = LocaleServiceProviderPool.getPool(cls); + pool.getAvailableLocales(); + } catch (Exception e) { + System.out.println(e); + e.printStackTrace(); + failed = true; + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/RootLocale.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/RootLocale.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/RootLocale.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/RootLocale.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6277243 + * @summary Verify that there is Locale.ROOT constant, and it is equal to Locale("", "", "") + * @run junit RootLocale + */ + +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RootLocale { + + /** + * Locale.ROOT should exist and match an empty Locale given as + * Locale("", "", ""). + */ + @Test + public void rootTest() { + Locale root = new Locale("", "", ""); + assertEquals(Locale.ROOT, root, "Locale.ROOT is not equal to Locale(\"\", \"\", \"\")"); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8166994 + * @summary Checks the subsequent call to parse the same language ranges + * which must generate the same list of language ranges + * i.e. the priority list containing equivalents, as in the + * first call + * @run junit SubsequentRangeParsingTest + */ + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class SubsequentRangeParsingTest { + + /* + * Checks that consecutive calls to parse the same language ranges + * generate the same list of language ranges. + */ + @ParameterizedTest + @MethodSource("ranges") + public void parseConsistencyTest(List list, String ranges) { + // consecutive call to check the language range parse consistency + testParseConsistency(list, ranges); + testParseConsistency(list, ranges); + } + + // Ensure that parsing the ranges returns the expected list. + private static void testParseConsistency(List list, String ranges) { + List priorityList = parseRanges(ranges); + assertEquals(list, priorityList, "Failed to parse the language range:"); + } + + private static List parseRanges(String s) { + return Locale.LanguageRange.parse(s).stream() + .map(Locale.LanguageRange::getRange) + .collect(Collectors.toList()); + } + + // Ranges that have multiple equivalents and single equivalents. + private static Stream ranges() { + return Stream.of( + Arguments.of(Arrays.asList("ccq-aa", "ybd-aa", "rki-aa"), + "ccq-aa"), + Arguments.of(Arrays.asList("gfx-xz", "oun-xz", "mwj-xz", + "vaj-xz", "taj-xy", "tsf-xy"), "gfx-xz, taj-xy") + ); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/ThaiGov.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ThaiGov.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/ThaiGov.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/ThaiGov.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,98 +20,70 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** + +/* * @test * @bug 4474409 + * @summary Tests some localized methods with Thai locale * @author John O'Conner * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT ThaiGov + * @run junit/othervm -Djava.locale.providers=COMPAT ThaiGov */ -import java.util.*; -import java.text.*; - -public class ThaiGov { +import java.text.DateFormat; +import java.text.NumberFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; - ThaiGov() { - System.out.println("ThaiGov locale test..."); +import org.junit.jupiter.api.Test; - } - - void numberTest() throws RuntimeException { - final String strExpected = "\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53\u0E54"; - final double value = 12345678.234; +import static org.junit.jupiter.api.Assertions.assertEquals; - Locale locTH = new Locale("th", "TH", "TH"); - - // th_TH_TH test - NumberFormat nf = NumberFormat.getInstance(locTH); - String str = nf.format(value); +public class ThaiGov { - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } + private static final double VALUE = 12345678.234; + private static final Locale TH = new Locale("th", "TH", "TH"); + // Test number formatting for thai + @Test + public void numberTest() { + final String strExpected = "\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53\u0E54"; + NumberFormat nf = NumberFormat.getInstance(TH); + String str = nf.format(VALUE); + assertEquals(strExpected, str); } - void currencyTest() throws RuntimeException { + // Test currency formatting for Thai + @Test + public void currencyTest() { final String strExpected = "\u0E3F\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53"; - final double value = 12345678.234; - - Locale locTH = new Locale("th", "TH", "TH"); - - // th_TH_TH test - NumberFormat nf = NumberFormat.getCurrencyInstance(locTH); - String str = nf.format(value); - - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } - + NumberFormat nf = NumberFormat.getCurrencyInstance(TH); + String str = nf.format(VALUE); + assertEquals(strExpected, str); } - void dateTest() throws RuntimeException { - Locale locTH = new Locale("th", "TH", "TH"); - TimeZone tz = TimeZone.getTimeZone("PST"); - + // Test date formatting for Thai + @Test + public void dateTest() { + TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); Calendar calGregorian = Calendar.getInstance(tz, Locale.US); calGregorian.clear(); calGregorian.set(2002, 4, 1, 8, 30); final Date date = calGregorian.getTime(); - Calendar cal = Calendar.getInstance(tz, locTH); + Calendar cal = Calendar.getInstance(tz, TH); cal.clear(); cal.setTime(date); final String strExpected = "\u0E27\u0E31\u0E19\u0E1E\u0E38\u0E18\u0E17\u0E35\u0E48\u0020\u0E51\u0020\u0E1E\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21\u0020\u0E1E\u002E\u0E28\u002E\u0020\u0E52\u0E55\u0E54\u0E55\u002C\u0020\u0E58\u0020\u0E19\u0E32\u0E2C\u0E34\u0E01\u0E32\u0020\u0E53\u0E50\u0020\u0E19\u0E32\u0E17\u0E35\u0020\u0E50\u0E50\u0020\u0E27\u0E34\u0E19\u0E32\u0E17\u0E35"; - Date value = cal.getTime(); + Date value = cal.getTime(); // th_TH_TH test - DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locTH); + DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, TH); df.setTimeZone(tz); String str = df.format(value); - - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } - + assertEquals(strExpected, str); } - - public static void main(String[] args) { - - ThaiGov app = new ThaiGov(); - System.out.print("Running numberTest..."); - app.numberTest(); - System.out.print("Finished\n"); - System.out.print("Running currencyTest..."); - app.currencyTest(); - System.out.print("Finished\n"); - System.out.print("Running dateTest..."); - app.dateTest(); - System.out.print("Finished\n"); - - System.out.println("PASSED"); - } - - } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/TurkishLangRangeTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/TurkishLangRangeTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/TurkishLangRangeTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/TurkishLangRangeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8159420 + * @summary Checks the proper execution of LanguageRange.parse() and + * other LocaleMatcher methods when used in the locales like + * Turkish, because the toLowerCase() method is invoked in the + * parse() and other LocaleMatcher methods. + * e.g. "HI-Deva".toLowerCase() in the Turkish locale returns + * "hı-deva", where 'ı' is the LATIN SMALL LETTER DOTLESS I character + * which is not allowed in the language ranges/tags. + * @compile -encoding utf-8 TurkishLangRangeTest.java + * @run junit/othervm -Duser.language=tr -Duser.country=TR TurkishLangRangeTest + */ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Locale.LanguageRange; +import java.util.Locale.FilteringMode; +import java.util.LinkedHashMap; +import java.util.stream.Stream; + +import static java.util.Locale.FilteringMode.EXTENDED_FILTERING; +import static java.util.Locale.FilteringMode.AUTOSELECT_FILTERING; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TurkishLangRangeTest { + + /* + * Ensure parse() does not throw IllegalArgumentException for the Turkish Locale + * with the given input. + */ + @Test + public void parseTest() { + String ranges = "HI-Deva, ja-hIrA-JP, RKI"; + assertDoesNotThrow(() -> LanguageRange.parse(ranges)); + } + + /* + * Ensure filter() does not return empty list for the Turkish Locale + * with the given input. + */ + @ParameterizedTest + @MethodSource("modes") + public void filterTest(FilteringMode mode) { + String ranges = "hi-IN, itc-Ital"; + String tags = "hi-IN, itc-Ital"; + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLocales(tags); + String actualLocales = showLocales(Locale.filter(priorityList, tagList, mode)); + String expectedLocales = "hi-IN, itc-Ital"; + assertEquals(expectedLocales, actualLocales); + } + + private static Stream modes() { + return Stream.of( + EXTENDED_FILTERING, + AUTOSELECT_FILTERING + ); + } + + /* + * Ensure lookup() does not return null for the Turkish Locale with + * the given input. + */ + @Test + public void lookupTest() { + String ranges = "hi-IN, itc-Ital"; + String tags = "hi-IN, itc-Ital"; + List priorityList = LanguageRange.parse(ranges); + List localeList = generateLocales(tags); + Locale actualLocale = Locale.lookup(priorityList, localeList); + assertNotNull(actualLocale); + String actualLocaleString = actualLocale.toLanguageTag(); + String expectedLocale = "hi-IN"; + assertEquals(expectedLocale, actualLocaleString); + } + + /* + * Ensure mapEquivalents() does not only return "hi-in" for the Turkish + * Locale with the given input. + */ + @Test + public void mapEquivalentsTest() { + String ranges = "HI-IN"; + List priorityList = LanguageRange.parse(ranges); + HashMap> map = new LinkedHashMap<>(); + List equivalentList = new ArrayList<>(); + equivalentList.add("HI"); + equivalentList.add("HI-Deva"); + map.put("HI", equivalentList); + + List expected = new ArrayList<>(); + expected.add(new LanguageRange("hi-in")); + expected.add(new LanguageRange("hi-deva-in")); + List got = + LanguageRange.mapEquivalents(priorityList, map); + assertEquals(expected, got, getDifferences(expected, got)); + } + + private static String getDifferences(List expected, + List got) { + StringBuilder diffs = new StringBuilder(); + List cloneExpected = new ArrayList<>(expected); + cloneExpected.removeAll(got); + if (!cloneExpected.isEmpty()) { + diffs.append("Found missing range(s): ") + .append(cloneExpected) + .append(System.lineSeparator()); + } + List cloneGot = new ArrayList<>(got); + cloneGot.removeAll(expected); + if (!got.isEmpty()) { + diffs.append("Got extra range(s): ") + .append(cloneGot) + .append(System.lineSeparator()); + } + return diffs.toString(); + } + + private static List generateLocales(String tags) { + if (tags == null) { + return null; + } + + List localeList = new ArrayList<>(); + if (tags.equals("")) { + return localeList; + } + String[] t = tags.split(", "); + for (String tag : t) { + localeList.add(Locale.forLanguageTag(tag)); + } + return localeList; + } + + private static String showLocales(List locales) { + StringBuilder sb = new StringBuilder(); + + Iterator itr = locales.iterator(); + if (itr.hasNext()) { + sb.append(itr.next().toLanguageTag()); + } + while (itr.hasNext()) { + sb.append(", "); + sb.append(itr.next().toLanguageTag()); + } + + return sb.toString().trim(); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/UseOldISOCodesTest.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/UseOldISOCodesTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/UseOldISOCodesTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/UseOldISOCodesTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8295232 + * @summary Ensures java.locale.useOldISOCodes is statically initialized + * @library /test/lib + * @run junit UseOldISOCodesTest + */ + +import java.util.Locale; +import jdk.test.lib.process.ProcessTools; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UseOldISOCodesTest { + + // Ensure java.locale.useOldISOCodes is only interpreted at runtime startup + @Test + public void staticInitializationTest() throws Exception { + ProcessTools.executeTestJvm("-Djava.locale.useOldISOCodes=true", "UseOldISOCodesTest$Runner") + .outputTo(System.out) + .errorTo(System.err) + .shouldHaveExitValue(0); + } + + static class Runner { + private static final String obsoleteCode = "iw"; + private static final String newCode = "he"; + + public static void main(String[] args) { + // Should have no effect + System.setProperty("java.locale.useOldISOCodes", "false"); + Locale locale = new Locale(newCode); + assertEquals(obsoleteCode, locale.getLanguage(), + "newCode 'he' was not mapped to 'iw' with useOldISOCodes=true"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4122700.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4122700.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4122700.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4122700.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 4122700 - * @summary Verify that list of available locales is non-empty, and print the list - */ - -import java.util.Locale; - -public class bug4122700 { - public static void main(String[] args) throws Exception { - Locale[] systemLocales = Locale.getAvailableLocales(); - if (systemLocales.length == 0) - throw new Exception("Available locale list is empty!"); - System.out.println("Found " + systemLocales.length + " locales:"); - Locale[] locales = new Locale[systemLocales.length]; - for (int i = 0; i < locales.length; i++) { - Locale lowest = null; - for (int j = 0; j < systemLocales.length; j++) { - if (i > 0 && locales[i - 1].toString().compareTo(systemLocales[j].toString()) >= 0) - continue; - if (lowest == null || systemLocales[j].toString().compareTo(lowest.toString()) < 0) - lowest = systemLocales[j]; - } - locales[i] = lowest; - } - for (int i = 0; i < locales.length; i++) { - if (locales[i].getCountry().length() == 0) - System.out.println(" " + locales[i].getDisplayLanguage() + ":"); - else { - if (locales[i].getVariant().length() == 0) - System.out.println(" " + locales[i].getDisplayCountry()); - else - System.out.println(" " + locales[i].getDisplayCountry() + ", " - + locales[i].getDisplayVariant()); - } - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4123285.html openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.html --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4123285.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.html 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ - diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4123285.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug4123285.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug4123285.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.util.Locale; - -public class bug4123285 extends java.applet.Applet { - public void start() { - System.out.println("Hello, world!"); - Locale[] systemLocales = null; - try { - System.out.println("Default locale = " + Locale.getDefault()); - systemLocales = Locale.getAvailableLocales(); - System.out.println("Found " + systemLocales.length + " locales:"); - Locale[] locales = new Locale[systemLocales.length]; - for (int i = 0; i < locales.length; i++) { - Locale lowest = null; - for (int j = 0; j < systemLocales.length; j++) { - if (i > 0 && locales[i - 1].toString().compareTo(systemLocales[j].toString()) >= 0) - continue; - if (lowest == null || systemLocales[j].toString().compareTo(lowest.toString()) < 0) - lowest = systemLocales[j]; - } - locales[i] = lowest; - } - for (int i = 0; i < locales.length; i++) { - if (locales[i].getCountry().length() == 0) - System.out.println(" " + locales[i].getDisplayLanguage() + ":"); - else { - if (locales[i].getVariant().length() == 0) - System.out.println(" " + locales[i].getDisplayCountry()); - else - System.out.println(" " + locales[i].getDisplayCountry() + ", " - + locales[i].getDisplayVariant()); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug6277243.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6277243.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug6277243.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6277243.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 6277243 - * @summary Verify that there is Locale.ROOT constant, and it is equal to Locale("", "", "") - */ - -import java.util.Locale; - -public class bug6277243 { - - public static void main(String[] args) throws Exception { - Locale root = new Locale("", "", ""); - if (!Locale.ROOT.equals(root)) { - throw new RuntimeException("Locale.ROOT is not equal to Locale(\"\", \"\", \"\")"); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug6312358.java openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6312358.java --- openjdk-17-17.0.14+7/test/jdk/java/util/Locale/bug6312358.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/Locale/bug6312358.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 6312358 - * @summary Verify that an NPE is thrown by issueing Locale.getInstance() with - * any argument being null. - * @modules java.base/java.util:open - */ - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Locale; - -public class bug6312358 { - - - public static void main(String[] args) throws Exception { - - try { - // Locale.getInstance is not directly accessible. - Method getInstanceMethod = Locale.class.getDeclaredMethod( - "getInstance", String.class, String.class, String.class - ); - getInstanceMethod.setAccessible(true); - - getInstanceMethod.invoke(null, "null", "GB", ""); - try { - getInstanceMethod.invoke(null, null, "GB", ""); - throw new RuntimeException("Should NPE with language set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with language set to null"); - } - } - - getInstanceMethod.invoke(null, "en", "null", ""); - try { - getInstanceMethod.invoke(null, "en", null, ""); - throw new RuntimeException("Should NPE with country set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with country set to null"); - } - } - - getInstanceMethod.invoke(null, "en", "GB", "null"); - try { - getInstanceMethod.invoke(null, "en", "GB", null); - throw new RuntimeException("Should NPE with variant set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with variant set to null"); - } - } - } catch (java.lang.NoSuchMethodException exc) { - // method is not found. consider it as a success - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java --- openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java 2025-04-09 19:45:33.000000000 +0000 @@ -90,15 +90,13 @@ // UnreadableRB.properties is in current directory String cp = Utils.TEST_CLASSES + File.pathSeparator + Utils.TEST_SRC + File.pathSeparator + "."; - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(cp) - .addToolArg("MissingResourceCauseTest"); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", cp, + "MissingResourceCauseTest"); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java --- openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; +import jdk.test.lib.Utils; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.ProcessTools; @@ -133,17 +134,15 @@ */ public static void runModule(String mp, String mn, List localeList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + List args = List.of( + "-ea", "-esa", + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); @@ -161,19 +160,17 @@ */ public static void runModuleWithCp(String cp, String mp, String mn, List localeList, boolean expected) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(cp) - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); + List args = List.of( + "-ea", "-esa", + "-cp", cp, + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); if (expected) { if (exitCode != 0) { throw new RuntimeException("Execution of the test loads bundles " @@ -198,18 +195,17 @@ */ public static void runModuleWithLegacyCode(String mp, String mn, List localeList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-Djava.locale.useOldISOCodes=true") - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); + List args = List.of( + "-ea", "-esa", + "-Djava.locale.useOldISOCodes=true", + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,16 +71,13 @@ } private static void runCmd() throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("Main") - .addToolArg(Utils.TEST_CLASSES); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "Main", Utils.TEST_CLASSES); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; @@ -73,42 +74,34 @@ private static void runCmd() throws Throwable { // access resource bundles that are exported private unconditionally. - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("--module-path") - .addToolArg(MODS_DIR.toString()) - .addToolArg("--add-modules") - .addToolArg("bundles") - .addToolArg("Main"); - LOCALE_LIST.forEach(launcher::addToolArg); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + List args = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "--module-path", MODS_DIR.toString(), + "--add-modules", "bundles", + "Main"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), LOCALE_LIST.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test1 failed. " + "Unexpected exit code: " + exitCode); } // --add-exports can't open resources - launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("--module-path") - .addToolArg(MODS_DIR.toString()) - .addToolArg("--add-modules") - .addToolArg("bundles") - .addToolArg("--add-opens") - .addToolArg("bundles/jdk.test.internal.resources=ALL-UNNAMED") - .addToolArg("Main"); - LOCALE_LIST.forEach(launcher::addToolArg); + List argsWithOpens = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "--module-path", MODS_DIR.toString(), + "--add-modules", "bundles", + "--add-opens", "bundles/jdk.test.internal.resources=ALL-UNNAMED", + "Main"); + pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(argsWithOpens.stream(), LOCALE_LIST.stream()).toList()); - exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Evaluate process status + exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test2 failed. " + "Unexpected exit code: " + exitCode); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 8137317 8139238 8210408 * @summary Visibility tests for ResourceBundle.getBundle with and without * an unnamed module argument. + * @requires vm.flagless * @library /test/lib * .. * @build jdk.test.lib.JDKToolLauncher @@ -39,10 +40,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import jdk.test.lib.process.ProcessTools; + import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -328,11 +331,10 @@ } private int runCmd(List argsList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa"); - argsList.forEach(launcher::addToolArg); - - return ProcessTools.executeCommand(launcher.getCommand()).getExitValue(); + // Build process (without VM flags) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + Stream.concat(Stream.of("-ea", "-esa"), argsList.stream()).toList()); + // Evaluate process status + return ProcessTools.executeCommand(pb).getExitValue(); } -} \ No newline at end of file +} diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/Bug4322313.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug4322313.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/Bug4322313.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug4322313.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,14 +27,17 @@ * @summary Make sure that new implementation of custom time zone * support for TimeZone.getTimeZone() works correctly and the * getDisplayName() methods are locale independent. - * @library /java/text/testlib + * @run junit Bug4322313 */ -import java.io.*; -import java.text.*; -import java.util.*; +import java.util.Locale; +import java.util.TimeZone; -public class Bug4322313 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4322313 { private static final int MPM = 60 * 1000; /* Milliseconds per minute */ private static final Object[][] VALIDS = { /* given ID rawOffset normalized ID */ @@ -80,6 +83,7 @@ "GMT+09:00 ", }; + @Test void Test4322313() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -106,7 +110,7 @@ "\"] Invalid TimeZone ID, expected:" + VALIDS[k][2] + ", got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Valid TimeZone ID, got:" + VALIDS[k][2]); } @@ -119,7 +123,7 @@ "\"] Invalid RawOffset, expected:" + VALIDS[k][1] + ", got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Vaild RawOffset, got:" + offset); } @@ -132,7 +136,7 @@ "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] DSTSavings is zero."); } @@ -150,7 +154,7 @@ "\"] Invalid TimeZone ID, expected:GMT, got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] Valid TimeZone ID, got:" + tz.getID()); } @@ -163,7 +167,7 @@ "\"] RawOffset should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] RawOffset is zero."); } @@ -176,7 +180,7 @@ "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] DSTSavings is zero."); } @@ -218,13 +222,9 @@ TimeZone.setDefault(savedTimeZone); } if (err) { - errln("TimeZone.getTimeZone() test failed"); + fail("TimeZone.getTimeZone() test failed"); } else { - logln("TimeZone.getTimeZone() test passed"); + System.out.println("TimeZone.getTimeZone() test passed"); } } - - public static void main (String[] args) throws Exception { - new Bug4322313().run(args); - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/Bug6329116.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug6329116.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/Bug6329116.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/Bug6329116.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,27 +27,24 @@ * 7039469 7090843 7103108 7103405 7158483 8008577 8059206 8064560 8072042 * 8077685 8151876 8166875 8169191 8170316 8176044 * @summary Make sure that timezone short display names are idenical to Olson's data. - * @library /java/text/testlib - * @build Bug6329116 TextFileReader - * @run main/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug6329116 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug6329116 { static Locale[] locales = Locale.getAvailableLocales(); static String[] timezones = TimeZone.getAvailableIDs(); - public static void main(String[] args) throws IOException { - if (bug6329116()) { - throw new RuntimeException("At least one timezone display name is incorrect."); - } - } - - static boolean bug6329116() throws IOException { + @Test + public void bug6329116() throws IOException { boolean err = false; HashMap aliasTable = new HashMap<>(); @@ -200,7 +197,9 @@ } } - return err; + if (err) { + fail("At least one timezone display name is incorrect."); + } } static boolean useLocalzedShortDisplayName(TimeZone tz, diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java 2025-04-09 19:45:33.000000000 +0000 @@ -29,16 +29,18 @@ * @requires os.family != "windows" * @run main/othervm CustomTzIDCheckDST */ + import java.util.Calendar; import java.util.Date; -import java.util.List; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.time.DayOfWeek; import java.time.ZonedDateTime; import java.time.temporal.TemporalAdjusters; + import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; + public class CustomTzIDCheckDST { // Northern Hemisphere private static String CUSTOM_TZ = "MEZ-1MESZ,M3.5.0,M10.5.0/3"; @@ -46,7 +48,7 @@ private static String CUSTOM_TZ2 = "MEZ-1MESZ,M10.5.0,M3.5.0/3"; public static void main(String args[]) throws Throwable { if (args.length == 0) { - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of("CustomTzIDCheckDST", "runTZTest")); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("CustomTzIDCheckDST", "runTZTest"); pb.environment().put("TZ", CUSTOM_TZ); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldHaveExitValue(0); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,26 @@ /* * @test - * @library /java/text/testlib * @summary test Time Zone Boundary + * @run junit TimeZoneBoundaryTest */ -import java.text.*; -import java.util.*; +import java.text.DateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; /** * A test which discovers the boundaries of DST programmatically and verifies * that they are correct. */ -public class TimeZoneBoundaryTest extends IntlTest +public class TimeZoneBoundaryTest { static final int ONE_SECOND = 1000; static final int ONE_MINUTE = 60*ONE_SECOND; @@ -57,10 +65,6 @@ static final long AUSTRALIA_1997_BEG = 877797000000L; static final long AUSTRALIA_1997_END = 859653000000L; - public static void main(String[] args) throws Exception { - new TimeZoneBoundaryTest().run(args); - } - /** * Date.toString().substring() Boundary Test * Look for a DST changeover to occur within 6 months of the given Date. @@ -75,7 +79,7 @@ if (d.toString().indexOf(startMode) == -1) { - logln("Error: " + startMode + " not present in " + d); + System.out.println("Error: " + startMode + " not present in " + d); } // Use a binary search, assuming that we have a Standard @@ -98,15 +102,15 @@ } } - logln("Date Before: " + showDate(min)); - logln("Date After: " + showDate(max)); + System.out.println("Date Before: " + showDate(min)); + System.out.println("Date After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, long expectedBoundary) @@ -128,14 +132,14 @@ if (tz.inDaylightTime(d) != startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + d + ") != " + startsInDST); startsInDST = !startsInDST; // Flip over; find the apparent value } if (tz.inDaylightTime(new Date(max)) == startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); return; } @@ -154,16 +158,16 @@ } } - logln(tz.getID() + " Before: " + showDate(min, tz)); - logln(tz.getID() + " After: " + showDate(max, tz)); + System.out.println(tz.getID() + " Before: " + showDate(min, tz)); + System.out.println(tz.getID() + " After: " + showDate(max, tz)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } private static String showDate(long l) @@ -209,23 +213,23 @@ boolean expUseDaylightTime, boolean expInDaylightTime, int expZoneOffset, int expDSTOffset) { - logln("-- Verifying time " + d + + System.out.println("-- Verifying time " + d + " in zone " + time_zone.getID()); if (time_zone.inDaylightTime(d) == expInDaylightTime) - logln("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); + System.out.println("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); else - errln("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); + fail("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); if (time_zone.useDaylightTime() == expUseDaylightTime) - logln("PASS: useDaylightTime = " + time_zone.useDaylightTime()); + System.out.println("PASS: useDaylightTime = " + time_zone.useDaylightTime()); else - errln("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); + fail("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); if (time_zone.getRawOffset() == expZoneOffset) - logln("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); + System.out.println("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); else - errln("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + + fail("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + "; expected " + expZoneOffset/(double)ONE_HOUR); GregorianCalendar gc = new GregorianCalendar(time_zone); @@ -237,13 +241,14 @@ gc.get(gc.SECOND)) * 1000 + gc.get(gc.MILLISECOND)); if (offset == expDSTOffset) - logln("PASS: getOffset() = " + offset/(double)ONE_HOUR); + System.out.println("PASS: getOffset() = " + offset/(double)ONE_HOUR); else - errln("FAIL: getOffset() = " + offset/(double)ONE_HOUR + + fail("FAIL: getOffset() = " + offset/(double)ONE_HOUR + "; expected " + expDSTOffset/(double)ONE_HOUR); } @SuppressWarnings("deprecation") + @Test public void TestBoundaries() { TimeZone pst = TimeZone.getTimeZone("PST"); @@ -263,19 +268,19 @@ inDST ? -7*ONE_HOUR : -8*ONE_HOUR); } - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,0,1), "PST", PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,6,1), "PDT", PST_1997_END); // Southern hemisphere test - logln("========================================"); + System.out.println("========================================"); TimeZone z = TimeZone.getTimeZone(AUSTRALIA); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), true, AUSTRALIA_1997_END, z); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), false, PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true, PST_1997_END); } finally { TimeZone.setDefault(save); @@ -297,7 +302,7 @@ if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); } while ((max - min) > INTERVAL) @@ -313,120 +318,49 @@ } } - logln("Binary Search Before: " + showDate(min)); - logln("Binary Search After: " + showDate(max)); + System.out.println("Binary Search Before: " + showDate(min)); + System.out.println("Binary Search After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } - /* - static void testUsingMillis(Date d, boolean startsInDST) - { - long millis = d.getTime(); - long max = millis + (long)(370 * ONE_DAY); // A year plus extra - - boolean lastDST = startsInDST; - while (millis < max) - { - cal.setTime(new Date(millis)); - boolean inDaylight = cal.inDaylightTime(); - - if (inDaylight != lastDST) - { - logln("Switch " + (inDaylight ? "into" : "out of") - + " DST at " + (new Date(millis))); - lastDST = inDaylight; - } - - millis += 15*ONE_MINUTE; - } - } - */ - /** * Test new rule formats. */ @SuppressWarnings("deprecation") - public void TestNewRules() - { - //logln(Locale.getDefault().getDisplayName()); - //logln(TimeZone.getDefault().getID()); - //logln(new Date(0)); - - if (true) - { - // Doesn't matter what the default TimeZone is here, since we - // are creating our own TimeZone objects. - - SimpleTimeZone tz; - - logln("-----------------------------------------------------------------"); - logln("Aug 2ndTues .. Mar 15"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", - Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, - Calendar.MARCH, 15, 0, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); - - logln("-----------------------------------------------------------------"); - logln("Apr Wed>=14 .. Sep Sun<=20"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", - Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, - Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); - } - - /* - if (true) - { - logln("========================================"); - logln("Stepping using millis"); - testUsingMillis(new Date(97,0,1), false); - } - - if (true) - { - logln("========================================"); - logln("Stepping using fields"); - testUsingFields(1997, false); - } - - if (false) - { - cal.clear(); - cal.set(1997, 3, 5, 10, 0); - // cal.inDaylightTime(); - logln("Date = " + cal.getTime()); - logln("Millis = " + cal.getTime().getTime()/3600000); - } - */ - } - - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - // Long Bug - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - - //public void Test3() - //{ - // findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true); - //} + @Test + public void TestNewRules() { + // Doesn't matter what the default TimeZone is here, since we + // are creating our own TimeZone objects. + + SimpleTimeZone tz; + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Aug 2ndTues .. Mar 15"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", + Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, + Calendar.MARCH, 15, 0, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Apr Wed>=14 .. Sep Sun<=20"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", + Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, + Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); + } /** * Find boundaries by stepping. @@ -439,15 +373,15 @@ long limit = time + ONE_YEAR + ONE_DAY; boolean lastState = z.inDaylightTime(d); int changes = 0; - logln("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); - logln("useDaylightTime = " + z.useDaylightTime()); + System.out.println("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); + System.out.println("useDaylightTime = " + z.useDaylightTime()); while (time < limit) { d.setTime(time); boolean state = z.inDaylightTime(d); if (state != lastState) { - logln((state ? "Entry " : "Exit ") + + System.out.println((state ? "Entry " : "Exit ") + "at " + d); lastState = state; ++changes; @@ -456,23 +390,24 @@ } if (changes == 0) { - if (!lastState && !z.useDaylightTime()) logln("No DST"); - else errln("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); + if (!lastState && !z.useDaylightTime()) System.out.println("No DST"); + else fail("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); } else if (changes != 2) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); } else if (!z.useDaylightTime()) { - errln("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); + fail("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); } if (changes != expectedChanges) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); } } + @Test public void TestStepwise() { findBoundariesStepwise(1997, ONE_DAY, TimeZone.getTimeZone("ACT"), 0); diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneData/VERSION openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/VERSION --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneData/VERSION 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/VERSION 2025-04-09 19:45:33.000000000 +0000 @@ -1 +1 @@ -tzdata2024b +tzdata2025a diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneData/aliases.txt openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/aliases.txt --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneData/aliases.txt 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneData/aliases.txt 2025-04-09 19:45:33.000000000 +0000 @@ -1,6 +1,3 @@ -Link Asia/Riyadh87 Mideast/Riyadh87 -Link Asia/Riyadh88 Mideast/Riyadh88 -Link Asia/Riyadh89 Mideast/Riyadh89 Link Australia/Sydney Australia/ACT #= Australia/Canberra Link Australia/Lord_Howe Australia/LHI Link Australia/Sydney Australia/NSW diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,17 +66,15 @@ //run it with the security manager on, plus accesscontroller debugging //will go into infinite recursion trying to get enough permissions for //printing Date of failing certificate unless fix is applied. - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-Djava.security.manager") - .addToolArg("-Djava.security.debug=access,failure,policy") - .addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(jarPath) - .addToolArg("TimeZoneDatePermissionCheck"); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-Djava.security.manager", + "-Djava.security.debug=access,failure,policy", + "-ea", "-esa", + "-cp", jarPath, + "TimeZoneDatePermissionCheck"); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Unexpected exit code: " + exitCode); } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneRegression.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneRegression.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneRegression.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneRegression.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,42 +27,44 @@ * 4154525 4154537 4154542 4154650 4159922 4162593 4173604 4176686 4184229 4208960 * 4966229 6433179 6851214 8007520 8008577 * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression */ import java.util.*; import java.io.*; import java.text.*; -public class TimeZoneRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimeZoneRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneRegression { + @Test public void Test4073209() { TimeZone z1 = TimeZone.getTimeZone("PST"); TimeZone z2 = TimeZone.getTimeZone("PST"); if (z1 == z2) { - errln("Fail: TimeZone should return clones"); + fail("Fail: TimeZone should return clones"); } } @SuppressWarnings("deprecation") + @Test public void Test4073215() { SimpleTimeZone z = new SimpleTimeZone(0, "GMT"); if (z.useDaylightTime()) { - errln("Fail: Fix test to start with non-DST zone"); + fail("Fail: Fix test to start with non-DST zone"); } z.setStartRule(Calendar.FEBRUARY, 1, Calendar.SUNDAY, 0); z.setEndRule(Calendar.MARCH, -1, Calendar.SUNDAY, 0); if (!z.useDaylightTime()) { - errln("Fail: DST not active"); + fail("Fail: DST not active"); } if (z.inDaylightTime(new Date(97, Calendar.JANUARY, 31)) || !z.inDaylightTime(new Date(97, Calendar.MARCH, 1)) || z.inDaylightTime(new Date(97, Calendar.MARCH, 31))) { - errln("Fail: DST not working as expected"); + fail("Fail: DST not working as expected"); } } @@ -74,6 +76,7 @@ * day of end 0:59 AM STD = display name 1:59 AM DT * 1:00 AM STD = display name 1:00 AM ST */ + @Test public void Test4084933() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -113,10 +116,11 @@ offset3 != SToffset || offset4 != DToffset || offset5 != DToffset || offset6 != SToffset || offset7 != SToffset || offset8 != SToffset) - errln("Fail: TimeZone misbehaving"); { + fail("Fail: TimeZone misbehaving"); { } } + @Test public void Test4096952() { String[] ZONES = { "GMT", "MET", "IST" }; boolean pass = true; @@ -124,7 +128,7 @@ for (int i=0; i max) max = ids.length; - logln(hname + ' ' + ids.length + + System.out.println(hname + ' ' + ids.length + ((ids.length > 0) ? (" e.g. " + ids[0]) : "")); } catch (Exception e) { - errln(hname + ' ' + "Fail: " + e); + fail(hname + ' ' + "Fail: " + e); } } - logln("Maximum zones per offset = " + max); + System.out.println("Maximum zones per offset = " + max); } + @Test public void Test4151429() { try { TimeZone tz = TimeZone.getTimeZone("GMT"); String name = tz.getDisplayName(true, Integer.MAX_VALUE, Locale.getDefault()); - errln("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); + fail("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); } catch(IllegalArgumentException e) {} } @@ -373,6 +381,7 @@ * SimpleTimeZone accepts illegal DST savings values. These values * must be non-zero. There is no upper limit at this time. */ + @Test public void Test4154525() { final int GOOD = 1, BAD = 0; int[] DATA = { @@ -404,15 +413,15 @@ break; } if (valid) { - logln("Pass: DST savings of " + savings + " accepted by " + method); + System.out.println("Pass: DST savings of " + savings + " accepted by " + method); } else { - errln("Fail: DST savings of " + savings + " accepted by " + method); + fail("Fail: DST savings of " + savings + " accepted by " + method); } } catch (IllegalArgumentException e) { if (valid) { - errln("Fail: DST savings of " + savings + " to " + method + " gave " + e); + fail("Fail: DST savings of " + savings + " to " + method + " gave " + e); } else { - logln("Pass: DST savings of " + savings + " to " + method + " gave " + e); + System.out.println("Pass: DST savings of " + savings + " to " + method + " gave " + e); } } } @@ -423,6 +432,7 @@ * SimpleTimeZone.hasSameRules() doesn't work for zones with no DST * and different DST parameters. */ + @Test public void Test4154537() { // tz1 and tz2 have no DST and different rule parameters SimpleTimeZone tz1 = new SimpleTimeZone(0, "1", 0, 0, 0, 0, 2, 0, 0, 0); @@ -435,15 +445,15 @@ if (tz1.useDaylightTime() || tz2.useDaylightTime() || !tza.useDaylightTime() || !tzA.useDaylightTime() || !tzb.useDaylightTime()) { - errln("Test is broken -- rewrite it"); + fail("Test is broken -- rewrite it"); } if (!tza.hasSameRules(tzA) || tza.hasSameRules(tzb)) { - errln("Fail: hasSameRules() broken for zones with rules"); + fail("Fail: hasSameRules() broken for zones with rules"); } if (!tz1.hasSameRules(tz2)) { - errln("Fail: hasSameRules() returns false for zones without rules"); - errln("zone 1 = " + tz1); - errln("zone 2 = " + tz2); + fail("Fail: hasSameRules() returns false for zones without rules"); + fail("zone 1 = " + tz1); + fail("zone 2 = " + tz2); } } @@ -451,6 +461,7 @@ * SimpleTimeZone constructors, setStartRule(), and setEndRule() don't * check for out-of-range arguments. */ + @Test public void Test4154542() { final int GOOD = 1; final int BAD = 0; @@ -496,7 +507,7 @@ ex = e; } if ((ex == null) != shouldBeGood) { - errln("setStartRule(month=" + month + ", day=" + day + + fail("setStartRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -509,7 +520,7 @@ ex = e; } if ((ex == null) != shouldBeGood) { - errln("setEndRule(month=" + month + ", day=" + day + + fail("setEndRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -524,7 +535,7 @@ ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(month=" + month + ", day=" + day + + fail("SimpleTimeZone(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (", ) should work but throws " + ex) : ", ) should fail but doesn't")); @@ -539,7 +550,7 @@ ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(, month=" + month + ", day=" + day + + fail("SimpleTimeZone(, month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -550,6 +561,7 @@ /** * SimpleTimeZone.getOffset accepts illegal arguments. */ + @Test public void Test4154650() { final int GOOD=1, BAD=0; final int GOOD_ERA=GregorianCalendar.AD, GOOD_YEAR=1998, GOOD_MONTH=Calendar.AUGUST; @@ -594,7 +606,7 @@ e = ex; } if (good != (e == null)) { - errln("Fail: getOffset(" + + fail("Fail: getOffset(" + DATA[i+1] + ", " + DATA[i+2] + ", " + DATA[i+3] + ", " + DATA[i+4] + ", " + DATA[i+5] + ", " + DATA[i+6] + (good ? (") threw " + e) : ") accepts invalid args")); @@ -605,6 +617,7 @@ /** * TimeZone constructors allow null IDs. */ + @Test public void Test4159922() { TimeZone z = null; @@ -612,38 +625,38 @@ // allow null. try { z = TimeZone.getTimeZone((String)null); - errln("FAIL: Null allowed in getTimeZone"); + fail("FAIL: Null allowed in getTimeZone"); } catch (NullPointerException e) {} z = TimeZone.getTimeZone("GMT"); try { z.getDisplayName(false, TimeZone.SHORT, null); - errln("FAIL: Null allowed in getDisplayName(3)"); + fail("FAIL: Null allowed in getDisplayName(3)"); } catch (NullPointerException e) {} try { z.getDisplayName(null); - errln("FAIL: Null allowed in getDisplayName(1)"); + fail("FAIL: Null allowed in getDisplayName(1)"); } catch (NullPointerException e) {} try { if (z.hasSameRules(null)) { - errln("FAIL: hasSameRules returned true"); + fail("FAIL: hasSameRules returned true"); } } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in hasSameRules"); + fail("FAIL: Null NOT allowed in hasSameRules"); } try { z.inDaylightTime(null); - errln("FAIL: Null allowed in inDaylightTime"); + fail("FAIL: Null allowed in inDaylightTime"); } catch (NullPointerException e) {} try { z.setID(null); - errln("FAIL: Null allowed in setID"); + fail("FAIL: Null allowed in setID"); } catch (NullPointerException e) {} TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(null); } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in setDefault"); + fail("FAIL: Null NOT allowed in setDefault"); } finally { TimeZone.setDefault(save); } @@ -652,15 +665,15 @@ SimpleTimeZone s = null; try { s = new SimpleTimeZone(0, null); - errln("FAIL: Null allowed in SimpleTimeZone(2)"); + fail("FAIL: Null allowed in SimpleTimeZone(2)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0); - errln("FAIL: Null allowed in SimpleTimeZone(10)"); + fail("FAIL: Null allowed in SimpleTimeZone(10)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0, 1000); - errln("FAIL: Null allowed in SimpleTimeZone(11)"); + fail("FAIL: Null allowed in SimpleTimeZone(11)"); } catch (NullPointerException e) {} } @@ -669,6 +682,7 @@ * transitions at midnight correctly. */ @SuppressWarnings("deprecation") + @Test public void Test4162593() { SimpleDateFormat fmt = new SimpleDateFormat("z", Locale.US); final int ONE_HOUR = 60*60*1000; @@ -711,18 +725,18 @@ Date d = new Date(p[0], p[1], p[2], p[3], p[4]); boolean transitionExpected = ((Boolean)DATA[j+2]).booleanValue(); - logln(tz.getID() + ":"); + System.out.println(tz.getID() + ":"); for (int i=0; i<4; ++i) { zone[i] = fmt.format(d); - logln("" + i + ": " + d); + System.out.println("" + i + ": " + d); d = new Date(d.getTime() + ONE_HOUR); } if (zone[0].equals(zone[1]) && (zone[1].equals(zone[2]) != transitionExpected) && zone[2].equals(zone[3])) { - logln("Ok: transition " + transitionExpected); + System.out.println("Ok: transition " + transitionExpected); } else { - errln("Fail: boundary transition incorrect"); + fail("Fail: boundary transition incorrect"); } } } @@ -736,6 +750,7 @@ /** * TimeZone broken in last hour of year */ + @Test public void Test4173604() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -748,7 +763,7 @@ int o23 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 23*60*60*1000); int o00 = pst.getOffset(1, 1999, 0, 1, Calendar.FRIDAY, 0); if (o22 != o23 || o22 != o00) { - errln("Offsets should be the same (for PST), but got: " + + fail("Offsets should be the same (for PST), but got: " + "12/31 22:00 " + o22 + ", 12/31 23:00 " + o23 + ", 01/01 00:00 " + o00); @@ -767,12 +782,12 @@ ++transitions; Calendar t = (Calendar)cal.clone(); t.add(Calendar.MINUTE, -delta); - logln(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); - logln(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); + System.out.println(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); + System.out.println(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); } } if (transitions != 4) { - errln("Saw " + transitions + " transitions; should have seen 4"); + fail("Saw " + transitions + " transitions; should have seen 4"); } } @@ -780,6 +795,7 @@ * getDisplayName doesn't work with unusual savings/offsets. */ @SuppressWarnings("deprecation") + @Test public void Test4176686() { // Construct a zone that does not observe DST but // that does have a DST savings (which should be ignored). @@ -827,7 +843,7 @@ for (int i=0; i " + DATA[i+1] + ", exp " + DATA[i+2]); + fail("FAIL: " + DATA[i] + " -> " + DATA[i+1] + ", exp " + DATA[i+2]); } } } @@ -835,57 +851,58 @@ /** * SimpleTimeZone allows invalid DOM values. */ + @Test public void Test4184229() { SimpleTimeZone zone = null; try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 startDay"); + fail("Failed. No exception has been thrown for DOM -1 startDay"); } catch(IllegalArgumentException e) { - logln("(a) " + e.getMessage()); + System.out.println("(a) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 endDay"); + fail("Failed. No exception has been thrown for DOM -1 endDay"); } catch(IllegalArgumentException e) { - logln("(b) " + e.getMessage()); + System.out.println("(b) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 startDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 startDay +savings"); } catch(IllegalArgumentException e) { - logln("(c) " + e.getMessage()); + System.out.println("(c) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 endDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 endDay +savings"); } catch(IllegalArgumentException e) { - logln("(d) " + e.getMessage()); + System.out.println("(d) " + e.getMessage()); } // Make a valid constructor call for subsequent tests. zone = new SimpleTimeZone(0, "A", 0, 1, 0, 0, 0, 1, 0, 0); try { zone.setStartRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); } catch(IllegalArgumentException e) { - logln("(e) " + e.getMessage()); + System.out.println("(e) " + e.getMessage()); } try { zone.setStartRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule"); } catch(IllegalArgumentException e) { - logln("(f) " + e.getMessage()); + System.out.println("(f) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); } catch(IllegalArgumentException e) { - logln("(g) " + e.getMessage()); + System.out.println("(g) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule"); } catch(IllegalArgumentException e) { - logln("(h) " + e.getMessage()); + System.out.println("(h) " + e.getMessage()); } } @@ -893,6 +910,7 @@ * SimpleTimeZone.getOffset() throws IllegalArgumentException when to get * of 2/29/1996 (leap day). */ + @Test public void Test4208960 () { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -905,14 +923,14 @@ int offset = tz.getOffset(GregorianCalendar.AD, 1996, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); } catch (IllegalArgumentException e) { - errln("FAILED: to get TimeZone.getOffset(2/29/96)"); + fail("FAILED: to get TimeZone.getOffset(2/29/96)"); } try { int offset = tz.getOffset(GregorianCalendar.AD, 1997, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); - errln("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); + fail("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); } catch (IllegalArgumentException e) { - logln("got IllegalArgumentException"); + System.out.println("got IllegalArgumentException"); } } @@ -921,6 +939,7 @@ * sun.util.calendar.ZoneInfo doesn't clone properly. */ @SuppressWarnings("deprecation") + @Test public void Test4966229() { TimeZone savedTZ = TimeZone.getDefault(); try { @@ -945,7 +964,7 @@ cal2.setTime(d); int hourOfDay = cal2.get(cal.HOUR_OF_DAY); if (hourOfDay != expectedHourOfDay) { - errln("wrong hour of day: got: " + hourOfDay + fail("wrong hour of day: got: " + hourOfDay + ", expected: " + expectedHourOfDay); } } finally { @@ -956,6 +975,7 @@ /** * 6433179: (tz) Incorrect DST end for America/Winnipeg and Canada/Central in 2038+ */ + @Test public void Test6433179() { // Use the old America/Winnipeg rule for testing. Note that // startMode is WALL_TIME for testing. It's actually @@ -974,7 +994,7 @@ cal.set(cal.DAY_OF_WEEK_IN_MONTH, -1); cal.add(Calendar.HOUR_OF_DAY, 2); if (cal.get(cal.DST_OFFSET) == 0) { - errln("Should still be in DST."); + fail("Should still be in DST."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneTest.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TimeZoneTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TimeZoneTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -27,8 +27,8 @@ * 8008577 8077685 8098547 8133321 8138716 8148446 8151876 8159684 8166875 8181157 * 8228469 8274407 8305113 * @modules java.base/sun.util.resources - * @library /java/text/testlib * @summary test TimeZone + * @run junit TimeZoneTest */ import java.io.*; @@ -36,14 +36,14 @@ import java.util.*; import sun.util.resources.LocaleData; -public class TimeZoneTest extends IntlTest +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneTest { static final int millisPerHour = 3600000; - public static void main(String[] args) throws Exception { - new TimeZoneTest().run(args); - } - /** * Bug 4130885 * Certain short zone IDs, used since 1.1.x, are incorrect. @@ -99,6 +99,7 @@ * else. E.g., EST usually indicates the US Eastern zone, so it cannot be * used for Brazil (BET). */ + @Test public void TestShortZoneIDs() throws Exception { ZoneDescriptor[] JDK_116_REFERENCE_LIST = { @@ -153,10 +154,10 @@ ZoneDescriptor referenceZone = JDK_116_REFERENCE_LIST[i]; ZoneDescriptor currentZone = hash.get(referenceZone.getID()); if (referenceZone.equals(currentZone)) { - logln("ok " + referenceZone); + System.out.println("ok " + referenceZone); } else { - errln("Fail: Expected " + referenceZone + + fail("Fail: Expected " + referenceZone + "; got " + currentZone); } } @@ -238,6 +239,7 @@ * ID "Custom" is no longer used for TimeZone objects created with * a custom time zone ID, such as "GMT-8". See 4322313. */ + @Test public void TestCustomParse() throws Exception { Object[] DATA = { // ID Expected offset in minutes @@ -261,7 +263,7 @@ Integer exp = (Integer)DATA[i+1]; TimeZone zone = TimeZone.getTimeZone(id); if (zone.getID().equals("GMT")) { - logln(id + " -> generic GMT"); + System.out.println(id + " -> generic GMT"); // When TimeZone.getTimeZone() can't parse the id, it // returns GMT -- a dubious practice, but required for // backward compatibility. @@ -273,7 +275,7 @@ else { int ioffset = zone.getRawOffset()/60000; String offset = formatMinutes(ioffset); - logln(id + " -> " + zone.getID() + " GMT" + offset); + System.out.println(id + " -> " + zone.getID() + " GMT" + offset); if (exp == null) { throw new Exception("Expected parse failure for " + id + ", got offset of " + offset + @@ -300,12 +302,13 @@ * 4/21/98 - make smarter, so the test works if the ext resources * are present or not. */ + @Test public void TestDisplayName() { TimeZone zone = TimeZone.getTimeZone("PST"); String name = zone.getDisplayName(Locale.ENGLISH); - logln("PST->" + name); + System.out.println("PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); //***************************************************************** // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES @@ -324,7 +327,7 @@ ((Integer)DATA[i+1]).intValue(), Locale.ENGLISH); if (!name.equals(DATA[i+2])) - errln("Fail: Expected " + DATA[i+2] + "; got " + name); + fail("Fail: Expected " + DATA[i+2] + "; got " + name); } // Make sure that we don't display the DST name by constructing a fake @@ -332,11 +335,11 @@ SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST"); zone2.setStartRule(Calendar.JANUARY, 1, 0); zone2.setEndRule(Calendar.DECEMBER, 31, 0); - logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); + System.out.println("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); name = zone2.getDisplayName(Locale.ENGLISH); - logln("Modified PST->" + name); + System.out.println("Modified PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); // Make sure we get the default display format for Locales // with no display name data. @@ -347,7 +350,7 @@ // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES //***************************************************************** - logln("PST(zh_CN)->" + name); + System.out.println("PST(zh_CN)->" + name); // Now be smart -- check to see if zh resource is even present. // If not, we expect the en fallback behavior. @@ -359,9 +362,9 @@ boolean noZH = enRB == zhRB; if (noZH) { - logln("Warning: Not testing the zh_CN behavior because resource is absent"); + System.out.println("Warning: Not testing the zh_CN behavior because resource is absent"); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected Pacific Standard Time"); + fail("Fail: Expected Pacific Standard Time"); } else if (!name.equals("Pacific Standard Time") && !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") && @@ -370,48 +373,49 @@ !name.equals("GMT-8:00") && !name.equals("GMT-0800") && !name.equals("GMT-800")) { - errln("Fail: Expected GMT-08:00 or something similar"); - errln("************************************************************"); - errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED"); - errln("************************************************************"); + fail("Fail: Expected GMT-08:00 or something similar\n" + + "************************************************************\n" + + "THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED\n" + + "************************************************************\n"); } // Now try a non-existent zone zone2 = new SimpleTimeZone(90*60*1000, "xyzzy"); name = zone2.getDisplayName(Locale.ENGLISH); - logln("GMT+90min->" + name); + System.out.println("GMT+90min->" + name); if (!name.equals("GMT+01:30") && !name.equals("GMT+1:30") && !name.equals("GMT+0130") && !name.equals("GMT+130")) - errln("Fail: Expected GMT+01:30 or something similar"); + fail("Fail: Expected GMT+01:30 or something similar"); } + @Test public void TestGenericAPI() { String id = "NewGMT"; int offset = 12345; SimpleTimeZone zone = new SimpleTimeZone(offset, id); if (zone.useDaylightTime()) { - errln("FAIL: useDaylightTime should return false"); + fail("FAIL: useDaylightTime should return false"); } TimeZone zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setID("abc"); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setRawOffset(45678); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } TimeZone saveDefault = TimeZone.getDefault(); @@ -419,10 +423,10 @@ TimeZone.setDefault(zone); TimeZone defaultzone = TimeZone.getDefault(); if (defaultzone == zone) { - errln("FAIL: Default object is identical, not clone"); + fail("FAIL: Default object is identical, not clone"); } if (!defaultzone.equals(zone)) { - errln("FAIL: Default object is not equal"); + fail("FAIL: Default object is not equal"); } } finally { @@ -431,13 +435,14 @@ } @SuppressWarnings("deprecation") + @Test public void TestRuleAPI() { // ErrorCode status = ZERO_ERROR; int offset = (int)(60*60*1000*1.75); // Pick a weird offset SimpleTimeZone zone = new SimpleTimeZone(offset, "TestZone"); - if (zone.useDaylightTime()) errln("FAIL: useDaylightTime should return false"); + if (zone.useDaylightTime()) fail("FAIL: useDaylightTime should return false"); // Establish our expected transition times. Do this with a non-DST // calendar with the (above) declared local offset. @@ -465,18 +470,18 @@ long expMarchOne = 636251400000L; if (marchOne != expMarchOne) { - errln("FAIL: Expected start computed as " + marchOne + + fail("FAIL: Expected start computed as " + marchOne + " = " + new Date(marchOne)); - logln(" Should be " + expMarchOne + + System.out.println(" Should be " + expMarchOne + " = " + new Date(expMarchOne)); } long expJulyOne = 646793100000L; if (julyOne != expJulyOne) { - errln("FAIL: Expected start computed as " + julyOne + + fail("FAIL: Expected start computed as " + julyOne + " = " + new Date(julyOne)); - logln(" Should be " + expJulyOne + + System.out.println(" Should be " + expJulyOne + " = " + new Date(expJulyOne)); } @@ -487,15 +492,15 @@ if (zone.inDaylightTime(new Date(marchOne - 1000)) || !zone.inDaylightTime(new Date(marchOne))) - errln("FAIL: Start rule broken"); + fail("FAIL: Start rule broken"); if (!zone.inDaylightTime(new Date(julyOne - 1000)) || zone.inDaylightTime(new Date(julyOne))) - errln("FAIL: End rule broken"); + fail("FAIL: End rule broken"); zone.setStartYear(1991); if (zone.inDaylightTime(new Date(marchOne)) || zone.inDaylightTime(new Date(julyOne - 1000))) - errln("FAIL: Start year broken"); + fail("FAIL: Start year broken"); // failure(status, "TestRuleAPI"); // delete gc; @@ -508,7 +513,7 @@ boolean startsInDST = tz.inDaylightTime(new Date(min)); // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); return; } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; @@ -522,52 +527,54 @@ } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; } - logln("Binary Search Before: " + min + " = " + new Date(min)); - logln("Binary Search After: " + max + " = " + new Date(max)); + System.out.println("Binary Search Before: " + min + " = " + new Date(min)); + System.out.println("Binary Search After: " + max + " = " + new Date(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + System.out.println("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); else - errln("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + fail("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); } static final int INTERVAL = 100; // Bug 006; verify the offset for a specific zone. + @Test public void TestPRTOffset() { TimeZone tz = TimeZone.getTimeZone( "PRT" ); if( tz == null ) { - errln( "FAIL: TimeZone(PRT) is null" ); + fail( "FAIL: TimeZone(PRT) is null" ); } else{ if (tz.getRawOffset() != (-4*millisPerHour)) - errln("FAIL: Offset for PRT should be -4"); + fail("FAIL: Offset for PRT should be -4"); } } // Test various calls @SuppressWarnings("deprecation") + @Test public void TestVariousAPI518() { TimeZone time_zone = TimeZone.getTimeZone("PST"); Date d = new Date(97, Calendar.APRIL, 30); - logln("The timezone is " + time_zone.getID()); + System.out.println("The timezone is " + time_zone.getID()); if (time_zone.inDaylightTime(d) != true) - errln("FAIL: inDaylightTime returned false"); + fail("FAIL: inDaylightTime returned false"); if (time_zone.useDaylightTime() != true) - errln("FAIL: useDaylightTime returned false"); + fail("FAIL: useDaylightTime returned false"); if (time_zone.getRawOffset() != -8*millisPerHour) - errln( "FAIL: getRawOffset returned wrong value"); + fail( "FAIL: getRawOffset returned wrong value"); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(d); @@ -575,10 +582,11 @@ gc.get(gc.DAY_OF_MONTH), gc.get(gc.DAY_OF_WEEK), 0) != -7*millisPerHour) - errln("FAIL: getOffset returned wrong value"); + fail("FAIL: getOffset returned wrong value"); } // Test getAvailableID API + @Test public void TestGetAvailableIDs913() { StringBuffer buf = new StringBuffer("TimeZone.getAvailableIDs() = { "); @@ -589,7 +597,7 @@ buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); buf.setLength(0); buf.append("TimeZone.getAvailableIDs(GMT+02:00) = { "); @@ -600,31 +608,32 @@ buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); TimeZone tz = TimeZone.getTimeZone("PST"); if (tz != null) - logln("getTimeZone(PST) = " + tz.getID()); + System.out.println("getTimeZone(PST) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); tz = TimeZone.getTimeZone("America/Los_Angeles"); if (tz != null) - logln("getTimeZone(America/Los_Angeles) = " + tz.getID()); + System.out.println("getTimeZone(America/Los_Angeles) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); // Bug 4096694 tz = TimeZone.getTimeZone("NON_EXISTENT"); if (tz == null) - errln("FAIL: getTimeZone(NON_EXISTENT) = null"); + fail("FAIL: getTimeZone(NON_EXISTENT) = null"); else if (!tz.getID().equals("GMT")) - errln("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); + fail("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); } /** * Bug 4107276 */ + @Test public void TestDSTSavings() { // It might be better to find a way to integrate this test into the main TimeZone // tests above, but I don't have time to figure out how to do this (or if it's @@ -634,43 +643,44 @@ (int)(0.5 * millisPerHour)); if (tz.getRawOffset() != -5 * millisPerHour) - errln("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + + fail("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + " hours instead of -5 hours."); if (!tz.useDaylightTime()) - errln("Test time zone should use DST but claims it doesn't."); + fail("Test time zone should use DST but claims it doesn't."); if (tz.getDSTSavings() != 0.5 * millisPerHour) - errln("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / + fail("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / millisPerHour) + " hours instead."); int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4.5 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + fail("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + (offset / millisPerHour) + " hours."); tz.setDSTSavings(millisPerHour); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + fail("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); } /** * Bug 4107570 */ + @Test public void TestAlternateRules() { // Like TestDSTSavings, this test should probably be integrated somehow with the main // test at the top of this class, but I didn't have time to figure out how to do that. @@ -685,25 +695,25 @@ int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 5, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 15, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 25, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); // test the day-of-week-after-day-in-month API @@ -713,25 +723,25 @@ offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 11, Calendar.WEDNESDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 14, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 17, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TransitionTest.java openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TransitionTest.java --- openjdk-17-17.0.14+7/test/jdk/java/util/TimeZone/TransitionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/TimeZone/TransitionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,8 +24,8 @@ /* * @test * @bug 4278609 4761696 - * @library /java/text/testlib * @summary Make sure to handle DST transition ending at 0:00 January 1. + * @run junit TransitionTest */ import java.text.SimpleDateFormat; @@ -36,12 +36,13 @@ import java.util.SimpleTimeZone; import java.util.TimeZone; -public class TransitionTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TransitionTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TransitionTest { + @Test public void Test4278609() { SimpleTimeZone tz = new SimpleTimeZone(0, "MyTimeZone", /* DST start day: August, 1, 0:00 */ @@ -77,7 +78,7 @@ SimpleDateFormat format = new SimpleDateFormat("dd MMM HH:mm:ss zzz", Locale.US); format.setTimeZone(tz); - errln("Wrong DST transition: " + tz + fail("Wrong DST transition: " + tz + "\na date just after DST = " + format.format(date) + "\ngetOffset = " + offset); } @@ -88,6 +89,7 @@ * * Derived from JCK test cases some of which specify wrong day of week values. */ + @Test public void Test4761696() { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); @@ -121,7 +123,7 @@ long endTime = cal.getTimeInMillis() + rawOffset; long expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#1: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#1: wrong offset: got "+offset+", expected="+expectedOffset); } // test#2 @@ -150,7 +152,7 @@ endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("Wrong offset: got "+offset+", expected="+expectedOffset); + fail("Wrong offset: got "+offset+", expected="+expectedOffset); } rawOffset = 43200000; @@ -179,7 +181,7 @@ endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#2: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#2: wrong offset: got "+offset+", expected="+expectedOffset); } // test#3 @@ -209,7 +211,7 @@ endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#3: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#3: wrong offset: got "+offset+", expected="+expectedOffset); } // test#4 @@ -243,7 +245,7 @@ long startTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime >= startTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#4: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#4: wrong offset: got "+offset+", expected="+expectedOffset); } // test#5 @@ -272,7 +274,7 @@ endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#5: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#5: wrong offset: got "+offset+", expected="+expectedOffset); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/logging/LoggingDeadlock2.java openjdk-17-17.0.15+6/test/jdk/java/util/logging/LoggingDeadlock2.java --- openjdk-17-17.0.14+7/test/jdk/java/util/logging/LoggingDeadlock2.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/logging/LoggingDeadlock2.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,12 @@ * @test * @bug 6467152 6716076 6829503 8132550 * @summary deadlock occurs in LogManager initialization and JVM termination + * @key randomness + * @library /test/lib * @author Serguei Spitsyn / Hitachi / Martin Buchholz * * @build LoggingDeadlock2 * @run main LoggingDeadlock2 - * @key randomness */ /* @@ -50,7 +51,6 @@ * This is a regression test for this bug. */ -import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.CyclicBarrier; @@ -63,6 +63,8 @@ import java.io.Reader; import java.util.concurrent.TimeUnit; +import jdk.test.lib.process.ProcessTools; + public class LoggingDeadlock2 { // ask child process to dumpstack after 60secs @@ -74,7 +76,9 @@ public static void realMain(String arg[]) throws Throwable { try { System.out.println(javaChildArgs); - ProcessBuilder pb = new ProcessBuilder(javaChildArgs); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + javaChildArgs); ProcessResults r = run(pb.start()); equal(r.exitValue(), 99); @@ -151,9 +155,6 @@ //---------------------------------------------------------------- // The rest of this test is copied from ProcessBuilder/Basic.java //---------------------------------------------------------------- - private static final String javaExe = - System.getProperty("java.home") + - File.separator + "bin" + File.separator + "java"; private static final String jstackExe = System.getProperty("java.home") + File.separator + "bin" + File.separator + "jstack"; @@ -161,10 +162,8 @@ private static final String classpath = System.getProperty("java.class.path"); - private static final List javaChildArgs = - Arrays.asList(new String[] - { javaExe, "-classpath", classpath, - "LoggingDeadlock2$JavaChild"}); + private static final List javaChildArgs = List.of( + "-classpath", classpath, "LoggingDeadlock2$JavaChild"); private static class ProcessResults { private final String out; diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/zip/Available.java openjdk-17-17.0.15+6/test/jdk/java/util/zip/Available.java --- openjdk-17-17.0.14+7/test/jdk/java/util/zip/Available.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/zip/Available.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,69 +22,136 @@ */ /* @test - @bug 4028605 4109069 4234207 4401122 - @summary Make sure ZipInputStream/InflaterInputStream.available() will - return 0 after EOF has reached and 1 otherwise. - */ + * @bug 4028605 4109069 4234207 4401122 8339154 + * @summary Verify that ZipInputStream, InflaterInputStream, ZipFileInputStream, + * ZipFileInflaterInputStream.available() return values according + * to their specification or long-standing behavior + * @run junit Available + */ +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.zip.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class Available { - public static void main(String[] args) throws Exception { - // 4028605 4109069 4234207 - test1(); - // test 4401122 - test2(); + // ZIP file produced in this test + private final Path zip = Path.of("available.jar"); + + /** + * Create the ZIP file used in this test, containing + * one deflated and one stored entry. + * + * @throws IOException if an unexpected error occurs + */ + @BeforeEach + public void setup() throws IOException { + byte[] contents = "contents".repeat(10).getBytes(StandardCharsets.UTF_8); + + try (ZipOutputStream zo = new ZipOutputStream(Files.newOutputStream(zip))) { + // First entry uses DEFLATE method + zo.putNextEntry(new ZipEntry("deflated.txt")); + zo.write(contents); + + // Second entry uses STORED method + ZipEntry stored = new ZipEntry("stored.txt"); + stored.setMethod(ZipEntry.STORED); + stored.setSize(contents.length); + CRC32 crc32 = new CRC32(); + crc32.update(contents); + stored.setCrc(crc32.getValue()); + zo.putNextEntry(stored); + zo.write(contents); + } } - private static void test1() throws Exception { - File f = new File(System.getProperty("test.src", "."), "input.jar"); + /** + * Delete the ZIP file created by this test + * + * @throws IOException if an unexpected error occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } - // test ZipInputStream - try (FileInputStream fis = new FileInputStream(f); - ZipInputStream z = new ZipInputStream(fis)) - { + /** + * Verify that ZipInputStream.available() returns 0 after EOF or + * closeEntry, otherwise 1, as specified in the API description. + * This tests 4028605 4109069 4234207 + * @throws IOException if an unexpected error occurs + */ + @Test + public void testZipInputStream() throws IOException { + try (InputStream in = Files.newInputStream(zip)) { + ZipInputStream z = new ZipInputStream(in); z.getNextEntry(); - tryAvail(z); - } - - // test InflaterInputStream - try (ZipFile zfile = new ZipFile(f)) { - tryAvail(zfile.getInputStream(zfile.getEntry("Available.java"))); + assertEquals(1, z.available()); + z.read(); + assertEquals(1, z.available()); + z.transferTo(OutputStream.nullOutputStream()); + assertEquals(0, z.available(), + "ZipInputStream.available() should return 0 after EOF"); + + z.close(); + assertThrows(IOException.class, () -> z.available(), + "Expected an IOException when calling available on a closed stream"); } - } - static void tryAvail(InputStream in) throws Exception { - byte[] buf = new byte[1024]; - int n; - - while ((n = in.read(buf)) != -1); - if (in.available() != 0) { - throw new Exception("available should return 0 after EOF"); + try (InputStream in = Files.newInputStream(zip); + ZipInputStream z = new ZipInputStream(in)) { + z.getNextEntry(); + z.closeEntry(); + assertEquals(0, z.available(), + "ZipInputStream.available() should return 0 after closeEntry"); } } - // To reproduce 4401122 - private static void test2() throws Exception { - File f = new File(System.getProperty("test.src", "."), "input.jar"); - try (ZipFile zf = new ZipFile(f)) { - InputStream in = zf.getInputStream(zf.getEntry("Available.java")); + /** + * Verify that ZipFileInputStream|ZipFileInflaterInputStream.available() + * return the number of remaining uncompressed bytes. + * + * This verifies unspecified, but long-standing behavior. See 4401122. + * + * @throws IOException if an unexpected error occurs + */ + @ParameterizedTest + @ValueSource(strings = { "stored.txt", "deflated.txt" }) + public void testZipFileStreamsRemainingBytes(String entryName) throws IOException { + try (ZipFile zfile = new ZipFile(zip.toFile())) { + ZipEntry entry = zfile.getEntry(entryName); + // Could be ZipFileInputStream or ZipFileInflaterInputStream + InputStream in = zfile.getInputStream(entry); int initialAvailable = in.available(); - in.read(); - if (in.available() != initialAvailable - 1) - throw new RuntimeException("Available not decremented."); - for(int j=0; j 0; i--) { + // Reading a single byte should decrement available by 1 in.read(); - if (in.available() != 0) - throw new RuntimeException(); + assertEquals(i - 1, in.available(), "Available not decremented"); + } + + // No remaining uncompressed bytes + assertEquals(0, in.available()); + + // available() should still return 0 after close in.close(); - if (in.available() != 0) - throw new RuntimeException(); + assertEquals(0, in.available()); } } - } diff -Nru openjdk-17-17.0.14+7/test/jdk/java/util/zip/EntryCount64k.java openjdk-17-17.0.15+6/test/jdk/java/util/zip/EntryCount64k.java --- openjdk-17-17.0.14+7/test/jdk/java/util/zip/EntryCount64k.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/java/util/zip/EntryCount64k.java 2025-04-09 19:45:33.000000000 +0000 @@ -37,7 +37,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; -import java.nio.file.Paths; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -161,11 +160,7 @@ } // Check java -jar - String javaHome = System.getProperty("java.home"); - String java = Paths.get(javaHome, "bin", "java").toString(); - String[] cmd = { java, "-jar", zipFile.getName() }; - ProcessBuilder pb = new ProcessBuilder(cmd); - OutputAnalyzer a = ProcessTools.executeProcess(pb); + OutputAnalyzer a = ProcessTools.executeTestJvm("-jar", zipFile.getName()); a.shouldHaveExitValue(0); a.stdoutShouldMatch("\\AMain\\Z"); a.stderrShouldMatch("\\A\\Z"); diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java --- openjdk-17-17.0.14+7/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8283404 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @requires (os.family == "mac") + * @summary Verifies if JMenu accessibility label magnifies using + * screen magnifier a11y tool. + * @run main/manual TestJMenuScreenMagnifier + */ + +import java.lang.reflect.InvocationTargetException; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; + +public class TestJMenuScreenMagnifier { + private static JFrame frame; + private static final String INSTRUCTIONS = + "1) Enable Screen magnifier on theMac \n\n" + + "System Preference -> Accessibility -> Zoom -> " + + "Select ( Enable Hover Text) \n\n" + + "2) Move the mouse over the \"File\" or \"Edit\" menu by pressing " + + "\"cmd\" button.\n\n" + + "3) If magnified label is visible, Press Pass else Fail."; + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame passFailJFrame = new PassFailJFrame( + "JMenu Screen Magnifier Test Instructions", INSTRUCTIONS, 5, 12, 40); + try { + SwingUtilities.invokeAndWait( + TestJMenuScreenMagnifier::createAndShowUI); + passFailJFrame.awaitAndCheck(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + private static void createAndShowUI() { + frame = new JFrame("JMenu A11Y Screen Magnifier Test"); + + JMenu file = new JMenu("File"); + file.getAccessibleContext().setAccessibleName("File Menu"); + + JMenuItem open = new JMenuItem("Open"); + open.getAccessibleContext().setAccessibleName("Open MenuItem"); + + JMenuItem quit = new JMenuItem("Quit"); + quit.getAccessibleContext().setAccessibleName("Quit MenuItem"); + + file.add(open); + file.add(quit); + + JMenu edit = new JMenu("Edit"); + edit.getAccessibleContext().setAccessibleName("Edit Menu"); + + JMenuItem cut = new JMenuItem("Cut"); + cut.getAccessibleContext().setAccessibleName("Cut MenuItem"); + + edit.add(cut); + + JMenuBar jMenuBar = new JMenuBar(); + + jMenuBar.add(file); + jMenuBar.add(edit); + + + PassFailJFrame.addTestWindow(frame); + PassFailJFrame.positionTestWindow(frame, + PassFailJFrame.Position.HORIZONTAL); + frame.setJMenuBar(jMenuBar); + frame.setSize(300, 100); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.accessibility.AccessibleValue; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +/** + * @test + * @bug 8283387 + * @summary [macos] a11y : Screen magnifier does not show selected Tab + * JTabbedPane accessible children had no AccessibleValue manipulation API + * Testing this API since it was added in the fix for 8283387 + * @run main AccessibleTabbedPaneTest + */ + +public class AccessibleTabbedPaneTest { + public static void main(String[] args) { + JTabbedPane pane = new JTabbedPane(); + JPanel p1, p2, p3; + p1 = new JPanel(); + p2 = new JPanel(); + p3 = new JPanel(); + pane.add("One", p1); + pane.add("Two", p2); + pane.add("Three", p3); + for (int i = 0; i < pane.getAccessibleContext().getAccessibleChildrenCount(); i++) { + if (pane.getAccessibleContext() + .getAccessibleChild(i) + .getAccessibleContext() + .getAccessibleValue() == null) { + throw new RuntimeException("Test failed, accessible value for tab "+ i + " is null"); + } + } + AccessibleValue p2a = pane.getAccessibleContext() + .getAccessibleChild(1) + .getAccessibleContext() + .getAccessibleValue(); + // Select second tab using a11y API. + if (p2a.setCurrentAccessibleValue(1)) { + if (pane.getSelectedIndex() != 1) { + throw new RuntimeException("Can not change tab selection using a11y API"); + } + } + + // Try to deselect it - that should not be allowed + if (p2a.setCurrentAccessibleValue(0)) { + throw new RuntimeException("We should not be able to deselect " + + "currently selected tab via a11y API"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/accessibility/TestJMenuItemShortcutAccessibility.java openjdk-17-17.0.15+6/test/jdk/javax/accessibility/TestJMenuItemShortcutAccessibility.java --- openjdk-17-17.0.14+7/test/jdk/javax/accessibility/TestJMenuItemShortcutAccessibility.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/accessibility/TestJMenuItemShortcutAccessibility.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.KeyStroke; + +/* + * @test + * @bug 8339728 + * @summary Tests that JAWS announce the shortcuts for JMenuItems. + * @requires os.family == "windows" + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestJMenuItemShortcutAccessibility + */ + +public class TestJMenuItemShortcutAccessibility { + public static void main(String[] args) throws Exception { + String INSTRUCTIONS = """ + 1. Start the JAWS application + 2. Press Alt + M to open application Menu + 3. Navigate the Menu Items by using UP / DOWN arrow key + 4. Press Pass if you are able to hear correct JAWS announcements + (JAWS should read full shortcut text and not only the 1st + character of shortcut text for each menu item) else Fail + """; + + PassFailJFrame.builder() + .title("TestJMenuItemShortcutAccessibility Instruction") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(TestJMenuItemShortcutAccessibility::createUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createUI() { + JFrame frame = new JFrame("A Frame with Menu"); + + JMenuBar menuBar = new JMenuBar(); + JMenu menu = new JMenu("Menu with shortcuts"); + menu.setMnemonic(KeyEvent.VK_M); + menuBar.add(menu); + + KeyStroke keyStroke1 = KeyStroke.getKeyStroke(KeyEvent.VK_F, + InputEvent.CTRL_DOWN_MASK); + KeyStroke keyStroke2 = KeyStroke.getKeyStroke(KeyEvent.VK_2, + InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK); + KeyStroke keyStroke3 = KeyStroke.getKeyStroke(KeyEvent.VK_F1, + InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK); + KeyStroke keyStroke4 = KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, + InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK); + KeyStroke keyStroke5 = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, + InputEvent.CTRL_DOWN_MASK | InputEvent.ALT_DOWN_MASK); + KeyStroke keyStroke6 = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, + InputEvent.CTRL_DOWN_MASK); + KeyStroke keyStroke7 = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, + InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK); + + JMenuItem menuItem1 = new JMenuItem("First Menu Item"); + menuItem1.setAccelerator(keyStroke1); + JMenuItem menuItem2 = new JMenuItem("Second Menu Item"); + menuItem2.setAccelerator(keyStroke2); + JMenuItem menuItem3 = new JMenuItem("Third Menu Item"); + menuItem3.setAccelerator(keyStroke3); + JMenuItem menuItem4 = new JMenuItem("Fourth Menu Item"); + menuItem4.setAccelerator(keyStroke4); + JMenuItem menuItem5 = new JMenuItem("Fifth Menu Item"); + menuItem5.setAccelerator(keyStroke5); + JMenuItem menuItem6 = new JMenuItem("Sixth Menu Item"); + menuItem6.setAccelerator(keyStroke6); + JMenuItem menuItem7 = new JMenuItem("Seventh Menu Item"); + menuItem7.setAccelerator(keyStroke7); + + menu.add(menuItem1); + menu.add(menuItem2); + menu.add(menuItem3); + menu.add(menuItem4); + menu.add(menuItem5); + menu.add(menuItem6); + menu.add(menuItem7); + + frame.setJMenuBar(menuBar); + frame.setSize(300, 200); + return frame; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java --- openjdk-17-17.0.14+7/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8286779 + * @summary Test limited/default_local.policy containing inconsistent entries + * @library /test/lib + * @run testng/othervm InconsistentEntries + */ + +import org.testng.Assert; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import javax.crypto.*; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.Security; + +public class InconsistentEntries { + + private static final String JDK_HOME = System.getProperty("test.jdk"); + private static final String TEST_SRC = System.getProperty("test.src"); + private static final Path POLICY_DIR = Paths.get(JDK_HOME, "conf", "security", + "policy", "testlimited"); + private static final Path POLICY_FILE = Paths.get(TEST_SRC, "default_local.policy"); + + Path targetFile = null; + + @BeforeTest + public void setUp() throws IOException { + if (!POLICY_DIR.toFile().exists()) { + Files.createDirectory(POLICY_DIR); + } + + targetFile = POLICY_DIR.resolve(POLICY_FILE.getFileName()); + Files.copy(POLICY_FILE, targetFile, StandardCopyOption.REPLACE_EXISTING); + } + + @AfterTest + public void cleanUp() throws IOException { + Files.delete(targetFile); + } + + @Test + public void test() throws Exception { + String JAVA_HOME = System.getProperty("java.home"); + String FS = System.getProperty("file.separator"); + Path testlimited = Path.of(JAVA_HOME + FS + "conf" + FS + "security" + + FS + "policy" + FS + "testlimited"); + if (!Files.exists(testlimited)) { + throw new RuntimeException( + "custom policy subdirectory: testlimited does not exist"); + } + + File testpolicy = new File(JAVA_HOME + FS + "conf" + FS + "security" + + FS + "policy" + FS + "testlimited" + FS + "default_local.policy"); + if (testpolicy.length() == 0) { + throw new RuntimeException( + "policy: default_local.policy does not exist or is empty"); + } + + Security.setProperty("crypto.policy", "testlimited"); + + Assert.assertThrows(ExceptionInInitializerError.class, + () -> Cipher.getMaxAllowedKeyLength("AES")); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/crypto/CryptoPermissions/default_local.policy openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/default_local.policy --- openjdk-17-17.0.14+7/test/jdk/javax/crypto/CryptoPermissions/default_local.policy 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/crypto/CryptoPermissions/default_local.policy 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,4 @@ +grant { + permission javax.crypto.CryptoAllPermission; + permission javax.crypto.CryptoPermission "DES", 64; +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/imageio/plugins/jpeg/LargeAdobeMarkerSegmentTest.java openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/jpeg/LargeAdobeMarkerSegmentTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/imageio/plugins/jpeg/LargeAdobeMarkerSegmentTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/jpeg/LargeAdobeMarkerSegmentTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,59 @@ +/* + * Copyright 2023 Alphabet LLC. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6355567 + * @summary Verifies that AdobeMarkerSegment() keeps the available bytes + * and buffer pointer in sync, when a non-standard length Adobe + * marker is encountered. + */ + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.stream.ImageInputStream; + +public class LargeAdobeMarkerSegmentTest { + + private static String fileName = "jdk_6355567.jpg"; + + public static void main(String[] args) throws IOException { + /* + * Open a JPEG image, and get the metadata. Without the fix for + * 6355567, a NegativeArraySizeException is thrown while reading + * the metadata from the JPEG below. + */ + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + String filePath = dir+sep+fileName; + System.out.println("Test file: " + filePath); + File f = new File(filePath); + ImageInputStream iis = ImageIO.createImageInputStream(f); + ImageReader r = ImageIO.getImageReaders(iis).next(); + r.setInput(iis); + r.getImageMetadata(0); + } +} Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/javax/imageio/plugins/jpeg/jdk_6355567.jpg and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/jpeg/jdk_6355567.jpg differ diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/imageio/plugins/wbmp/WBMPStreamTruncateTest.java openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/wbmp/WBMPStreamTruncateTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/imageio/plugins/wbmp/WBMPStreamTruncateTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/imageio/plugins/wbmp/WBMPStreamTruncateTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8266435 + * @summary Test verifies that WBMPImageReader doesnt truncate + * the stream and reads it fully + * @run main WBMPStreamTruncateTest + */ + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.RandomAccessFile; +import javax.imageio.ImageIO; +import javax.imageio.stream.ImageInputStreamImpl; + +public class WBMPStreamTruncateTest +{ + static final int LIMIT = 100; + static final int width = 100; + static final int height = 100; + public static void main(String[] args) throws IOException + { + BufferedImage srcImage = new + BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); + Graphics2D g = (Graphics2D) srcImage.getGraphics(); + g.setBackground(Color.WHITE); + g.fillRect(0, 0, srcImage.getWidth(), srcImage.getHeight()); + g.dispose(); + // create WBMP image + File imageFile = File. + createTempFile("test", ".wbmp", new File("./")); + imageFile.deleteOnExit(); + ImageIO.write(srcImage, "wbmp", imageFile); + BufferedImage testImg = + ImageIO.read(new LimitedImageInputStream(imageFile, LIMIT)); + for (int x = 0; x < testImg.getWidth(); ++x) + { + for (int y = 0; y < testImg.getHeight(); ++y) + { + int i1 = testImg.getRGB(x, y); + int i2 = srcImage.getRGB(x, y); + if (i1 != i2) + { + throw new RuntimeException("Stream is decoded only until " + + "the limit specified"); + } + } + } + } + + static class LimitedImageInputStream extends ImageInputStreamImpl + { + private final RandomAccessFile raf; + private final int limit; + + public LimitedImageInputStream(File file, int limit) + throws FileNotFoundException + { + raf = new RandomAccessFile(file, "r"); + this.limit = limit; + } + + @Override + public int read() throws IOException + { + return raf.read(); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException + { + return raf.read(b, off, Math.min(limit, len)); + } + + @Override + public void close() throws IOException + { + super.close(); + raf.close(); + } + + @Override + public void seek(long pos) throws IOException + { + super.seek(pos); + raf.seek(pos); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/management/MBeanServer/ExceptionTest.java openjdk-17-17.0.15+6/test/jdk/javax/management/MBeanServer/ExceptionTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/management/MBeanServer/ExceptionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/management/MBeanServer/ExceptionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -123,10 +123,13 @@ } finally { try { // Close JMX Connector Client - cc.close(); + if (cc != null) { + cc.close(); + } // Stop connertor server - cs.stop(); - + if (cs != null) { + cs.stop(); + } } catch (Exception e) { Utils.printThrowable(e, true); throw new RuntimeException( diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,10 @@ * @summary test on a client notification deadlock. * @author Shanliang JIANG * + * @requires vm.compMode != "Xcomp" + * @comment Running with -Xcomp is likely to cause a timeout while establishing the connection + * (RMI: java.rmi.NoSuchObjectException: no such object in table). + * * @run clean DeadLockTest * @run build DeadLockTest * @run main DeadLockTest @@ -46,21 +50,23 @@ public static void main(String[] args) { System.out.println(">>> test on a client notification deadlock."); - boolean ok = true; + boolean fail = false; for (int i = 0; i < protocols.length; i++) { try { test(protocols[i]); } catch (Exception e) { + fail = true; // any one protocol failure, fails the test System.out.println(">>> Test failed for " + protocols[i]); e.printStackTrace(System.out); } } - + if (fail) { + throw new RuntimeException("FAILED"); + } System.out.println(">>> Test passed"); } - private static void test(String proto) - throws Exception { + private static void test(String proto) throws Exception { System.out.println(">>> Test for protocol " + proto); JMXServiceURL u = null; @@ -78,6 +84,7 @@ server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs); } catch (MalformedURLException e) { System.out.println(">>> Skipping unsupported URL " + proto); + return; // skip testing this protocol } server.start(); @@ -101,10 +108,10 @@ // which should be closed by the server. conn.getDefaultDomain(); - // allow the listner to have time to work + // allow the listener to have time to work Thread.sleep(100); - // get a closed notif, should no block. + // get a closed notif, should not block. client.close(); Thread.sleep(100); @@ -136,7 +143,7 @@ try { conn.getDefaultDomain(); } catch (IOException ioe) { - // Greate ! + // OK } synchronized(this) { diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,9 @@ * @bug 6199899 * @summary Tests reconnection done by a fetching notif thread. * @author Shanliang JIANG + * @requires vm.compMode != "Xcomp" + * @comment Running with -Xcomp is likely to cause a timeout from ServerCommunicatorAdmin + * before addNotificationListener can complete. * * @run clean NotifReconnectDeadlockTest * @run build NotifReconnectDeadlockTest diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/management/security/HashedPasswordFileTest.java openjdk-17-17.0.15+6/test/jdk/javax/management/security/HashedPasswordFileTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/management/security/HashedPasswordFileTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/management/security/HashedPasswordFileTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -200,6 +200,12 @@ return cs.getAddress(); } + private void stopServerSide() throws IOException { + if (cs != null) { + cs.stop(); + } + } + @Test public void testClearTextPasswordFile() throws IOException { Boolean[] bvals = new Boolean[]{true, false}; @@ -217,7 +223,7 @@ } Assert.assertEquals(isPasswordFileHashed(), bval); } finally { - cs.stop(); + stopServerSide(); } } } @@ -241,7 +247,7 @@ } Assert.assertEquals(isPasswordFileHashed(), false); } finally { - cs.stop(); + stopServerSide(); } } } @@ -263,7 +269,7 @@ } } } finally { - cs.stop(); + stopServerSide(); } } } @@ -400,7 +406,7 @@ } } } finally { - cs.stop(); + stopServerSide(); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/net/ssl/DTLS/TEST.properties openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/DTLS/TEST.properties --- openjdk-17-17.0.14+7/test/jdk/javax/net/ssl/DTLS/TEST.properties 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/DTLS/TEST.properties 2025-04-09 19:45:33.000000000 +0000 @@ -6,3 +6,4 @@ java.security.jgss/sun.security.krb5.internal:+open \ java.security.jgss/sun.security.krb5.internal.ktab \ java.base/sun.security.util +maxOutputSize = 2500000 diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java --- openjdk-17-17.0.14+7/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java 2025-04-09 19:45:33.000000000 +0000 @@ -72,6 +72,10 @@ sslOS.write(appData); sslOS.flush(); + int drained = 1; + while (drained < appData.length) { + drained += sslIS.read(appData, drained, appData.length - drained); + } } /* diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractButton/bug4290656.java openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractButton/bug4290656.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractButton/bug4290656.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractButton/bug4290656.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4290656 + * @summary Tests if custom AbstractButton implementation fails with Metal L&F + * @key headful + */ + +import java.awt.BorderLayout; +import java.awt.Graphics; +import java.awt.Robot; +import javax.swing.AbstractButton; +import javax.swing.DefaultButtonModel; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.ButtonUI; + +public class bug4290656 { + static JFrame f; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4290656"); + try { + UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel()); + } catch (Exception e) { + throw new RuntimeException("Failed to set metal L&F."); + } + + MyCustomButton button = new MyCustomButton(); + MyCustomToggleButton toggleButton = new MyCustomToggleButton(); + f.getContentPane().add(button, BorderLayout.NORTH); + f.getContentPane().add(toggleButton, BorderLayout.SOUTH); + + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } +} + +class MyCustomButton extends AbstractButton { + private static final String uiClassID = "ButtonUI"; + + public MyCustomButton() { + setModel(new DefaultButtonModel()); + init(null, null); + } + + public void updateUI() { + setUI((ButtonUI) UIManager.getUI(this)); + } + + public String getUIClassID() { + return uiClassID; + } + + protected void paintBorder(Graphics g) { + super.paintBorder(g); + } +} + +class MyCustomToggleButton extends AbstractButton { + private static final String uiClassID = "ToggleButtonUI"; + + public MyCustomToggleButton() { + setModel(new DefaultButtonModel()); + init(null, null); + } + + public void updateUI() { + setUI((ButtonUI) UIManager.getUI(this)); + } + + public String getUIClassID() { + return uiClassID; + } + + protected void paintBorder(Graphics g) { + super.paintBorder(g); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractDocument/bug4549069.java openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractDocument/bug4549069.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractDocument/bug4549069.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractDocument/bug4549069.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4549069 + * @summary Tests if javax.swing.text.AbstractDocument.BranchElement.getEndOffset() throws AIOOBE + * @key headful + */ + +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Timer; +import java.util.TimerTask; +import javax.swing.JFrame; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.undo.UndoManager; + +public class bug4549069 { + static Timer timer; + static volatile Point p; + + static JFrame f; + static JTextArea jta; + static UndoManager um; + static Robot robot; + + public static void main(String[] argv) throws Exception { + robot = new Robot(); + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4549069"); + f.addWindowListener(new TestStateListener()); + + jta = new JTextArea(); + um = new UndoManager(); + jta.setDocument(new DefaultStyledDocument()); + jta.getDocument().addUndoableEditListener(um); + + String text = "Press Ctrl-Z (undo) to get\n" + + "a stacktrace U shouldn't XX\n"; + jta.setText(text); + + jta.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (um.canUndo()) { + um.undo(); + } + } + }); + + f.getContentPane().add(jta); + f.pack(); + f.setVisible(true); + }); + + robot.waitForIdle(); + robot.delay(1000); + } finally { + if (f != null) { + SwingUtilities.invokeAndWait(() -> { + f.dispose(); + }); + } + } + } + + static class TestStateListener extends WindowAdapter { + public void windowOpened(WindowEvent ev) { + timer = new Timer(); + timer.schedule(new RobotTask(), 1000); + } + } + + static class RobotTask extends TimerTask { + public void run() { + try { + SwingUtilities.invokeAndWait(() -> { + p = jta.getLocationOnScreen(); + }); + } catch (Exception e) { + throw new RuntimeException("Could not get location"); + + } + robot.mouseMove(p.x, p.y); + robot.waitForIdle(); + + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_SPACE); + robot.keyRelease(KeyEvent.VK_SPACE); + robot.waitForIdle(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractWriter/bug4185537.java openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractWriter/bug4185537.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/AbstractWriter/bug4185537.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/AbstractWriter/bug4185537.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4185537 + * @summary javax.swing.text.AbstractWriter: TOTAL REWRITE COMPLETE. + */ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import javax.swing.text.AbstractWriter; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.Document; + +public class bug4185537 { + static char[] chars = {'a', 'b', 'c', 'd', 'e'}; + static StringWriter wr = new StringWriter(); + + public static void main(String[] argv) { + DefaultStyledDocument doc = new DefaultStyledDocument(); + + SimpleWriter sw = new SimpleWriter(wr, doc, 5, 200); + sw.test_getWriter(); + + if (sw.getStartOffset() != 5) { + throw new RuntimeException("getStartOffset fails..."); + } + if (sw.getEndOffset() != 205) { + throw new RuntimeException("getEndOffset fails..."); + } + + sw.setLineSeparator("+"); + if (!sw.getLineSeparator().equals("+")) { + throw new RuntimeException("Doesn't set line separator correctly..."); + } + sw.test_writeLineSeparator(); + + sw.test_write_output(); + sw.test_CurrentLineLength(); + sw.test_getLineLength(); + sw.test_getIndentLevel(); + sw.test_CanWrapLines(); + if (!wr.toString().equals("+abcde")) { + throw new RuntimeException("Test fails..."); + } + try { + wr.close(); + } catch (Exception e) { + System.out.println("Exception..."); + } + } + + static class SimpleWriter extends AbstractWriter { + + public SimpleWriter(Writer w, Document d, int pos, int len) { + super(w, d, pos, len); + } + + void test_writeLineSeparator() { + try { + writeLineSeparator(); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("writeLineSeparator fails..."); + } + } + + void test_getWriter() { + if (getWriter() != wr) throw new RuntimeException("Writer gets incorrect..."); + } + + void test_CurrentLineLength() { + setCurrentLineLength(0); + if (getCurrentLineLength() != 0) throw new RuntimeException("Doesn't set CurrentLineLength..."); + if (!isLineEmpty()) { + throw new RuntimeException("isLineEmpty() should return false..."); + } + } + + void test_getLineLength() { + setLineLength(80); + if (getLineLength() != 80) { + throw new RuntimeException("Default line length doesn't set..."); + } + } + + void test_CanWrapLines() { + setCanWrapLines(true); + if (!getCanWrapLines()) { + throw new RuntimeException("Doesn't set wrapping lines correctly"); + } + } + + void test_getIndentLevel() { + incrIndent(); + if (getIndentLevel() != 1) { + throw new RuntimeException("getIndentLevel() fails..."); + } + } + + void test_write_output() { + try { + write(chars, 0, 3); + } catch (IOException e) { + throw new RuntimeException("write(char[], int, int): unexpected IOException..."); + } + try { + output(chars, 3, 2); + } catch (IOException e) { + throw new RuntimeException("output(char[], int, int): unexpected IOException..."); + } + } + + public void write() throws IOException, BadLocationException { + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4239714 + * @summary Tests that BasicMenuItemUI.installComponent() is protected + */ + +import javax.swing.JMenuItem; +import javax.swing.plaf.basic.BasicMenuItemUI; + +public class bug4239714 { + public static void main(String[] argv) throws Exception { + Tester tester = new Tester(); + tester.test(); + } + + static class Tester extends BasicMenuItemUI { + public void test() { + JMenuItem mi = new JMenuItem("bug4239714"); + installComponents(mi); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/BasicMenuUI/bug4244616.java openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuUI/bug4244616.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/BasicMenuUI/bug4244616.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/BasicMenuUI/bug4244616.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4244616 + * @summary Tests that debug output in BasicMenuUI private inner classes + * is commented out + */ + +import java.awt.event.ActionEvent; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import javax.swing.Action; +import javax.swing.ActionMap; +import javax.swing.JMenu; +import javax.swing.plaf.basic.BasicMenuUI; + +public class bug4244616 { + public static void main(String[] argv) throws Exception { + JMenu menu = new JMenu(); + BasicMenuUI ui = new BasicMenuUI(); + ui.installUI(menu); + ActionMap amap = menu.getActionMap(); + + String[] names = {"selectMenu", "cancel", + "selectNext", "selectPrevious"}; + ActionEvent ev = new ActionEvent(menu, + ActionEvent.ACTION_PERFORMED, "test event"); + + // Stream redirection + final PrintStream oldOut = System.out; + final PrintStream oldErr = System.err; + try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ByteArrayOutputStream berr = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + PrintStream err = new PrintStream(berr)) { + for (int i = 0; i < names.length; i++) { + Action action = amap.get(names[i]); + try { + action.actionPerformed(ev); + } catch (Exception ignored) { + } + } + + if (bout.size() != 0 || berr.size() != 0) { + System.out.println("bout: " + bout); + System.out.println("berr: " + berr); + throw new RuntimeException("Failed: some debug output occurred"); + } + } finally { + // Restore streams + System.setOut(oldOut); + System.setErr(oldErr); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java openjdk-17-17.0.15+6/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4240870 4240855 + * @summary Tests that DefaultTableCellRenderer overrides following methods: + * validate() + * revalidate() + * repaint(long, int, int, int, int) + * repaint(Rectangle) + * firePropertyChange(String, Object, Object) + * firePropertyChange(String, boolean, boolean) + */ + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.table.DefaultTableCellRenderer; + +public class bug4240870 { + public static void main(String[] argv) { + // Test overridden public methods using reflection + String methodName = null; + try { + Class clazz = Class.forName( + "javax.swing.table.DefaultTableCellRenderer"); + Class[] noArgs = {}; + methodName = "validate"; + clazz.getDeclaredMethod(methodName, noArgs); + methodName = "revalidate"; + clazz.getDeclaredMethod(methodName, noArgs); + + Class[] args1 = {long.class, int.class, int.class, + int.class, int.class}; + methodName = "repaint"; + clazz.getDeclaredMethod(methodName, args1); + Class[] args2 = {Class.forName("java.awt.Rectangle")}; + methodName = "repaint"; + clazz.getDeclaredMethod(methodName, args2); + + Class objectClass = Class.forName("java.lang.Object"); + Class stringClass = Class.forName("java.lang.String"); + Class[] args3 = {stringClass, objectClass, objectClass}; + methodName = "firePropertyChange"; + clazz.getDeclaredMethod(methodName, args3); + Class[] args4 = {stringClass, boolean.class, boolean.class}; + clazz.getDeclaredMethod(methodName, args4); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Failed: " + methodName + " not overridden"); + } catch (ClassNotFoundException e) { + } + + // test protected firePropertyChange(String, Object, Object) + Renderer r = new Renderer(); + r.addPropertyChangeListener(new Listener()); + r.test(); + } + + static class Renderer extends DefaultTableCellRenderer { + public void test() { + super.firePropertyChange("text", "old_text", "new_text"); + super.firePropertyChange("stuff", "old_stuff", "new_stuff"); + } + } + + static class Listener implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent e) { + if (!e.getPropertyName().equals("text")) { + throw new RuntimeException("Failed: firePropertyChange not overridden"); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.awt.AWTException; -import java.awt.BorderLayout; -import java.awt.EventQueue; -import java.awt.Point; -import java.awt.Robot; -import java.awt.event.InputEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.SwingUtilities; - -/* - * @test - * @key headful - * @bug 8049069 - * @summary Tests whether right mouse click releases a pressed JButton - */ - -public class PressedButtonRightClickTest { - - private static Robot testRobot; - private static JFrame myFrame; - private static JButton myButton; - - public static void main(String[] args) throws Throwable { - - SwingUtilities.invokeAndWait(PressedButtonRightClickTest::constructTestUI); - - try { - testRobot = new Robot(); - } catch (AWTException ex) { - throw new RuntimeException("Exception in Robot creation"); - } - - testRobot.waitForIdle(); - testRobot.delay(500); - - // Method performing auto test operation - try { - test(); - } finally { - EventQueue.invokeAndWait(PressedButtonRightClickTest::disposeTestUI); - } - } - - private static void test() { - Point loc = myFrame.getLocationOnScreen(); - - testRobot.mouseMove((loc.x + 100), (loc.y + 100)); - - // Press the left mouse button - System.out.println("press BUTTON1_DOWN_MASK"); - testRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - myButton.setText("Left button pressed"); - testRobot.delay(500); - - // Press the right mouse button - System.out.println("press BUTTON3_DOWN_MASK"); - testRobot.mousePress(InputEvent.BUTTON3_DOWN_MASK); - myButton.setText("Left button pressed + Right button pressed"); - testRobot.delay(500); - - // Release the right mouse button - System.out.println("release BUTTON3_DOWN_MASK"); - testRobot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); - myButton.setText("Right button released"); - testRobot.waitForIdle(); - testRobot.delay(500); - - // Test whether the button is still pressed - boolean pressed = myButton.getModel().isPressed(); - System.out.println("release BUTTON1_DOWN_MASK"); - testRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - if (!pressed) { - disposeTestUI(); - throw new RuntimeException("Test Failed!"); - } - } - - private static void disposeTestUI() { - myFrame.setVisible(false); - myFrame.dispose(); - } - - public static void constructTestUI() { - myFrame = new JFrame(); - myFrame.setLayout(new BorderLayout()); - myButton = new JButton("Whatever"); - myButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mousePressed(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseEntered(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseExited(MouseEvent e) { - System.out.println(e); - } - }); - myFrame.add(myButton, BorderLayout.CENTER); - myFrame.setSize(400, 300); - myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - myFrame.setLocationRelativeTo(null); - myFrame.setVisible(true); - } -} - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/bug4323121.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4323121.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/bug4323121.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4323121.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,59 +24,81 @@ /* * @test * @bug 4323121 - * @summary Tests whether any button that extends JButton always - returns true for isArmed() + * @summary Tests whether a button model always returns true for isArmed() + * when mouse hovers over the button * @key headful * @run main bug4323121 */ -import java.awt.Graphics; import java.awt.Point; import java.awt.Robot; +import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; +import java.util.concurrent.CountDownLatch; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; -public class bug4323121 { +import static java.util.concurrent.TimeUnit.SECONDS; + +public final class bug4323121 { static JFrame frame; - static testButton button; - static volatile Point pt; - static volatile int buttonW; - static volatile int buttonH; - static volatile boolean failed = false; + static JButton button; + + static volatile Point buttonCenter; + + private static final CountDownLatch mouseEntered = new CountDownLatch(1); + + // Usage of this flag is thread-safe because of using the mouseEntered latch + private static boolean modelArmed; public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); + try { SwingUtilities.invokeAndWait(() -> { + button = new JButton("gotcha"); + button.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + if (button.getModel().isArmed()) { + modelArmed = true; + } + mouseEntered.countDown(); + } + }); + frame = new JFrame("bug4323121"); - button = new testButton("gotcha"); frame.getContentPane().add(button); + frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); + robot.waitForIdle(); - robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { - pt = button.getLocationOnScreen(); - buttonW = button.getSize().width; - buttonH = button.getSize().height; + Point location = button.getLocationOnScreen(); + buttonCenter = new Point(location.x + button.getWidth() / 2, + location.y + button.getHeight() / 2); }); - robot.mouseMove(pt.x + buttonW / 2, pt.y + buttonH / 2); - robot.waitForIdle(); - if (failed) { - throw new RuntimeException("Any created button returns " + - "true for isArmed()"); + + robot.mouseMove(buttonCenter.x, buttonCenter.y); + + if (!mouseEntered.await(1, SECONDS)) { + throw new RuntimeException("Mouse entered event wasn't received"); + } + if (modelArmed) { + throw new RuntimeException("getModel().isArmed() returns true " + + "when mouse hovers over the button"); } } finally { - SwingUtilities.invokeAndWait(() -> { + SwingUtilities.invokeAndWait(() -> { if (frame != null) { frame.dispose(); } @@ -84,42 +106,4 @@ } } - static class testButton extends JButton implements MouseMotionListener, MouseListener { - public testButton(String label) { - super(label); - addMouseMotionListener(this); - addMouseListener(this); - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - } - - protected void paintBorder(Graphics g) { - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseDragged(MouseEvent e) { - } - - public void mouseMoved(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - if (getModel().isArmed()) { - failed = true; - } - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/bug4490179.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4490179.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JButton/bug4490179.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JButton/bug4490179.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,7 +23,7 @@ /* * @test - * @bug 4490179 + * @bug 4490179 8049069 * @summary Tests that JButton only responds to left mouse clicks. * @key headful * @run main bug4490179 @@ -31,61 +31,107 @@ import java.awt.Point; import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.concurrent.CountDownLatch; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; -public class bug4490179 { +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +public final class bug4490179 + extends MouseAdapter + implements ActionListener { static JFrame frame; static JButton button; - static volatile Point pt; - static volatile int buttonW; - static volatile int buttonH; - static volatile boolean passed = true; + + private static volatile Point buttonCenter; + + private static final CountDownLatch windowGainedFocus = new CountDownLatch(1); + + private static final CountDownLatch mouseButton1Released = new CountDownLatch(1); + private static final CountDownLatch mouseButton3Released = new CountDownLatch(2); + + private static final CountDownLatch actionPerformed = new CountDownLatch(1); public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); - robot.setAutoWaitForIdle(true); + + final bug4490179 eventHandler = new bug4490179(); try { SwingUtilities.invokeAndWait(() -> { - frame = new JFrame("bug4490179"); button = new JButton("Button"); + button.addActionListener(eventHandler); + button.addMouseListener(eventHandler); + + frame = new JFrame("bug4490179"); frame.getContentPane().add(button); - button.addActionListener(e -> { - if ((e.getModifiers() & InputEvent.BUTTON1_MASK) - != InputEvent.BUTTON1_MASK) { - System.out.println("Status: Failed"); - passed = false; + + frame.addWindowFocusListener(new WindowAdapter() { + @Override + public void windowGainedFocus(WindowEvent e) { + windowGainedFocus.countDown(); } }); + frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); + + if (!windowGainedFocus.await(1, SECONDS)) { + throw new RuntimeException("Window didn't gain focus"); + } robot.waitForIdle(); - robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { - pt = button.getLocationOnScreen(); - buttonW = button.getSize().width; - buttonH = button.getSize().height; + Point location = button.getLocationOnScreen(); + buttonCenter = new Point(location.x + button.getWidth() / 2, + location.y + button.getHeight() / 2); }); - robot.mouseMove(pt.x + buttonW / 2, pt.y + buttonH / 2); - robot.waitForIdle(); + robot.mouseMove(buttonCenter.x, buttonCenter.y); + System.out.println("Press / Release button 3"); robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); + System.out.println("Press button 1"); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + System.out.println("Press button 3"); robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); + System.out.println("Release button 3"); robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.delay(500); - if (!passed) { - throw new RuntimeException("Test Failed"); + try { + if (!mouseButton3Released.await(1, SECONDS)) { + throw new RuntimeException("Mouse button 3 isn't released"); + } + + robot.waitForIdle(); + + if (actionPerformed.await(100, MILLISECONDS)) { + throw new RuntimeException("Action event triggered by releasing button 3"); + } + } finally { + System.out.println("Release button 1"); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + if (!mouseButton1Released.await(1, SECONDS)) { + throw new RuntimeException("Mouse button 1 isn't released"); + } + if (!actionPerformed.await(100, MILLISECONDS)) { + throw new RuntimeException("Action event isn't triggered by releasing button 1"); } } finally { SwingUtilities.invokeAndWait(() -> { @@ -95,4 +141,21 @@ }); } } + + @Override + public void actionPerformed(ActionEvent e) { + System.out.println(" actionPerformed"); + actionPerformed.countDown(); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + System.out.println(" mouseReleased: button 1"); + mouseButton1Released.countDown(); + } else if (e.getButton() == MouseEvent.BUTTON3) { + System.out.println(" mouseReleased: button 3"); + mouseButton3Released.countDown(); + } + } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ - - - - - -Verify that scaled components are rendered smoothly to image. - -1. Run the test. -2. Check that Selected and Deselected JCheckBox icons are drawn smoothly. -If so, press PASS, else press FAIL. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.awt.BorderLayout; -import java.awt.Canvas; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import javax.swing.JApplet; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; - -/* @test - * @bug 8032667 - * @summary [macosx] Components cannot be rendered in HiDPI to BufferedImage - * @run applet/manual=yesno bug8032667.html - */ -public class bug8032667 extends JApplet { - - static final int scale = 2; - static final int width = 130; - static final int height = 50; - static final int scaledWidth = scale * width; - static final int scaledHeight = scale * height; - - @Override - public void init() { - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - - final Image image1 = getImage(getCheckBox("Deselected", false)); - final Image image2 = getImage(getCheckBox("Selected", true)); - - Canvas canvas = new Canvas() { - - @Override - public void paint(Graphics g) { - super.paint(g); - g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this); - g.drawImage(image2, 0, scaledHeight + 5, - scaledWidth, scaledHeight, this); - } - }; - - getContentPane().add(canvas, BorderLayout.CENTER); - } - }); - } - - static JCheckBox getCheckBox(String text, boolean selected) { - JCheckBox checkBox = new JCheckBox(text); - checkBox.setSelected(selected); - checkBox.setSize(new Dimension(width, height)); - return checkBox; - } - - static Image getImage(JComponent component) { - final BufferedImage image = new BufferedImage( - scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB); - final Graphics g = image.getGraphics(); - ((Graphics2D) g).scale(scale, scale); - component.paint(g); - g.dispose(); - - return image; - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; - -import jdk.test.lib.Platform; - -/* @test - * @bug 8032667 - * @summary [macosx] Components cannot be rendered in HiDPI to BufferedImage - * @library /test/lib - * @build jdk.test.lib.Platform - * @run main bug8032667_image_diff - */ -public class bug8032667_image_diff { - - static final int IMAGE_WIDTH = 130; - static final int IMAGE_HEIGHT = 50; - - public static void main(String[] args) throws Exception { - - if (!Platform.isOSX()) { - return; - } - - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - - JCheckBox checkBox = new JCheckBox(); - checkBox.setSelected(true); - checkBox.setSize(new Dimension(IMAGE_WIDTH, IMAGE_HEIGHT)); - - final BufferedImage image1 = getHiDPIImage(checkBox); - final BufferedImage image2 = getScaledImage(checkBox); - - if(equal(image1, image2)){ - throw new RuntimeException("2x image equals to non smooth image"); - } - } - }); - } - - static boolean equal(BufferedImage image1, BufferedImage image2) { - - int w = image1.getWidth(); - int h = image1.getHeight(); - - if (w != image2.getWidth() || h != image2.getHeight()) { - return false; - } - - for (int i = 0; i < w; i++) { - for (int j = 0; j < h; j++) { - int color1 = image1.getRGB(i, j); - int color2 = image2.getRGB(i, j); - - if (color1 != color2) { - return false; - } - } - } - return true; - } - - static BufferedImage getHiDPIImage(JComponent component) { - return getImage(component, 2, IMAGE_WIDTH, IMAGE_HEIGHT); - } - - static BufferedImage getScaledImage(JComponent component) { - Image image1x = getImage(component, 1, IMAGE_WIDTH, IMAGE_HEIGHT); - final BufferedImage image2x = new BufferedImage( - 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB); - final Graphics g = image2x.getGraphics(); - ((Graphics2D) g).scale(2, 2); - g.drawImage(image1x, 0, 0, null); - g.dispose(); - return image2x; - } - - static BufferedImage getImage(JComponent component, int scale, int width, int height) { - final BufferedImage image = new BufferedImage( - scale * width, scale * height, BufferedImage.TYPE_INT_ARGB); - final Graphics g = image.getGraphics(); - ((Graphics2D) g).scale(scale, scale); - component.paint(g); - g.dispose(); - return image; - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/bug8032667.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/bug8032667.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JCheckBox/bug8032667.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JCheckBox/bug8032667.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; + +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; + +/* @test + * @bug 8032667 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary [macosx] Components cannot be rendered in HiDPI to BufferedImage + * @run main/manual bug8032667 + */ + +public class bug8032667 { + + static final int scale = 2; + static final int width = 130; + static final int height = 50; + static final int scaledWidth = scale * width; + static final int scaledHeight = scale * height; + + private static final String INSTRUCTIONS = """ + Verify that scaled components are rendered smoothly to image. + + 1. Run the test. + 2. Check that Selected and Deselected JCheckBox icons are drawn smoothly. + If so, press PASS, else press FAIL. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug8032667 Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(bug8032667::createAndShowGUI) + .build() + .awaitAndCheck(); + } + + public static JFrame createAndShowGUI() { + JFrame frame = new JFrame("bug8032667 HiDPI Component Test"); + frame.setLayout(new BorderLayout()); + frame.setBounds(0, 400, 400, 400); + + final Image image1 = getImage(getCheckBox("Deselected", false)); + final Image image2 = getImage(getCheckBox("Selected", true)); + JPanel panel = new JPanel() { + @Override + public void paint(Graphics g) { + super.paint(g); + g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this); + g.drawImage(image2, 0, scaledHeight + 5, + scaledWidth, scaledHeight, this); + } + }; + frame.add(panel, BorderLayout.CENTER); + return frame; + } + + static JCheckBox getCheckBox(String text, boolean selected) { + JCheckBox checkBox = new JCheckBox(text); + checkBox.setSelected(selected); + checkBox.setSize(new Dimension(width, height)); + return checkBox; + } + + static Image getImage(JComponent component) { + final BufferedImage image = new BufferedImage( + scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB); + final Graphics g = image.getGraphics(); + ((Graphics2D) g).scale(scale, scale); + component.paint(g); + g.dispose(); + + return image; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,21 +34,17 @@ public class JColorChooserDnDTest { public static void main(String[] args) { - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - JFrame frame = new JFrame(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - JPanel panel = new JPanel(); - JColorChooser colorChooser = new JColorChooser(); - colorChooser.setDragEnabled(true); - panel.setBorder(BorderFactory.createTitledBorder("JColorChoosers")); - panel.add(colorChooser); - frame.setContentPane(panel); - frame.pack(); - frame.setVisible(true); - } + SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JPanel panel = new JPanel(); + JColorChooser colorChooser = new JColorChooser(); + colorChooser.setDragEnabled(true); + panel.setBorder(BorderFactory.createTitledBorder("JColorChoosers")); + panel.add(colorChooser); + frame.setContentPane(panel); + frame.pack(); + frame.setVisible(true); }); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ - - - - - 1. Compile the java test JColorChooserDnDTest.java: - > /bin/javac JColorChooserDnDTest.java - 2. Run the first instance of the java test: - > /bin/java JColorChooserDnDTest - 3. Select a color in the color chooser - 4. Run the second instance of the java test: - > /bin/java JColorChooserDnDTest - 5. Drag and drop the selected color from the first color chooser - preview panel to the second color chooser preview panel - 6. If the color is dragged to the second color chooser then the test passes. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,15 +20,39 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import javax.swing.JApplet; /* * @test * @bug 8065098 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary JColorChooser no longer supports drag and drop * between two JVM instances - * @run applet/manual=yesno bug8065098.html + * @run main/manual bug8065098 */ -public class bug8065098 extends JApplet { +public class bug8065098 { + private static final String INSTRUCTIONS = """ + 1. Compile the java test JColorChooserDnDTest.java: + > /bin/javac JColorChooserDnDTest.java + 2. Run the first instance of the java test: + > /bin/java JColorChooserDnDTest + 3. Select a color in the color chooser. + 4. Run the second instance of the java test: + > /bin/java JColorChooserDnDTest + 5. Drag and drop the selected color from the first color chooser + preview panel to the second color chooser preview panel + 6. If the color is dragged to the second color chooser, then the + test passes. Otherwise, the test fails. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug8065098 Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .build() + .awaitAndCheck(); + } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4222508.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4222508.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ - - - - -Use the check box above the color chooser to disable it. -You could not choose a color using by the disable color chooser. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4222508.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4222508.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4222508.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,36 +21,50 @@ * questions. */ +import java.awt.BorderLayout; +import javax.swing.JCheckBox; +import javax.swing.JColorChooser; +import javax.swing.JFrame; + /* * @test * @bug 4222508 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Tests the color chooser disabling - * @author Sergey Malenkov - * @run applet/manual=yesno Test4222508.html + * @run main/manual Test4222508 */ +public final class Test4222508 { -import java.awt.BorderLayout; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import javax.swing.JApplet; -import javax.swing.JCheckBox; -import javax.swing.JColorChooser; - -public final class Test4222508 extends JApplet implements ItemListener { + public static void main(String[] args) throws Exception { + String instructions = "Click on colors in the JColorChooser.\n" + + "Then uncheck the checkbox and click on colors again.\n" + + "If the JColorChooser is disabled when the checkbox is unchecked, " + + "then pass the test."; + + PassFailJFrame.builder() + .title("Test4222508") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4222508::test) + .build() + .awaitAndCheck(); + } - private JCheckBox checkbox; - private JColorChooser chooser; + public static JFrame test() { + JFrame frame = new JFrame("JColorChooser with enable/disable checkbox"); + frame.setLayout(new BorderLayout()); + JColorChooser chooser = new JColorChooser(); + JCheckBox checkbox = new JCheckBox("Enable the color chooser below", true); + checkbox.addItemListener(e -> chooser.setEnabled(checkbox.isSelected())); + + frame.add(chooser, BorderLayout.SOUTH); + frame.add(checkbox, BorderLayout.NORTH); + frame.pack(); - @Override - public void init() { - this.chooser = new JColorChooser(); - this.checkbox = new JCheckBox("Enable the color chooser below", true); - this.checkbox.addItemListener(this); - add(BorderLayout.NORTH, this.checkbox); - add(BorderLayout.CENTER, this.chooser); + return frame; } - public void itemStateChanged(ItemEvent event) { - this.chooser.setEnabled(this.checkbox.isSelected()); - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4319113.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4319113.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ - - - - -1. Press button "Show ColorChooser" in the frame "frame" and - a color chooser dialog should appear. -2. Without closing the color chooser, change Look And Feel - selecting it from the combobox in the frame "frame". - Dialog appearance will change. -3. Resize the color chooser by mouse drag. - - If you see some remnants of the previous color chooser, - press "Fail" else press "Pass". - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4319113.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4319113.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4319113.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,27 +21,15 @@ * questions. */ -/* - * @test - * @bug 4319113 - * @summary Tests the open JColorChooser behavior on LaF change. - * @author yan - * @run applet/manual=yesno Test4319113.html - */ - - import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.GridLayout; -import java.awt.LayoutManager; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; -import java.io.PrintStream; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComboBox; @@ -50,47 +38,66 @@ import javax.swing.SwingUtilities; import javax.swing.UIManager; -public class Test4319113 -extends JApplet -implements ActionListener { - private final JFrame frame = new JFrame("frame"); - private JComboBox cbPlaf; - - @Override - public void init() { - try { - java.awt.EventQueue.invokeLater( () -> { - Test4319113.this.frame.setLayout(new GridLayout(2, 1)); - Test4319113.this.show(Test4319113.this.frame); - }); - }catch(Exception ex) { - ex.printStackTrace(); - } - } +/* + * @test + * @bug 4319113 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests the open JColorChooser behavior on LaF change. + * @run main/manual Test4319113 + */ +public class Test4319113 { - @Override - public void actionPerformed(ActionEvent actionEvent) { - Object object = actionEvent.getSource(); - Component component = object instanceof Component ? (Component)object : null; - JDialog jDialog = JColorChooser.createDialog(component, "ColorChooser", false, new JColorChooser(Color.BLUE), null, null); - jDialog.setVisible(true); + public static void main(String[] args) throws Exception { + String instructions = "1. Press button \"Show ColorChooser\" in the frame \"frame\" and\n" + + " a color chooser dialog should appear.\n" + + "2. Without closing the color chooser, change Look And Feel\n" + + " selecting it from the combobox in the frame \"frame\".\n" + + " Dialog appearance will change.\n" + + "3. Resize the color chooser by mouse drag.\n" + + "\n" + + " If you see some remnants of the previous color chooser,\n" + + " press \"Fail\" else press \"Pass\"."; + + PassFailJFrame.builder() + .title("Test4319113") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4319113::test) + .build() + .awaitAndCheck(); } - private void show(Window window) { + private static JFrame test() { + JFrame frame = new JFrame("JColorChooser behavior on LaF change"); + frame.setLayout(new GridLayout(2, 1)); + JButton jButton = new JButton("Show ColorChooser"); jButton.setActionCommand("Show ColorChooser"); - jButton.addActionListener(this); - this.cbPlaf = new JComboBox(UIManager.getInstalledLookAndFeels()); - this.cbPlaf.addItemListener(new ItemListener(){ + jButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + Object object = actionEvent.getSource(); + Component component = object instanceof Component ? (Component) object : null; + JDialog jDialog = JColorChooser.createDialog(component, "ColorChooser", + false, new JColorChooser(Color.BLUE), null, null); + jDialog.setVisible(true); + } + }); + JComboBox cbPlaf = new JComboBox(UIManager.getInstalledLookAndFeels()); + cbPlaf.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { if (itemEvent.getStateChange() == 1) { - SwingUtilities.invokeLater(new Runnable(){ + SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - UIManager.LookAndFeelInfo lookAndFeelInfo = (UIManager.LookAndFeelInfo)Test4319113.this.cbPlaf.getSelectedItem(); + UIManager.LookAndFeelInfo lookAndFeelInfo = + (UIManager.LookAndFeelInfo) cbPlaf.getSelectedItem(); try { UIManager.setLookAndFeel(lookAndFeelInfo.getClassName()); Frame[] arrframe = Frame.getFrames(); @@ -98,8 +105,7 @@ while (--n >= 0) { Test4319113.updateWindowTreeUI(arrframe[n]); } - } - catch (Exception var2_3) { + } catch (Exception var2_3) { System.err.println("Exception while changing L&F!"); } } @@ -108,10 +114,12 @@ } }); - window.add(this.cbPlaf); - window.add(jButton); - window.pack(); - window.setVisible(true); + + frame.add(cbPlaf); + frame.add(jButton); + frame.pack(); + + return frame; } private static void updateWindowTreeUI(Window window) { diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759306.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759306.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ - - - - -If you see the preview panel, then test failed, otherwise it passed. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759306.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759306.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759306.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,22 +21,34 @@ * questions. */ +import javax.swing.JColorChooser; +import javax.swing.JPanel; + /* * @test * @bug 4759306 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Checks if JColorChooser.setPreviewPanel removes the old one - * @author Konstantin Eremin - @run applet/manual=yesno Test4759306.html + * @run main/manual Test4759306 */ +public class Test4759306 { -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.JPanel; + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Test4759306") + .instructions("Check that there is no panel titled \"Preview\" in the JColorChooser.") + .rows(5) + .columns(40) + .testTimeOut(10) + .splitUIRight(Test4759306::createColorChooser) + .build() + .awaitAndCheck(); + } -public class Test4759306 extends JApplet { - public void init() { + private static JColorChooser createColorChooser() { JColorChooser chooser = new JColorChooser(); chooser.setPreviewPanel(new JPanel()); - getContentPane().add(chooser); + return chooser; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759934.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759934.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ - - - - -1. Press button "Show Dialog" at the frame "Test" and - the dialog with button "Show ColorChooser" should appears. -2. Press button "Show ColorChooser" at the dialog "Dialog" and - the colorchooser should appears. -3. Press the button "Cancel" of colorchooser. - If the focus will come to the frame "Test" then test fails. - If the focus will come to the dialog "Dialog" then test passes. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759934.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4759934.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4759934.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,60 +21,87 @@ * questions. */ -/* - * @test - * @bug 4759934 - * @summary Tests windows activation problem - * @author Andrey Pikalev - * @run applet/manual=yesno Test4759934.html - */ - import java.awt.Color; import java.awt.Component; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; -public class Test4759934 extends JApplet implements ActionListener { +/* + * @test + * @bug 4759934 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests windows activation problem + * @run main/manual Test4759934 + */ +public class Test4759934 { private static final String CMD_DIALOG = "Show Dialog"; // NON-NLS: first button private static final String CMD_CHOOSER = "Show ColorChooser"; // NON-NLS: second button - private final JFrame frame = new JFrame("Test"); // NON-NLS: frame title + private static JFrame frame; - public void init() { - show(this.frame, CMD_DIALOG); - } + private static ActionListener al = new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + String command = event.getActionCommand(); + if (CMD_DIALOG.equals(command)) { + JDialog dialog = new JDialog(frame, "Dialog"); // NON-NLS: dialog title + dialog.setLocation(200, 0); + show(dialog, CMD_CHOOSER, true); + } + else if (CMD_CHOOSER.equals(command)) { + Object source = event.getSource(); + Component component = (source instanceof Component) + ? (Component) source + : null; - public void actionPerformed(ActionEvent event) { - String command = event.getActionCommand(); - if (CMD_DIALOG.equals(command)) { - JDialog dialog = new JDialog(this.frame, "Dialog"); // NON-NLS: dialog title - dialog.setLocation(200, 0); - show(dialog, CMD_CHOOSER); + JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title + } } - else if (CMD_CHOOSER.equals(command)) { - Object source = event.getSource(); - Component component = (source instanceof Component) - ? (Component) source - : null; + }; - JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title - } + public static void main(String[] args) throws Exception { + String instructions = "1. Press button \"Show Dialog\" at the frame \"Test\" and\n" + + " the dialog with button \"Show ColorChooser\" should appears.\n" + + "2. Press button \"Show ColorChooser\" at the dialog \"Dialog\" and\n" + + " the colorchooser should appears.\n" + + "3. Press the button \"Cancel\" of colorchooser.\n" + + " If the focus will come to the frame \"Test\" then test fails.\n" + + " If the focus will come to the dialog \"Dialog\" then test passes."; + + PassFailJFrame.builder() + .title("Test4759934") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4759934::test) + .build() + .awaitAndCheck(); } - private void show(Window window, String command) { + public static JFrame test() { + frame = new JFrame("ColorChooser dialog on button press test"); + show(frame, CMD_DIALOG, false); + return frame; + } + + private static void show(Window window, String command, boolean setVisible) { JButton button = new JButton(command); button.setActionCommand(command); - button.addActionListener(this); + button.addActionListener(al); + button.setFont(button.getFont().deriveFont(64.0f)); window.add(button); window.pack(); - window.setVisible(true); + if (setVisible) { + window.setVisible(true); + } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4887836.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4887836.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ - - - - -If you do not see white area under swatches, -then test passed, otherwise it failed. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4887836.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test4887836.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test4887836.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,23 +21,49 @@ * questions. */ +import java.awt.Color; +import java.awt.Font; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +import jtreg.SkippedException; + /* * @test * @bug 4887836 - * @summary Checks if no tooltip modification when no KeyStroke modifier - * @author Konstantin Eremin - * @run applet/manual=yesno Test4887836.html + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame + * @summary Checks for white area under the JColorChooser Swatch tab + * @run main/manual Test4887836 */ -import java.awt.Color; -import java.awt.Font; -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.UIManager; +public class Test4887836 { + + public static void main(String[] args) throws Exception { + + // ColorChooser UI design is different for GTK L&F. + // There is no Swatches tab available for GTK L&F, skip the testing. + if (UIManager.getLookAndFeel().getName().contains("GTK")) { + throw new SkippedException("Test not applicable for GTK L&F"); + } + + String instructions = """ + If you do not see white area under the \"Swatches\" tab, + then test passed, otherwise it failed."""; + + PassFailJFrame.builder() + .title("Test4759306") + .instructions(instructions) + .columns(40) + .testUI(Test4887836::createColorChooser) + .build() + .awaitAndCheck(); + } + + private static JColorChooser createColorChooser() { + JColorChooser chooser = new JColorChooser(Color.LIGHT_GRAY); -public class Test4887836 extends JApplet { - public void init() { - UIManager.put("Label.font", new Font("Perpetua", 0, 36)); // NON-NLS: property and font names - add(new JColorChooser(Color.LIGHT_GRAY)); + UIManager.put("Label.font", new Font("Font.DIALOG", 0, 36)); + return chooser; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6348456.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6348456.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ - - - - -When applet starts, you'll see that the preview is white. -When you swap models, you'll see that the preview color is changed. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6348456.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6348456.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6348456.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,43 +21,67 @@ * questions. */ -/* - * @test - * @bug 6348456 - * @summary Tests model changing - * @author Sergey Malenkov - * @run applet/manual=yesno Test6348456.html - */ - import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; +import javax.swing.JFrame; import javax.swing.colorchooser.DefaultColorSelectionModel; -public final class Test6348456 extends JApplet implements ActionListener { +/* + * @test + * @bug 6348456 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests model changing + * @run main/manual Test6348456 + */ - private static final DefaultColorSelectionModel WHITE = new DefaultColorSelectionModel(Color.WHITE); - private static final DefaultColorSelectionModel BLACK = new DefaultColorSelectionModel(Color.BLACK); +public final class Test6348456 { - private JColorChooser chooser; + private static final DefaultColorSelectionModel WHITE = + new DefaultColorSelectionModel(Color.WHITE); + private static final DefaultColorSelectionModel BLACK = + new DefaultColorSelectionModel(Color.BLACK); + + private static JColorChooser chooser; + + public static void main(String[] args) throws Exception { + String instructions = "When test starts, you'll see that the preview is white.\n" + + "When you swap models, you'll see that the preview color is changed.\n" + + "Click pass if so, otherwise fail."; + + PassFailJFrame.builder() + .title("Test6348456") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test6348456::test) + .build() + .awaitAndCheck(); + } - @Override - public void init() { + public static JFrame test() { + JFrame frame = new JFrame("JColor Swap Models Test"); JButton button = new JButton("Swap models"); - button.addActionListener(this); - - this.chooser = new JColorChooser(Color.RED); - this.chooser.setSelectionModel(WHITE); - - add(BorderLayout.NORTH, button); - add(BorderLayout.CENTER, this.chooser); - } + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + chooser.setSelectionModel(chooser.getSelectionModel() == BLACK ? WHITE : BLACK); + + } + }); + + chooser = new JColorChooser(Color.RED); + chooser.setSelectionModel(WHITE); + + frame.add(BorderLayout.NORTH, button); + frame.add(BorderLayout.CENTER, chooser); + frame.pack(); - public void actionPerformed(ActionEvent event){ - this.chooser.setSelectionModel(this.chooser.getSelectionModel() == BLACK ? WHITE : BLACK); + return frame; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6977726.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6977726.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ - - - - -If you don't see the preview panel, then test failed, otherwise it passed. - - - - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6977726.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JColorChooser/Test6977726.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JColorChooser/Test6977726.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,22 +21,42 @@ * questions. */ +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.JLabel; + /* * @test * @bug 6977726 - * @summary Checks if JColorChooser.setPreviewPanel removes the old one - * @author Sergey Malenkov - * @run applet/manual=yesno Test6977726.html + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Checks if JColorChooser.setPreviewPanel(JLabel) doesn't remove the preview panel but + * removes the content of the default preview panel + * @run main/manual Test6977726 */ -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.JLabel; +public class Test6977726 { + + public static void main(String[] args) throws Exception { + String instructions = """ + Check that there is a panel with "Text Preview Panel" text + and with title "Preview" in the JColorChooser. + Test passes if the panel is as described, test fails otherwise."""; + + PassFailJFrame.builder() + .title("Test6977726") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(2) + .testUI(Test6977726::createColorChooser) + .build() + .awaitAndCheck(); + } -public class Test6977726 extends JApplet { - public void init() { - JColorChooser chooser = new JColorChooser(); + private static JColorChooser createColorChooser() { + JColorChooser chooser = new JColorChooser(Color.BLUE); chooser.setPreviewPanel(new JLabel("Text Preview Panel")); - getContentPane().add(chooser); + return chooser; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java 2025-04-09 19:45:33.000000000 +0000 @@ -24,29 +24,32 @@ /* * @test * @key headful - * @bug 6559152 + * @bug 6559152 8294067 * @summary Checks that you can select an item in JComboBox with keyboard * when it is a JTable cell editor. * @run main bug6559152 */ +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + import javax.swing.DefaultCellEditor; +import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; -import javax.swing.JComboBox; +import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; -import javax.swing.JTable; -import java.awt.Point; -import java.awt.event.KeyEvent; -import java.awt.event.InputEvent; -import java.awt.Robot; public class bug6559152 { private static JFrame frame; private static JComboBox cb; private static Robot robot; private static Point p = null; + private static Dimension d; public static void main(String[] args) throws Exception { robot = new Robot(); @@ -69,6 +72,7 @@ try { SwingUtilities.invokeAndWait(() -> { p = comp.getLocationOnScreen(); + d = comp.getSize(); }); } catch (IllegalStateException e) { try { @@ -97,7 +101,7 @@ } private static void test() throws Exception { - robot.mouseMove(p.x, p.y); + robot.mouseMove(p.x + d.width / 2, p.y + d.height / 2); robot.waitForIdle(); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JComponent/bug4765272.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4765272.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JComponent/bug4765272.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4765272.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4765272 + * @summary REGRESSION: IAE: focusCycleRoot not focus cyle root of a Component + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4765272 { + static boolean focusGained = false; + static JFrame f; + static JButton bt1; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4765272"); + bt1 = new JButton("Button 1"); + JButton bt2 = new JButton("Button 2"); + + JPanel p = new JPanel(); + p.setLayout(new FlowLayout()); + p.add(bt1); + p.add(bt2); + f.getContentPane().add(p); + + FocusTraversalPolicy policy = new FocusTraversalPolicy() { + @Override + public Component getComponentAfter(Container aContainer, Component aComponent) { + if (aComponent == bt1) { + return bt2; + } + return bt1; + } + + @Override + public Component getComponentBefore(Container aContainer, Component aComponent) { + if (aComponent == bt1) { + return bt2; + } + return bt1; + } + + @Override + public Component getFirstComponent(Container aContainer) { + return bt1; + } + + @Override + public Component getLastComponent(Container aContainer) { + return bt2; + } + + @Override + public Component getDefaultComponent(Container aContainer) { + return bt1; + } + }; + + bt1.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + p.removeAll(); + synchronized (this) { + focusGained = true; + this.notifyAll(); + } + } + }); + + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + bt1.requestFocus(); + try { + if (!focusGained) { + Thread.sleep(5000); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JComponent/bug4979794.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4979794.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JComponent/bug4979794.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JComponent/bug4979794.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4979794 + * @summary A component is sometimes the next component for itself in focus policy. + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4979794 { + static JFrame fr; + static JButton btn1; + static JButton btn2; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4979794"); + fr.getContentPane().setLayout(null); + + JPanel p = new JPanel(); + p.setLayout(null); + fr.getContentPane().add(p); + + btn1 = new JButton("Button 1"); + btn1.setBounds(0, 0, 200, 200); + + btn2 = new JButton("Button 2"); + btn2.setBounds(0, 0, 200, 200); + + p.add(btn1); + p.add(btn2); + p.setSize(200, 200); + + fr.setLocationRelativeTo(null); + fr.setSize(300, 300); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Container root = btn1.getFocusCycleRootAncestor(); + FocusTraversalPolicy policy = root.getFocusTraversalPolicy(); + Component next1 = policy.getComponentAfter(fr, btn1); + Component next2 = policy.getComponentAfter(fr, btn2); + if (next1 == next2) { + throw new RuntimeException("btn1 and btn2 have the same next Component."); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ - - - - - -1. Go into 'subdir' folder via double click -2. Return to parent directory -3. Go into 'subdir' folder: select 'subdir' folder and press the 'Open' button - - diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,41 +21,53 @@ * questions. */ -/* @test - @bug 6698013 - @summary JFileChooser can no longer navigate non-local file systems. - @run applet/manual=done bug6698013.html -*/ - import java.io.File; - -import javax.swing.JApplet; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileSystemView; -public class bug6698013 extends JApplet { - - final static VirtualFile root = new VirtualFile("testdir", true); +/* + * @test + * @bug 6698013 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary JFileChooser can no longer navigate non-local file systems. + * @run main/manual bug6698013 + */ - final static VirtualFile rootFile = new VirtualFile("testdir/test.txt", false); +public class bug6698013 { - final static VirtualFile subdir = new VirtualFile("testdir/subdir", true); - - final static VirtualFile subdirFile = new VirtualFile("testdir/subdir/subtest.txt", false); + final static VirtualFile root = new VirtualFile("testdir", true); public static void main(String[] args) throws Exception { - SwingUtilities.invokeAndWait(() -> new bug6698013().init()); - } + String instructions = """ + 1. Go into 'subdir' folder via double click + 2. Return to parent directory + 3. Go into 'subdir' folder: select 'subdir' folder and press the 'Open' button + If both methods of navigating into the subdir work, pass test. Otherwise fail."""; + + PassFailJFrame pfframe = PassFailJFrame.builder() + .title("bug6698013") + .instructions(instructions) + .rows(25) + .columns(40) + .testTimeOut(10) + .build(); + + SwingUtilities.invokeAndWait(() -> { + JFileChooser chooser = new JFileChooser(new VirtualFileSystemView()); + chooser.setCurrentDirectory(root); + chooser.showOpenDialog(null); + }); - public void init() { - JFileChooser chooser = new JFileChooser(new VirtualFileSystemView()); - chooser.setCurrentDirectory(root); - chooser.showOpenDialog(null); + pfframe.awaitAndCheck(); } } class VirtualFileSystemView extends FileSystemView { + final static VirtualFile rootFile = new VirtualFile("testdir/test.txt", false); + final static VirtualFile subdir = new VirtualFile("testdir/subdir", true); + final static VirtualFile subdirFile = new VirtualFile("testdir/subdir/subtest.txt", false); public boolean isRoot(File dir) { return bug6698013.root.equals(dir); @@ -87,11 +99,11 @@ public File[] getFiles(File dir, boolean hide_hidden) { if (dir.equals(bug6698013.root)) { - return new File[]{bug6698013.rootFile, bug6698013.subdir}; + return new File[]{rootFile, subdir}; } - if (dir.equals(bug6698013.subdir)) { - return new File[]{bug6698013.subdirFile}; + if (dir.equals(subdir)) { + return new File[]{subdirFile}; } return null; diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,17 @@ * @test * @bug 8080628 * @summary No mnemonics on Open and Save buttons in JFileChooser. - * @author Alexey Ivanov + * @requires os.family != "linux" + * @modules java.desktop/sun.swing + * @run main bug8080628 + */ + +/* + * @test + * @bug 8080628 + * @key headful + * @summary No mnemonics on Open and Save buttons in JFileChooser. + * @requires os.family == "linux" * @modules java.desktop/sun.swing * @run main bug8080628 */ @@ -81,8 +91,10 @@ try { UIManager.setLookAndFeel(info.getClassName()); } catch (final UnsupportedLookAndFeelException ignored) { + System.out.println("Unsupported L&F: " + info.getClassName()); continue; } + System.out.println("Testing L&F: " + info.getClassName()); for (Locale locale : LOCALES) { for (String key : MNEMONIC_KEYS) { diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/FileSystemView/WindowsDefaultIconSizeTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/FileSystemView/WindowsDefaultIconSizeTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/FileSystemView/WindowsDefaultIconSizeTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/FileSystemView/WindowsDefaultIconSizeTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -44,18 +44,16 @@ } public void test() { - String sep = System.getProperty("file.separator"); - String dir = System.getProperty("test.src", "."); String filename = "test.not"; - File testFile = new File(dir + sep + filename); + File testFile = new File(filename); try { if (!testFile.exists()) { testFile.createNewFile(); testFile.deleteOnExit(); } FileSystemView fsv = FileSystemView.getFileSystemView(); - Icon icon = fsv.getSystemIcon(new File(dir + sep + filename)); + Icon icon = fsv.getSystemIcon(new File(filename)); if (icon instanceof ImageIcon) { Image image = ((ImageIcon) icon).getImage(); if (image instanceof MultiResolutionImage) { diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/bug4587721.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/bug4587721.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFileChooser/bug4587721.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFileChooser/bug4587721.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4587721 + * @summary Tests if JFileChooser details view chops off text + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4587721 + */ + +import java.awt.Font; +import java.util.Enumeration; + +import javax.swing.JFileChooser; +import javax.swing.UIDefaults; +import javax.swing.UIManager; +import javax.swing.plaf.FontUIResource; +import javax.swing.plaf.metal.MetalLookAndFeel; + +public class bug4587721 { + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel(new MetalLookAndFeel()); + + String instructions = """ + Click on the Details button in JFileChooser Window. + If the filename text is chopped off by height, + then Press FAIL else Press PASS. + """; + + PassFailJFrame.builder() + .title("bug4587721") + .instructions(instructions) + .columns(40) + .testUI(bug4587721::createUI) + .build() + .awaitAndCheck(); + } + + public static JFileChooser createUI() { + setFonts(); + JFileChooser fc = new JFileChooser(); + return fc; + } + + public static void setFonts() { + UIDefaults defaults = UIManager.getDefaults(); + Enumeration keys = defaults.keys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (defaults.get(key) instanceof Font) + UIManager.put(key, new FontUIResource(new Font("Courier", Font.BOLD, 30))); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JFrame/DefaultCloseOperation.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JFrame/DefaultCloseOperation.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JFrame/DefaultCloseOperation.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JFrame/DefaultCloseOperation.java 2025-04-09 19:45:33.000000000 +0000 @@ -99,7 +99,6 @@ CloseOpFrame testFrame = new CloseOpFrame(); testFrame.setLocationRelativeTo(null); - PassFailJFrame.addTestWindow(testFrame); add(new JLabel("JFrame Default Close Operation:")); frameCloseOp = new JComboBox<>(); @@ -127,7 +126,6 @@ testDialog = new CloseOpDialog(testFrame); testDialog.setLocationRelativeTo(null); - PassFailJFrame.addTestWindow(testDialog); add(new JLabel("JDialog Default Close Operation:")); dialogCloseOp = new JComboBox<>(); diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,68 +21,61 @@ * questions. */ -/* @test +/* + * @test * @key headful * @bug 6725409 * @requires (os.family == "windows") * @summary Checks that JInternalFrame's system menu * can be localized during run-time - * @author Mikhail Lapshin - * @library /lib/client/ * @modules java.desktop/com.sun.java.swing.plaf.windows - * @build ExtendedRobot * @run main bug6725409 */ -import javax.swing.*; -import java.awt.*; +import java.awt.Robot; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel; +import com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane; public class bug6725409 { private JFrame frame; private JInternalFrame iFrame; - private TestTitlePane testTitlePane; - private boolean passed; - private static ExtendedRobot robot = createRobot(); + private static TestTitlePane testTitlePane; + private static volatile boolean passed; + private static Robot robot; public static void main(String[] args) throws Exception { - try { - UIManager.setLookAndFeel( - new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel()); - } catch(UnsupportedLookAndFeelException e) { - System.out.println("The test is for Windows LaF only"); - return; - } + UIManager.setLookAndFeel( + new WindowsClassicLookAndFeel()); + robot = new Robot(); final bug6725409 bug6725409 = new bug6725409(); try { - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.setupUIStep1(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::setupUIStep1); sync(); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.setupUIStep2(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::setupUIStep2); sync(); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.test(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::test); sync(); bug6725409.checkResult(); } finally { - if (bug6725409.frame != null) { - bug6725409.frame.dispose(); - } + SwingUtilities.invokeAndWait(() -> { + if (bug6725409.frame != null) { + bug6725409.frame.dispose(); + } + }); } } private void setupUIStep1() { - frame = new JFrame(); + frame = new JFrame("bug6725409"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JDesktopPane desktop = new JDesktopPane(); @@ -147,19 +140,9 @@ private static void sync() { robot.waitForIdle(); } - private static ExtendedRobot createRobot() { - try { - ExtendedRobot robot = new ExtendedRobot(); - return robot; - }catch(Exception ex) { - ex.printStackTrace(); - throw new Error("Unexpected Failure"); - } - } // Extend WindowsInternalFrameTitlePane to get access to systemPopupMenu - private class TestTitlePane extends - com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane { + private class TestTitlePane extends WindowsInternalFrameTitlePane { private JPopupMenu systemPopupMenu; public TestTitlePane(JInternalFrame f) { diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JPanel/bug4907772.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JPanel/bug4907772.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JPanel/bug4907772.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JPanel/bug4907772.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4907772 + * @summary 1.4 REGRESSION: JPanel responds to mouse clicks on overlapping JPanel + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4907772 { + static JFrame fr; + static JButton btn1; + static JButton btn2; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4907772"); + fr.getContentPane().setLayout(null); + + JPanel p = new JPanel(); + p.setLayout(null); + fr.getContentPane().add(p); + + btn1 = new JButton("Button 1"); + btn1.setBounds(0, 0, 200, 200); + + btn2 = new JButton("Button 2"); + btn2.setBounds(0, 0, 200, 200); + + p.add(btn1); + p.add(btn2); + + fr.setLocationRelativeTo(null); + fr.pack(); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Container root = btn1.getFocusCycleRootAncestor(); + FocusTraversalPolicy policy = root.getFocusTraversalPolicy(); + Component initial = policy.getInitialComponent(fr); + if (initial == btn2) { + throw new RuntimeException("The underlying button shouldn't be the initial component of FCR"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,79 +23,66 @@ /* * @test - * @key headful * @bug 4865918 + * @requires (os.family != "mac") * @summary REGRESSION:JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JScrollBar - * @author Andrey Pikalev * @run main bug4865918 */ -import javax.swing.*; -import java.awt.*; -import java.awt.event.*; -import java.util.*; +import java.awt.Dimension; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import java.util.Date; public class bug4865918 { private static TestScrollBar sbar; - private static JFrame frame; + private static final CountDownLatch mousePressLatch = new CountDownLatch(1); public static void main(String[] argv) throws Exception { - try { - Robot robot = new Robot(); - SwingUtilities.invokeAndWait(new Runnable() { - - public void run() { - createAndShowGUI(); - } - }); - - robot.waitForIdle(); - - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - sbar.pressMouse(); - } - }); - - robot.waitForIdle(); + String osName = System.getProperty("os.name"); + if (osName.toLowerCase().contains("os x")) { + System.out.println("This test is not for MacOS, considered passed."); + return; + } + SwingUtilities.invokeAndWait(() -> setupTest()); - int value = getValue(); + SwingUtilities.invokeAndWait(() -> sbar.pressMouse()); + if (!mousePressLatch.await(2, TimeUnit.SECONDS)) { + throw new RuntimeException("Timed out waiting for mouse press"); + } - if (value != 9) { - throw new Error("The scrollbar block increment is incorect"); - } - } finally { - if (frame != null) SwingUtilities.invokeAndWait(() -> frame.dispose()); + if (getValue() != 9) { + throw new RuntimeException("The scrollbar block increment is incorrect"); } } private static int getValue() throws Exception { final int[] result = new int[1]; - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - result[0] = sbar.getValue(); - } + SwingUtilities.invokeAndWait(() -> { + result[0] = sbar.getValue(); }); + System.out.println("value " + result[0]); return result[0]; } - private static void createAndShowGUI() { - frame = new JFrame("bug4865918"); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + private static void setupTest() { sbar = new TestScrollBar(JScrollBar.HORIZONTAL, -1, 10, -100, 100); sbar.setPreferredSize(new Dimension(200, 20)); sbar.setBlockIncrement(10); - - frame.getContentPane().add(sbar); - frame.pack(); - frame.setVisible(true); + sbar.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + mousePressLatch.countDown(); + } + }); } @@ -111,7 +98,7 @@ MouseEvent me = new MouseEvent(sbar, MouseEvent.MOUSE_PRESSED, (new Date()).getTime(), - MouseEvent.BUTTON1_MASK, + MouseEvent.BUTTON1_DOWN_MASK, 3 * getWidth() / 4, getHeight() / 2, 1, true); processMouseEvent(me); diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JScrollPane/bug4688907.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollPane/bug4688907.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JScrollPane/bug4688907.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JScrollPane/bug4688907.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4688907 + * @summary ScrollPaneLayout.minimumLayoutSize incorrectly compares hsbPolicy + */ + +import java.awt.Dimension; +import javax.swing.JScrollPane; + +public class bug4688907 { + public static void main(String[] args) throws Exception { + JScrollPane sp = new JScrollPane(); + Dimension d1 = sp.getMinimumSize(); + sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + Dimension d2 = sp.getMinimumSize(); + if (d1.height == d2.height) { + throw new RuntimeException("The scrollbar minimum size doesn't take " + + "into account horizontal scrollbar policy"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,13 +1,43 @@ +/* + * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ -import java.awt.*; +import java.awt.Component; +import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; + import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; -import javax.swing.*; +import javax.swing.Icon; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; import javax.swing.plaf.nimbus.NimbusLookAndFeel; /* @@ -22,7 +52,7 @@ private static volatile Exception exception = null; private static JFrame frame; - public static void main(String args[]) throws Exception { + public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTableHeader/bug4243927.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTableHeader/bug4243927.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTableHeader/bug4243927.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTableHeader/bug4243927.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4243927 + * @summary Tests that methods getAccessibleChild() and getAccessibleAt() + * of class JTableHeader.AccessibleJTableHeader do not throw NPE + */ + +import javax.accessibility.AccessibleComponent; +import javax.accessibility.AccessibleContext; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; + +public class bug4243927 { + public static void main(String[] argv) { + JTableHeader header = new JTableHeader(); + header.getColumnModel().addColumn(new TableColumn(0)); + + AccessibleContext c = header.getAccessibleContext(); + c.getAccessibleChild(0); + ((AccessibleComponent)c).getAccessibleAt(new java.awt.Point(0,0)); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4138694.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4138694.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4138694.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4138694.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4138694 + * @summary When adding an Action object to a toolbar, the Action object's + * SHORT_DESCRIPTION property (if present) should be automatically used + * for toolTip text. + * @run main bug4138694 + */ + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JComponent; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4138694 { + public static final String actionName = "Action"; + + private static class MyAction extends AbstractAction { + public void actionPerformed(ActionEvent e) {} + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar jtb = new JToolBar(); + MyAction aa = new MyAction(); + aa.putValue(Action.SHORT_DESCRIPTION, actionName); + jtb.add(aa); + JComponent c = (JComponent)jtb.getComponentAtIndex(0); + if (!c.getToolTipText().equals(actionName)) { + throw new RuntimeException("ToolTip not set automatically..."); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4140421.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4140421.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4140421.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4140421.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4140421 + * @summary Tests JToolBar set title correctly + * @run main bug4140421 + */ + +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4140421 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar("MyToolBar"); + if (!tb.getName().equals("MyToolBar")) { + throw new RuntimeException("Title of JToolBar set incorrectly..."); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4196662.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4196662.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4196662.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4196662.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4196662 + * @summary JToolBar has remove(int) method. + * @run main bug4196662 + */ + +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4196662 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar(); + tb.add(new JButton("Button1")); + JButton bt2 = new JButton("Button2"); + tb.add(bt2); + tb.add(new JButton("Button3")); + tb.remove(1); + if (tb.getComponentCount() != 2 || tb.getComponent(1) == bt2) { + throw new RuntimeException("Component wasn't removed..."); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4243930.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4243930.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4243930.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4243930.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4243930 + * @summary Tests that JToolBar.remove() does not throw StackOverflowError + * @run main bug4243930 + */ + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4243930 { + + private static class NullAction extends AbstractAction { + public void actionPerformed(ActionEvent e){} + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar(); + JButton test = tb.add(new NullAction()); + tb.remove(test); + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4368050.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4368050.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4368050.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4368050.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4368050 + * @summary Default toolbar layout manager should be serializable. + * @run main bug4368050 + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.swing.JToolBar; + +public class bug4368050 { + public static void main(String[] args) throws Exception { + JToolBar toolBar = new JToolBar(); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(toolBar); + byte[] buf = baos.toByteArray(); + try (ByteArrayInputStream bais = new ByteArrayInputStream(buf); + ObjectInputStream ois = new ObjectInputStream(bais)) { + ois.readObject(); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4465534.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4465534.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4465534.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4465534.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4465534 + * @summary Tests adding borderless button to a toolbar + * @run main bug4465534 + */ + +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4465534 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar toolbar = new JToolBar(); + JButton button = new JButton("text"); + button.setBorder(null); + toolbar.add(button); + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4700351.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4700351.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolBar/bug4700351.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolBar/bug4700351.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4700351 + * @summary Checks if JToolBar keeps orientation when dragged off + * @key headful + * @run main bug4700351 + */ + +import javax.swing.JFrame; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.plaf.basic.BasicToolBarUI; + +public class bug4700351 { + static JFrame fr; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4700351"); + JToolBar tb = new JToolBar(); + tb.setOrientation(JToolBar.VERTICAL); + fr.add(tb); + BasicToolBarUI ui = (javax.swing.plaf.basic.BasicToolBarUI) tb.getUI(); + if (!ui.isFloating()) { + ui.setFloatingLocation(100, 100); + ui.setFloating(true, tb.getLocation()); + } + if (tb.getOrientation() != JToolBar.VERTICAL) { + throw new RuntimeException("Error: toolbar's orientation " + + "has changed"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolTip/bug4107843.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolTip/bug4107843.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JToolTip/bug4107843.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JToolTip/bug4107843.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4107843 + * @summary ToolTipText for JTabbedPane. + * @run main bug4107843 + */ + +import javax.swing.JButton; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; + +public class bug4107843 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTabbedPane tp = new JTabbedPane(); + tp.add("First", new JButton("Button1")); + tp.add("Second", new JButton("Button2")); + tp.setToolTipTextAt(0, "first button"); + if (!tp.getToolTipTextAt(0).equals("first button")) { + throw new RuntimeException("ToolTipText isn't set " + + "as expected..."); + } + tp.setToolTipTextAt(1, "second button"); + if (!tp.getToolTipTextAt(1).equals("second button")) { + throw new RuntimeException("ToolTipText isn't set " + + "as expected..."); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4161685.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4161685.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4161685.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4161685.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4161685 + * @summary JTree now has the public methods setAnchorSelectionPath, + * getAnchorSelectionPath, setLeadSelectionPath. + * @run main bug4161685 + */ + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreePath; + +public class bug4161685 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTree tr = new JTree(); + TreePath tp = tr.getPathForRow(2); + tr.setAnchorSelectionPath(tp); + if (tr.getAnchorSelectionPath() != tp) { + throw new RuntimeException("AnchorSelectionPath isn't " + + "set correctly..."); + } + tr.setLeadSelectionPath(tp); + if (tr.getLeadSelectionPath() != tp) { + throw new RuntimeException("LeadSelectionPath isn't " + + "set correctly..."); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4210432.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4210432.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4210432.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4210432.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4210432 + * @summary Tests if JTree allows nodes not visible to be selected + * @run main bug4210432 + */ + +import javax.swing.JPanel; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; + +public class bug4210432 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JPanel p = new JPanel(); + DefaultMutableTreeNode expansible = + new DefaultMutableTreeNode("expansible"); + DefaultMutableTreeNode unexpansible = + new DefaultMutableTreeNode("unexpansible"); + DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); + DefaultMutableTreeNode subexpansible1 = + new DefaultMutableTreeNode("sub-expansible 1"); + DefaultMutableTreeNode subexpansible2 = + new DefaultMutableTreeNode("sub-expansible 2"); + DefaultMutableTreeNode subsubexpansible1 = + new DefaultMutableTreeNode("sub-sub-expansible 1"); + DefaultMutableTreeNode subsubexpansible2 = + new DefaultMutableTreeNode("sub-sub-expansible 2"); + expansible.add(subexpansible1); + expansible.add(subexpansible2); + subexpansible1.add(subsubexpansible1); + subexpansible1.add(subsubexpansible2); + root.add(expansible); + root.add(unexpansible); + DefaultTreeModel model = new DefaultTreeModel(root); + JTree t = new JTree(model); + Object[] tpa = {root, expansible, subexpansible1}; + Object[] tpa2 = {root, expansible}; + t.setExpandsSelectedPaths(false); + t.setSelectionPath(new TreePath(tpa)); + p.add(t); + if (t.isExpanded(new TreePath(tpa2))) { + throw new RuntimeException("Test failed: JTree should not have " + + "expanded path"); + } + t.clearSelection(); + t.setExpandsSelectedPaths(true); + t.setSelectionPath(new TreePath(tpa)); + if (!t.isExpanded(new TreePath(tpa2))) { + throw new RuntimeException("Test failed: JTree should have " + + "expanded path"); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4213868.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4213868.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4213868.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4213868.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4213868 + * @summary Tests if AccessibleJTreeNode.getAccessibleIndexInParent() returns + * correct value + * @run main bug4213868 + */ + +import javax.accessibility.AccessibleContext; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; + +public class bug4213868 { + public static JTree createTree() { + DefaultMutableTreeNode root = + new DefaultMutableTreeNode(0, true); + JTree tree = new JTree(root); + for (int i = 1; i < 10; i++) { + root.add(new DefaultMutableTreeNode(i)); + } + return tree; + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTree parent = createTree(); + AccessibleContext c = parent.getAccessibleContext() + .getAccessibleChild(0) + .getAccessibleContext(); + if (c.getAccessibleChild(1) + .getAccessibleContext() + .getAccessibleIndexInParent() != 1) { + throw new RuntimeException("Test failed: " + + "AccessibleJTreeNode.getAccessibleIndexInParent() " + + "returns incorrect value"); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4224491.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4224491.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4224491.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4224491.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4224491 + * @summary Tests if JTree's model & invokesStopCellEditing bound properties + * are working + * @run main bug4224491 + */ + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; + +public class bug4224491 { + private static boolean modelChanged = false; + private static boolean invokesStopCellEditingChanged = false; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + JTree jt = new JTree(new DefaultTreeModel(root)); + jt.addPropertyChangeListener(evt -> { + if (evt.getPropertyName().equals("model")) { + modelChanged = true; + } + if (evt.getPropertyName().equals("invokesStopCellEditing")) { + invokesStopCellEditingChanged = true; + } + }); + jt.setModel(new DefaultTreeModel(root)); + jt.setInvokesStopCellEditing(true); + if (!(modelChanged && invokesStopCellEditingChanged)) { + throw new RuntimeException("Test failed: JTree's model " + + "& invokesStopCellEditing bound properties " + + "are not working"); + } + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4237370.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4237370.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4237370.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4237370.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4237370 + * @summary Tests that JTree calls TreeExpansionListener methods + * after it has been updated due to expanded/collapsed event + * @run main bug4237370 + */ + +import java.lang.reflect.InvocationTargetException; + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeExpansionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeModel; + +public class bug4237370 { + static class TestTree extends JTree implements TreeExpansionListener { + int[] testMap = {1, 2}; + int testIndex = 0; + + private void testRowCount() { + int rows = getRowCount(); + if (rows != testMap[testIndex]) { + throw new RuntimeException("Bad row count: reported " + rows + + " instead of " + testMap[testIndex]); + } else { + testIndex++; + } + } + + public void treeExpanded(TreeExpansionEvent e) { + testRowCount(); + } + + public void treeCollapsed(TreeExpansionEvent e) { + testRowCount(); + } + + public TestTree() { + super((TreeModel)null); + DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root"); + top.add(new DefaultMutableTreeNode("Sub 1")); + setModel(new DefaultTreeModel(top)); + addTreeExpansionListener(this); + } + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + SwingUtilities.invokeAndWait(() -> { + TestTree tree = new TestTree(); + tree.collapseRow(0); + tree.expandRow(0); + }); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4662505.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4662505.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4662505.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4662505.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4662505 + * @summary IllegalArgumentException with empty JTree and key event + * @run main bug4662505 + */ + +import java.awt.event.KeyEvent; +import java.util.Date; + +import javax.swing.JTree; +import javax.swing.SwingUtilities; + +public class bug4662505 { + static DummyTree tree; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + tree = new DummyTree(); + + try { + tree.doTest(); + } catch (Exception e) { + throw new RuntimeException("Empty JTree shouldn't handle " + + "first letter navigation", e); + } + }); + } + + static class DummyTree extends JTree { + public DummyTree() { + super(new Object[]{}); + } + + public void doTest() { + KeyEvent key = new KeyEvent(tree, KeyEvent.KEY_TYPED, + new Date().getTime(), 0, KeyEvent.VK_UNDEFINED, 'a'); + processKeyEvent(key); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4696499.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4696499.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug4696499.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug4696499.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4696499 + * @summary new tree model asked about nodes of previous tree model + * @run main bug4696499 + */ + +import java.util.ArrayList; + +import javax.swing.JTree; +import javax.swing.event.TreeModelListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; + +public class bug4696499 { + public static void main(String[] args) throws Exception { + JTree tree = new JTree(); + TreeModel model = new MyModel(); + tree.setModel(model); + + tree.setSelectionRow(1); + model = new MyModel(); + tree.setModel(model); + } +} + +class MyModel implements TreeModel { + private Object root = "Root"; + private ArrayList listeners = new ArrayList(); + private TreeNode ONE; + static int next = 1; + + MyModel() { + ONE = new DefaultMutableTreeNode(next); + next *= 2; + } + + public void addTreeModelListener(TreeModelListener l) { + listeners.add(l); + } + + public void removeTreeModelListener(TreeModelListener l) { + listeners.remove(l); + } + + public void valueForPathChanged(TreePath tp, Object newValue) { + } + + public Object getRoot() { + return root; + } + + public boolean isLeaf(Object o) { + return o == ONE; + } + + public int getIndexOfChild(Object parent, Object child) { + if (parent != root || child != ONE) { + throw new RuntimeException("This method is called with the child " + + "of the previous tree model"); + } + return 0; + } + + public int getChildCount(Object o) { + if (o == root) { + return 1; + } + if (o == ONE) { + return 0; + } + throw new IllegalArgumentException(o.toString()); + } + + public Object getChild(Object o, int index) { + if (o != root || index != 0) { + throw new IllegalArgumentException(o + ", " + index); + } + return ONE; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug5039542.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug5039542.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JTree/bug5039542.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JTree/bug5039542.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 5039542 + * @summary JTree's setToolTipText() doesn't work + * @run main bug5039542 + */ + +import javax.swing.JTree; + +public class bug5039542 { + public static void main(String[] args) throws Exception { + final String exampleStr = "TEST"; + JTree tree = new JTree(); + tree.setToolTipText(exampleStr); + if (tree.getToolTipText(null) != exampleStr) { + throw new RuntimeException("The default JTree tooltip text " + + "have to be used if renderer doesn't provide it."); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JViewport/bug4546474.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4546474.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JViewport/bug4546474.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4546474.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4546474 + * @summary JScrollPane's always-visible scrollbars not updated when + * viewport is replaced + * @run main bug4546474 + */ + +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; + +public class bug4546474 { + public static void main(String[] args) { + JPanel panel = new JPanel(); + JScrollPane scrollpane = new JScrollPane(panel, + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + JScrollBar sbar = scrollpane.getVerticalScrollBar(); + + scrollpane.setViewportView(null); + + if (sbar.getVisibleAmount() > 0) { + throw new RuntimeException("Vertical scrollbar is not " + + "updated when viewport is replaced"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/JViewport/bug4677611.java openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4677611.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/JViewport/bug4677611.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/JViewport/bug4677611.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4677611 + * @summary JViewport sets Opaque after UpdateUI (prevents UI delegates + * to determine look) + * @run main bug4677611 + */ + +import java.awt.Color; + +import javax.swing.JScrollPane; +import javax.swing.JViewport; + +public class bug4677611 { + public static void main(String[] args) throws Exception { + JScrollPane sp = new JScrollPane(); + JViewport vp = new MyViewport(); + vp.setBackground(Color.blue); + sp.setViewport(vp); + + if (vp.isOpaque()) { + throw new RuntimeException("JViewport shouldn't set Opaque " + + "after update the UI"); + } + } + + static class MyViewport extends JViewport { + public void updateUI() { + setOpaque(false); + super.updateUI(); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/KeyboardManager/bug4345798.java openjdk-17-17.0.15+6/test/jdk/javax/swing/KeyboardManager/bug4345798.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/KeyboardManager/bug4345798.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/KeyboardManager/bug4345798.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4345798 + * @summary Tests if Pressing enter to dismiss menu works when a JRootPane + * has a default button. + * @key headful + * @run main bug4345798 + */ + +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JRootPane; +import javax.swing.SwingUtilities; + +public class bug4345798 { + private static JFrame f; + private static JButton b; + private static JMenu menu; + private static volatile boolean passed = true; + private static volatile Point p; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4345798"); + JMenuBar mbar = new JMenuBar(); + JMenuItem item = new JMenuItem("Open..."); + menu = new JMenu("File"); + item.addActionListener(new TestActionListener()); + menu.add(item); + mbar.add(menu); + + f.setJMenuBar(mbar); + + b = new JButton("Default"); + b.addActionListener(new TestActionListener()); + f.getContentPane().add(b); + JRootPane rp = f.getRootPane(); + rp.setDefaultButton(b); + + f.setSize(200, 200); + f.setLocationRelativeTo(null); + f.setVisible(true); + b.requestFocus(); + }); + + Robot robot = new Robot(); + robot.setAutoDelay(100); + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> p = menu.getLocationOnScreen()); + robot.mouseMove(p.x, p.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + + robot.keyPress(KeyEvent.VK_F10); + robot.keyRelease(KeyEvent.VK_F10); + + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + + if (!passed) { + throw new RuntimeException("Test failed."); + } + } + + static class TestActionListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == b) { + passed = false; + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/bug4306431.java openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4306431.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/bug4306431.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4306431.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4306431 + * @summary Tests that Metal themes allow font definition for JList + */ + +import java.awt.Font; +import javax.swing.LookAndFeel; +import javax.swing.plaf.FontUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; + +public class bug4306431 { + static final Font FONT = new Font(Font.MONOSPACED, Font.ITALIC, 24); + + public static void main(String[] argv) throws Exception { + MetalLookAndFeel.setCurrentTheme(new TestMetalTheme()); + LookAndFeel laf = new MetalLookAndFeel(); + Font font = laf.getDefaults().getFont("List.font"); + if (!font.equals(FONT)) { + throw new RuntimeException("Failed: font wasn't customized"); + } + } + + static class TestMetalTheme extends DefaultMetalTheme { + public FontUIResource getControlTextFont() { + return new FontUIResource(FONT); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/bug4736093.java openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4736093.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/bug4736093.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/bug4736093.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4736093 + * @requires (os.family == "windows") + * @summary REGRESSION: Menu and controls shortcuts are not visible in Win L&F in jdk1.4.1 + * @modules java.desktop/com.sun.java.swing.plaf.windows + * @key headful + */ + +import java.awt.Robot; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.MenuElement; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; + +public class bug4736093 { + static volatile boolean passed = true; + static volatile boolean done = false; + static volatile boolean winlaf = true; + static JFrame mainFrame = null; + static Robot robo; + + public static void main(String args[]) throws Exception { + try { + robo = new Robot(); + + SwingUtilities.invokeAndWait(() -> { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception ex) { + winlaf = false; + } + + if (winlaf && WindowsLookAndFeel.isMnemonicHidden()) { + mainFrame = new JFrame("Bug 4736093"); + mainFrame.addWindowListener(new TestStateListener()); + mainFrame.setSize(200, 400); + mainFrame.setLocationRelativeTo(null); + mainFrame.setVisible(true); + } else { + System.out.println("Test is not for this system. Passed."); + } + }); + + robo.waitForIdle(); + robo.delay(1000); + + if (!passed) { + throw new RuntimeException("Test failed."); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (mainFrame != null) { + mainFrame.dispose(); + } + }); + } + } + + public static void addMenuBar() { + JMenuBar mbar = new JMenuBar(); + JMenu menu = new JMenu("File"); + for (int i = 1; i < 5; i++) { + menu.add(new JMenuItem("Menu Item " + i)); + } + mbar.add(menu); + mainFrame.setJMenuBar(mbar); + } + + + public static void checkForMnemonics(boolean expected) { + if (expected != WindowsLookAndFeel.isMnemonicHidden()) { + passed = false; + } + } + + public static class TestStateListener extends WindowAdapter { + public void windowOpened(WindowEvent ev) { + try { + new Thread(new RobotThread()).start(); + } catch (Exception ex) { + throw new RuntimeException("Thread Exception"); + } + } + } + + public static class RobotThread implements Runnable { + public void run() { + MenuElement[] path; + int altKey = java.awt.event.KeyEvent.VK_ALT; + robo.setAutoDelay(3000); // 3 seconds delay + robo.waitForIdle(); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(false); // mnemonics should appear on press + robo.keyRelease(altKey); + robo.delay(1000); + + checkForMnemonics(true); // and disappear on release + robo.keyPress(java.awt.event.KeyEvent.VK_ESCAPE); + robo.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE); + robo.delay(1000); + + addMenuBar(); + robo.delay(1000); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(false); // mnemonics should appear on press + robo.keyRelease(altKey); + robo.delay(1000); + + checkForMnemonics(false); // and stay appeared in selected menu + path = MenuSelectionManager.defaultManager().getSelectedPath(); + if (path.length == 0) { + passed = false; // menu should be selected + } + robo.delay(1000); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(true); // and only now disappear + path = MenuSelectionManager.defaultManager().getSelectedPath(); + if (path.length != 0) { + passed = false; // menu should be deselected + } + robo.keyRelease(altKey); + done = true; + robo.delay(1000); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4236213 + * @summary Regression test isJavaLAFLockedCorrectly.java Failing with JDK-1.2.2-R + */ + +import javax.swing.LookAndFeel; + +public class isJavaLAFLockedCorrectly { + public static void main(String[] args) { + System.out.println(" === isJavaLAFLockedCorrectly === "); + + LookAndFeel newJLF; + try { + // try to make a version of the JLF + Class jlfClass = Class.forName("javax.swing.plaf.metal.MetalLookAndFeel"); + newJLF = (LookAndFeel) (jlfClass.newInstance()); + } catch (Exception e) { + // if any of these things didn't work, throw an exception + throw new RuntimeException("JLF not correctly (un)locked " + + "- Class files probably missing"); + } + + // see if the JLF is supported here + // it sure better be as it's supposed to be supported everywhere + if (newJLF.isSupportedLookAndFeel() == true) { + System.out.println("\t JLF correctly locked"); + } else { + throw new RuntimeException("JLF not correctly (un)locked"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + */ + +import javax.swing.LookAndFeel; + +public class isMultiLAFLockedCorrectly { + public static void main(String[] args) { + System.out.println(" === isMultiLAFLockedCorrectly === "); + + LookAndFeel newMulti; + try { + // try to make a version of the Multi L&F + Class multiClass = Class.forName("javax.swing.plaf.multi.MultiLookAndFeel"); + newMulti = (LookAndFeel) (multiClass.newInstance()); + } catch (Exception e) { + // if any of these things didn't work, throw an exception + throw new RuntimeException("Multi L&F not correctly locked " + + "- Class files probably missing"); + } + + // see if the Multi L&F is supported here + // it sure better be as it's supposed to be supported everywhere + if (newMulti.isSupportedLookAndFeel() == true) { + System.out.println("\t Multi L&F correctly locked"); + } else { + throw new RuntimeException("Multi L&F not correctly locked"); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java openjdk-17-17.0.15+6/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4221007 + * @summary Tests whether MetalInternalFrameTitlePane is public + */ + +import javax.swing.JInternalFrame; +import javax.swing.plaf.metal.MetalInternalFrameTitlePane; + +public class bug4221007 { + public static void main(String[] args) { + MetalInternalFrameTitlePane mitftp = + new MetalInternalFrameTitlePane(new JInternalFrame()); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,71 +25,88 @@ * @test * @key headful * @bug 6276087 - * @author Romain Guy * @summary Tests opacity of a popup menu. */ -import java.awt.*; -import java.awt.event.*; - -import javax.swing.*; +import java.awt.Point; +import java.awt.Dimension; +import java.awt.Robot; +import java.awt.event.InputEvent; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; import static javax.swing.UIManager.LookAndFeelInfo; import static javax.swing.UIManager.getInstalledLookAndFeels; import static javax.swing.UIManager.setLookAndFeel; -public class NonOpaquePopupMenuTest extends JFrame { +public class NonOpaquePopupMenuTest { private static JMenu fileMenu; + private static JFrame frame; private static final String AQUALAF="com.apple.laf.AquaLookAndFeel"; + private volatile static Point p; + private volatile static Dimension size; - public NonOpaquePopupMenuTest() { - getContentPane().setBackground(java.awt.Color.RED); + private static void createUI() { + frame = new JFrame(); + frame.getContentPane().setBackground(java.awt.Color.RED); JMenuBar menuBar = new JMenuBar(); fileMenu = new JMenu("File"); JMenuItem menuItem = new JMenuItem("New"); menuBar.add(fileMenu); - setJMenuBar(menuBar); + frame.setJMenuBar(menuBar); fileMenu.add(menuItem); fileMenu.getPopupMenu().setOpaque(false); - setSize(new Dimension(640, 480)); - setLocationRelativeTo(null); - setVisible(true); + frame.setSize(new Dimension(640, 480)); + frame.setLocationRelativeTo(null); + frame.setVisible(true); } public static void main(String[] args) throws Throwable { LookAndFeelInfo[] lookAndFeelInfoArray = getInstalledLookAndFeels(); + Robot robot = new Robot(); + robot.setAutoDelay(100); for (LookAndFeelInfo lookAndFeelInfo : lookAndFeelInfoArray) { - System.out.println(lookAndFeelInfo.getClassName()); - if ( AQUALAF == lookAndFeelInfo.getClassName()) { - System.out.println("This test scenario is not applicable for" + - " Aqua LookandFeel and hence skipping the validation"); - continue; - } - setLookAndFeel(lookAndFeelInfo.getClassName()); - Robot robot = new Robot(); - robot.setAutoDelay(250); - - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - new NonOpaquePopupMenuTest(); + try { + System.out.println(lookAndFeelInfo.getClassName()); + if ( AQUALAF == lookAndFeelInfo.getClassName()) { + System.out.println("This test scenario is not applicable for" + + " Aqua LookandFeel and hence skipping the validation"); + continue; } - }); + robot.delay(1000); + setLookAndFeel(lookAndFeelInfo.getClassName()); + + SwingUtilities.invokeAndWait(() -> createUI()); - robot.waitForIdle(); + robot.waitForIdle(); + robot.delay(1000); - Point p = getMenuClickPoint(); - robot.mouseMove(p.x, p.y); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + SwingUtilities.invokeAndWait(() -> { + p = fileMenu.getLocationOnScreen(); + size = fileMenu.getSize(); + }); + robot.mouseMove(p.x + size.width / 2, p.y + size.height / 2); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.waitForIdle(); + robot.waitForIdle(); - if (isParentOpaque()) { - throw new RuntimeException("Popup menu parent is opaque"); + if (isParentOpaque()) { + throw new RuntimeException("Popup menu parent is opaque"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } } @@ -107,23 +124,4 @@ return result[0]; } - - private static Point getMenuClickPoint() throws Exception { - final Point[] result = new Point[1]; - - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - Point p = fileMenu.getLocationOnScreen(); - Dimension size = fileMenu.getSize(); - - result[0] = new Point(p.x + size.width / 2, - p.y + size.height / 2); - } - }); - - return result[0]; - - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java openjdk-17-17.0.15+6/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java 2025-04-09 19:45:33.000000000 +0000 @@ -29,66 +29,64 @@ * @run main ProgressMonitorEscapeKeyPress */ -import java.awt.AWTException; -import java.awt.EventQueue; -import java.awt.Robot; -import java.awt.event.KeyEvent; + import javax.swing.JFrame; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; public class ProgressMonitorEscapeKeyPress { + static volatile int counter = 0; static ProgressMonitor monitor; - static int counter = 0; - static TestThread robotThread; + static TestThread testThread; static JFrame frame; + static CountDownLatch progressLatch; + static Robot robot; public static void main(String[] args) throws Exception { - - createTestUI(); - - monitor = new ProgressMonitor(frame, "Progress", null, 0, 100); - - robotThread = new TestThread(); - robotThread.start(); - - for (counter = 0; counter <= 100; counter += 10) { - Thread.sleep(1000); - - EventQueue.invokeAndWait(new Runnable() { - @Override - public void run() { - if (!monitor.isCanceled()) { - monitor.setProgress(counter); - System.out.println("Progress bar is in progress"); - } - } - }); - - if (monitor.isCanceled()) { - break; + try { + progressLatch = new CountDownLatch(20); + createTestUI(); + robot = new Robot(); + robot.setAutoDelay(50); + robot.setAutoWaitForIdle(true); + testThread = new TestThread(); + testThread.start(); + Thread.sleep(100); + if (progressLatch.await(15, TimeUnit.SECONDS)) { + System.out.println("Progress monitor completed 20%, lets press Esc..."); + robot.keyPress(KeyEvent.VK_ESCAPE); + robot.keyRelease(KeyEvent.VK_ESCAPE); + System.out.println("ESC pressed...."); + } else { + System.out.println("Failure : No status available from Progress monitor..."); + throw new RuntimeException( + "Can't get the status from Progress monitor even after waiting too long.."); } - } - disposeTestUI(); - - if (counter >= monitor.getMaximum()) { - throw new RuntimeException("Escape key did not cancel the ProgressMonitor"); + if (counter >= monitor.getMaximum()) { + throw new RuntimeException("Escape key did not cancel the ProgressMonitor"); + } + System.out.println("Test Passed..."); + } finally { + disposeTestUI(); } } - private static void createTestUI() throws Exception { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - frame = new JFrame("Test"); - frame.setSize(300, 300); - frame.setLocationByPlatform(true); - frame.setVisible(true); - }}); - } + private static void createTestUI() throws Exception { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame("Test"); + frame.setSize(300, 300); + monitor = new ProgressMonitor(frame, "Progress", "1", 0, 100); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setLocationByPlatform(true); + }); + } private static void disposeTestUI() throws Exception { @@ -100,26 +98,25 @@ class TestThread extends Thread { - - Robot testRobot; - - TestThread() throws AWTException { - super(); - testRobot = new Robot(); - } - @Override public void run() { - try { - // Sleep for 5 seconds - so that the ProgressMonitor starts - Thread.sleep(5000); - - // Press and release Escape key - testRobot.keyPress(KeyEvent.VK_ESCAPE); - testRobot.delay(20); - testRobot.keyRelease(KeyEvent.VK_ESCAPE); - } catch (InterruptedException ex) { - throw new RuntimeException("Exception in TestThread"); + System.out.println("TestThread started........."); + for (ProgressMonitorEscapeKeyPress.counter = 0; + ProgressMonitorEscapeKeyPress.counter <= 100; + ProgressMonitorEscapeKeyPress.counter += 1) { + ProgressMonitorEscapeKeyPress.robot.delay(100); + ProgressMonitor monitor = ProgressMonitorEscapeKeyPress.monitor; + if (!monitor.isCanceled()) { + monitor.setNote("" + ProgressMonitorEscapeKeyPress.counter); + monitor.setProgress(ProgressMonitorEscapeKeyPress.counter); + ProgressMonitorEscapeKeyPress.progressLatch.countDown(); + System.out.println("Progress bar is in progress....." + + ProgressMonitorEscapeKeyPress.counter + "%"); + } + if (monitor.isCanceled()) { + System.out.println("$$$$$$$$$$$$$$$ Monitor canceled"); + break; + } } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java openjdk-17-17.0.15+6/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4753342 + * @key headful + * @summary Makes sure add/remove/setLayout redirect to the contentpane + */ + +import java.awt.Container; +import java.awt.GridLayout; +import java.awt.LayoutManager; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JWindow; +import javax.swing.RootPaneContainer; +import javax.swing.SwingUtilities; + +public class RootPaneChecking { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + MyJFrame frame = new MyJFrame(); + frame.setTitle("RootPaneChecking"); + checkRootPaneCheckingEnabled(frame); + frame.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(frame); + + MyJWindow window = new MyJWindow(); + checkRootPaneCheckingEnabled(window); + window.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(window); + + MyJDialog dialog = new MyJDialog(); + checkRootPaneCheckingEnabled(dialog); + dialog.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(dialog); + + MyJInternalFrame iframe = new MyJInternalFrame(); + checkRootPaneCheckingEnabled(iframe); + iframe.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(iframe); + }); + } + + private static void checkRootPaneCheckingEnabled(RootPaneContainer rpc) { + Container parent = (Container) rpc; + Container cp = rpc.getContentPane(); + // Test add + JButton button = new JButton("RootPaneChecking"); + parent.add(button); + if (button.getParent() != cp) { + throw new RuntimeException("Add parent mismatch, want: " + + cp + " got " + button.getParent()); + } + + // Test remove + parent.remove(button); + if (button.getParent() != null) { + throw new RuntimeException("Remove mismatch, want null got " + + button.getParent()); + } + + // Test setLayout + LayoutManager manager = new GridLayout(); + parent.setLayout(manager); + if (manager != cp.getLayout()) { + throw new RuntimeException("LayoutManager mismatch, want: " + + manager + " got " + cp.getLayout()); + } + } + + private static void checkRootPaneCheckingDisabled(RootPaneContainer rpc) { + Container parent = (Container) rpc; + Container cp = rpc.getContentPane(); + + // Test add + JButton button = new JButton("RootPaneChecking"); + parent.add(button); + if (button.getParent() != parent) { + throw new RuntimeException("Add parent mismatch, want: " + + parent + " got " + button.getParent()); + } + + // Test setLayout + LayoutManager manager = new GridLayout(); + parent.setLayout(manager); + if (manager != parent.getLayout()) { + throw new RuntimeException("LayoutManager mismatch, want: " + + manager + " got " + cp.getLayout()); + } + } + + static class MyJFrame extends JFrame { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJWindow extends JWindow { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJDialog extends JDialog { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJInternalFrame extends JInternalFrame { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/SpringLayout/bug4756178.java openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4756178.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/SpringLayout/bug4756178.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4756178.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4756178 + * @summary SpringLayout:applyDefaults() discards size information when right-aligning. + * @key headful + */ + +import java.awt.Dimension; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.Spring; +import javax.swing.SpringLayout; +import javax.swing.SwingUtilities; + +public class bug4756178 { + static JFrame fr; + static JButton bt; + static volatile Dimension buttonPreferredSize; + static volatile Dimension actualSize; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4756178"); + JPanel p = (JPanel) fr.getContentPane(); + SpringLayout layout = new SpringLayout(); + p.setLayout(layout); + + SpringLayout.Constraints cc = new SpringLayout.Constraints(); + cc.setConstraint("East", + Spring.sum(Spring.constant(-20), + layout.getConstraint("East", p))); + cc.setConstraint("South", + Spring.sum(Spring.constant(-20), + layout.getConstraint("South", p))); + + bt = new JButton(); + + buttonPreferredSize = new Dimension(20, 20); + bt.setPreferredSize(buttonPreferredSize); + p.add(bt, cc); + + fr.setSize(200, 200); + fr.setLocationRelativeTo(null); + fr.setVisible(true); + }); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + actualSize = bt.getSize(); + }); + + if (!buttonPreferredSize.equals(actualSize)) { + throw new RuntimeException("Button size is " + actualSize + + ", should be " + buttonPreferredSize); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/SpringLayout/bug4803649.java openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4803649.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/SpringLayout/bug4803649.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/SpringLayout/bug4803649.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4803649 + * @summary setWidth() doesn't work on the container in a SpringLayout + * @key headful + */ + +import java.awt.Dimension; +import java.awt.Robot; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.Spring; +import javax.swing.SpringLayout; +import javax.swing.SwingUtilities; + +public class bug4803649 { + static JFrame fr; + static JPanel panel; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4803649"); + + panel = new JPanel(); + SpringLayout layout = new SpringLayout(); + panel.setLayout(layout); + + JTextArea textArea = new JTextArea("asasddsa"); + textArea.setPreferredSize(new Dimension(200, 200)); + panel.add(textArea); + SpringLayout.Constraints cCons = layout.getConstraints(textArea); + cCons.setX(Spring.constant(10)); + cCons.setY(Spring.constant(10)); + + SpringLayout.Constraints pCons = layout.getConstraints(panel); + pCons.setWidth(Spring.sum(Spring.constant(10), + cCons.getConstraint("East"))); + pCons.setHeight(Spring.sum(Spring.constant(10), + cCons.getConstraint("South"))); + + fr.getContentPane().add(panel); + + fr.setLocationRelativeTo(null); + fr.pack(); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Dimension d = panel.getSize(); + if (d.width < 220 || d.height < 220) { + throw new RuntimeException("JPanel with the SpringLayout is too small"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/ToolTipManager/bug5078214.java openjdk-17-17.0.15+6/test/jdk/javax/swing/ToolTipManager/bug5078214.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/ToolTipManager/bug5078214.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/ToolTipManager/bug5078214.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 5078214 + * @key headful + * @summary ToolTip is shown partially when the application is near the bottom of screen. + * @library /test/lib + * @build jtreg.SkippedException + * @run main bug5078214 + */ + +import java.awt.BorderLayout; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.MouseEvent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.ToolTipManager; + +import jtreg.SkippedException; + +public class bug5078214 { + static volatile boolean passed = false; + + static volatile JFrame mainFrame; + static volatile Rectangle bounds; + static volatile Insets insets; + static Robot robot; + + public static void main(String[] args) throws Exception { + try { + if (getGraphicsConfig() == null) { + throw new SkippedException("We need at least one screen " + + "with the taskbar at the bottom position."); + } + bounds = getGraphicsConfig().getBounds(); + + SwingUtilities.invokeAndWait(() -> { + mainFrame = new JFrame("bug5078214"); + mainFrame.setLayout(new BorderLayout()); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JButton button = new JButton("Button with tooltip") { + public Point getToolTipLocation(MouseEvent ev) { + return new Point(100, 100); + } + }; + mainFrame.add(button, BorderLayout.CENTER); + button.setToolTipText("ToolTip for this button"); + + // Position frame + mainFrame.setSize(200, 200); + int x = bounds.x + 200; + int y = bounds.y + bounds.height - insets.bottom - 100; + mainFrame.setLocation(x, y); + mainFrame.setVisible(true); + }); + + robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + test(bounds, insets); + + if (!passed) { + throw new RuntimeException("ToolTip shown outside of the visible area. Test failed."); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (mainFrame != null) { + mainFrame.dispose(); + } + }); + } + } + + public static void test(Rectangle b, Insets i) throws Exception { + SwingUtilities.invokeAndWait(() -> { + ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); + ToolTipManager.sharedInstance().setInitialDelay(100); + }); + + robot.mouseMove(b.x + 300, b.y + b.height - i.bottom - 10); + robot.delay(500); + Window[] ow = mainFrame.getOwnedWindows(); + if (ow == null || ow.length < 1) { + throw new RuntimeException("No owned windows for JFrame - no tooltip shown?"); + } + + Window ttwnd = ow[0]; + int wy = ttwnd.getBounds().y + ttwnd.getBounds().height - 1; + passed = wy < (b.y + b.height - i.bottom); + } + + public static GraphicsConfiguration getGraphicsConfig() { + GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getScreenDevices(); + for (GraphicsDevice device : devices) { + GraphicsConfiguration config = device.getDefaultConfiguration(); + insets = Toolkit.getDefaultToolkit().getScreenInsets(config); + if (insets.bottom != 0) { + return config; + } + } + return null; + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java 2025-04-09 19:45:33.000000000 +0000 @@ -26,28 +26,41 @@ * @key headful * @bug 4983388 8015600 * @summary shortcuts on menus do not work on JDS - * @author Oleg Mokhovikov * @library ../../../../regtesthelpers * @build Util * @run main bug4983388 */ -import java.awt.*; -import javax.swing.*; -import javax.swing.event.MenuListener; -import javax.swing.event.MenuEvent; +import java.awt.Robot; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.MenuEvent; +import javax.swing.event.MenuListener; + +import static java.util.concurrent.TimeUnit.SECONDS; public class bug4983388 { - static volatile boolean bMenuSelected = false; static JFrame frame; + private static final CountDownLatch menuSelected = new CountDownLatch(1); + private static class TestMenuListener implements MenuListener { + @Override public void menuCanceled(MenuEvent e) {} + @Override public void menuDeselected(MenuEvent e) {} + + @Override public void menuSelected(MenuEvent e) { System.out.println("menuSelected"); - bMenuSelected = true; + menuSelected.countDown(); } } @@ -56,28 +69,24 @@ JMenu menu = new JMenu("File"); menu.setMnemonic('F'); menuBar.add(menu); - frame = new JFrame(); + menu.addMenuListener(new TestMenuListener()); + + frame = new JFrame("bug4983388"); frame.setJMenuBar(menuBar); frame.setLocationRelativeTo(null); - frame.pack(); + frame.setSize(250, 100); frame.setVisible(true); - MenuListener listener = new TestMenuListener(); - menu.addMenuListener(listener); } public static void main(String[] args) throws Exception { - try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (UnsupportedLookAndFeelException | ClassNotFoundException ex) { - System.err.println("GTKLookAndFeel is not supported on this platform. Using defailt LaF for this platform."); + System.err.println("GTKLookAndFeel is not supported on this platform. " + + "Using default LaF for this platform."); } - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - createAndShowGUI(); - } - }); + SwingUtilities.invokeAndWait(bug4983388::createAndShowGUI); Robot robot = new Robot(); robot.setAutoDelay(50); @@ -85,13 +94,13 @@ robot.delay(500); Util.hitMnemonics(robot, KeyEvent.VK_F); - robot.waitForIdle(); - robot.delay(500); - - SwingUtilities.invokeAndWait(() -> frame.dispose()); - if (!bMenuSelected) { - throw new RuntimeException("shortcuts on menus do not work"); + try { + if (!menuSelected.await(1, SECONDS)) { + throw new RuntimeException("shortcuts on menus do not work"); + } + } finally { + SwingUtilities.invokeAndWait(frame::dispose); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +import jtreg.SkippedException; + +/* + * @test + * @bug 4419255 + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame + * @summary Tests if Metal Slider's thumb isn't clipped + * @run main/manual bug4419255 + */ + +public class bug4419255 { + + public static void main(String[] args) throws Exception { + + // ColorChooser UI design is different for GTK L&F. + // There is no RGB tab available for GTK L&F, skip the testing. + if (UIManager.getLookAndFeel().getName().contains("GTK")) { + throw new SkippedException("Test not applicable for GTK L&F"); + } + String instructions = """ + Choose RGB tab. If sliders' thumbs are painted correctly + (top is not clipped, black line is visible), + then test passed. Otherwise it failed."""; + + PassFailJFrame.builder() + .title("bug4419255") + .instructions(instructions) + .columns(40) + .testUI(bug4419255::createColorChooser) + .build() + .awaitAndCheck(); + } + + private static JColorChooser createColorChooser() { + return new JColorChooser(Color.BLUE); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/reliability/HangDuringStaticInitialization.java openjdk-17-17.0.15+6/test/jdk/javax/swing/reliability/HangDuringStaticInitialization.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/reliability/HangDuringStaticInitialization.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/reliability/HangDuringStaticInitialization.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,6 +33,7 @@ /** * @test * @bug 8189604 8208702 + * @requires !vm.debug | os.family != "windows" * @run main/othervm -Djava.awt.headless=false HangDuringStaticInitialization * @run main/othervm -Djava.awt.headless=true HangDuringStaticInitialization */ diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,10 +21,17 @@ * questions. */ -import javax.swing.*; -import java.awt.*; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JTextField; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; import java.awt.event.InputEvent; -import java.awt.image.BufferedImage; /** * @test @@ -39,7 +46,6 @@ private static JTextField field1; private static JTextField field2; private static JFrame frame; - private static Rectangle bounds; private static JMenu menu; private static JTextField anotherWindow; private static Point menuLoc; @@ -67,17 +73,9 @@ Robot robot = new Robot(); robot.waitForIdle(); robot.delay(200); - SwingUtilities.invokeAndWait(() -> { - bounds = field2.getBounds(); - bounds.setLocation(field2.getLocationOnScreen()); - }); - BufferedImage nosel = robot.createScreenCapture(bounds); SwingUtilities.invokeAndWait(field2::requestFocus); SwingUtilities.invokeAndWait(field2::selectAll); - robot.waitForIdle(); - robot.delay(200); - BufferedImage sel = robot.createScreenCapture(bounds); SwingUtilities.invokeAndWait(() -> { menuLoc = menu.getLocationOnScreen(); @@ -89,7 +87,7 @@ robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.waitForIdle(); robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { + if (!field2.getCaret().isSelectionVisible()) { throw new RuntimeException("Test fails: menu hides selection"); } @@ -98,7 +96,7 @@ SwingUtilities.invokeAndWait(field1::requestFocus); robot.waitForIdle(); robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), nosel)) { + if (field2.getCaret().isSelectionVisible()) { throw new RuntimeException( "Test fails: focus lost doesn't hide selection"); } @@ -119,35 +117,12 @@ SwingUtilities.invokeAndWait(anotherWindow::requestFocus); robot.waitForIdle(); robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), nosel)) { + if (!field2.getCaret().isSelectionVisible()) { throw new RuntimeException( "Test fails: switch window hides selection"); } - SwingUtilities.invokeAndWait(anotherWindow::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: selection ownership is lost selection is shown"); - } - SwingUtilities.invokeLater(frame2::dispose); SwingUtilities.invokeLater(frame::dispose); } - - static boolean biEqual(BufferedImage i1, BufferedImage i2) { - if (i1.getWidth() == i2.getWidth() && - i1.getHeight() == i2.getHeight()) { - for (int x = 0; x < i1.getWidth(); x++) { - for (int y = 0; y < i1.getHeight(); y++) { - if (i1.getRGB(x, y) != i2.getRGB(x, y)) { - return false; - } - } - } - return true; - } - return false; - } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,10 +21,17 @@ * questions. */ -import javax.swing.*; -import java.awt.*; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JTextField; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; import java.awt.event.InputEvent; -import java.awt.image.BufferedImage; /** * @test @@ -40,131 +47,113 @@ private static JTextField field1; private static JTextField field2; private static JFrame frame; - private static Rectangle bounds; private static JMenu menu; private static JTextField anotherWindow; private static Point menuLoc; private static JFrame frame2; public static void main(String[] args) throws Exception { - SwingUtilities.invokeAndWait(() -> { - frame = new JFrame(); - field1 = new JTextField("field1 "); - field2 = new JTextField("field2 "); - field1.setEditable(false); - field2.setEditable(false); - frame.getContentPane().setLayout(new FlowLayout()); - frame.getContentPane().add(field1); - frame.getContentPane().add(field2); - JMenuBar menuBar = new JMenuBar(); - menu = new JMenu("menu"); - menu.add(new JMenuItem("item")); - menuBar.add(menu); - frame.setJMenuBar(menuBar); - frame.pack(); - frame.setVisible(true); - }); - - Robot robot = new Robot(); - robot.waitForIdle(); - robot.delay(200); - SwingUtilities.invokeAndWait(() -> { - bounds = field2.getBounds(); - bounds.setLocation(field2.getLocationOnScreen()); - }); - BufferedImage nosel = robot.createScreenCapture(bounds); - - SwingUtilities.invokeAndWait(field2::requestFocus); - SwingUtilities.invokeAndWait(field2::selectAll); - robot.waitForIdle(); - robot.delay(200); - BufferedImage sel = robot.createScreenCapture(bounds); - - SwingUtilities.invokeAndWait(() -> { - menuLoc = menu.getLocationOnScreen(); - menuLoc.translate(10, 10); - }); - robot.mouseMove(menuLoc.x, menuLoc.y); - robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException("Test fails: menu hides selection"); - } - - SwingUtilities.invokeAndWait( - MenuSelectionManager.defaultManager()::clearSelectedPath); - SwingUtilities.invokeAndWait(field1::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: focus lost hides single selection"); - } - - SwingUtilities.invokeAndWait(field1::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), nosel)) { - throw new RuntimeException( - "Test fails: focus lost doesn't hide selection upon multi selection"); - } + try { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame(); + field1 = new JTextField("field1 "); + field2 = new JTextField("field2 "); + field1.setEditable(false); + field2.setEditable(false); + frame.getContentPane().setLayout(new FlowLayout()); + frame.getContentPane().add(field1); + frame.getContentPane().add(field2); + JMenuBar menuBar = new JMenuBar(); + menu = new JMenu("menu"); + menu.add(new JMenuItem("item")); + menuBar.add(menu); + frame.setJMenuBar(menuBar); + frame.pack(); + frame.setVisible(true); + }); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(200); + + SwingUtilities.invokeAndWait(field2::requestFocus); + SwingUtilities.invokeAndWait(field2::selectAll); + robot.waitForIdle(); + robot.delay(200); + + SwingUtilities.invokeAndWait(() -> { + menuLoc = menu.getLocationOnScreen(); + menuLoc.translate(10, 10); + }); + robot.mouseMove(menuLoc.x, menuLoc.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException("Test fails: menu hides selection"); + } - SwingUtilities.invokeAndWait(field2::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: focus gain hides selection upon multi selection"); - } + SwingUtilities.invokeAndWait( + MenuSelectionManager.defaultManager()::clearSelectedPath); + SwingUtilities.invokeAndWait(field1::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (field2.getSelectedText() == null || field2.getSelectedText().length() == 0) { + throw new RuntimeException( + "Test fails: focus lost hides single selection"); + } - SwingUtilities.invokeAndWait(field2::requestFocus); - robot.waitForIdle(); - SwingUtilities.invokeAndWait(() ->{ - frame2 = new JFrame(); - Point loc = frame.getLocationOnScreen(); - loc.translate(0, frame.getHeight()); - frame2.setLocation(loc); - anotherWindow = new JTextField("textField3"); - frame2.add(anotherWindow); - frame2.pack(); - frame2.setVisible(true); - }); - robot.waitForIdle(); - SwingUtilities.invokeAndWait(anotherWindow::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), nosel)) { - throw new RuntimeException( - "Test fails: switch window hides selection"); - } + SwingUtilities.invokeAndWait(field1::selectAll); + robot.waitForIdle(); + robot.delay(200); + if (field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: focus lost doesn't hide selection upon multi selection"); + } - SwingUtilities.invokeAndWait(anotherWindow::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: selection ownership is lost selection is shown"); - } + SwingUtilities.invokeAndWait(field2::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: focus gain hides selection upon multi selection"); + } - SwingUtilities.invokeLater(frame2::dispose); - SwingUtilities.invokeLater(frame::dispose); - } + SwingUtilities.invokeAndWait(field2::requestFocus); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + frame2 = new JFrame(); + Point loc = frame.getLocationOnScreen(); + loc.translate(0, frame.getHeight()); + frame2.setLocation(loc); + anotherWindow = new JTextField("textField3"); + frame2.add(anotherWindow); + frame2.pack(); + frame2.setVisible(true); + }); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(anotherWindow::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: switch window hides selection"); + } - static boolean biEqual(BufferedImage i1, BufferedImage i2) { - if (i1.getWidth() == i2.getWidth() && - i1.getHeight() == i2.getHeight()) { - for (int x = 0; x < i1.getWidth(); x++) { - for (int y = 0; y < i1.getHeight(); y++) { - if (i1.getRGB(x, y) != i2.getRGB(x, y)) { - return false; - } - } + SwingUtilities.invokeAndWait(anotherWindow::selectAll); + robot.waitForIdle(); + robot.delay(200); + if (field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: selection ownership is lost selection is shown"); + } + } finally { + if (frame2 != null) { + SwingUtilities.invokeLater(frame2::dispose); } - return true; + SwingUtilities.invokeLater(frame::dispose); } - return false; } } diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/SetCaretRateTest.java openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/SetCaretRateTest.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/text/DefaultCaret/SetCaretRateTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/text/DefaultCaret/SetCaretRateTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.swing.text.Caret; +import javax.swing.text.DefaultCaret; + +/* + * @test + * @bug 8301989 + * @summary Test checks that there is no exception happens + * when setting blink rate on a javax.swing.DefaultCaret that is not + * associated with any text component + * @run main SetCaretRateTest + */ +public class SetCaretRateTest { + public static void main(String[] args) { + Caret caret = new DefaultCaret(); + caret.setBlinkRate(0); + caret.setBlinkRate(100); + caret.setBlinkRate(0); + caret = new DefaultCaret(); + caret.setBlinkRate(100); + caret.setBlinkRate(0); + caret.setBlinkRate(100); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java openjdk-17-17.0.15+6/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java --- openjdk-17-17.0.14+7/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,98 +29,85 @@ * @run main bug4506788 */ -import java.awt.*; -import java.awt.event.*; -import java.lang.reflect.InvocationTargetException; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.text.*; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.awt.event.InputEvent; +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.MutableAttributeSet; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyledEditorKit; public class bug4506788 { - private volatile boolean passed = false; - private JEditorPane jep; + private static volatile boolean passed; + private static volatile Point p; + private static volatile Dimension dim; + private static JEditorPane jep; + private static JFrame f; - public static void main(final String[] args) { - bug4506788 app = new bug4506788(); - app.init(); - app.start(); - } - - public void init() { - try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - createAndShowGUI(); - } - }); - } catch (InterruptedException | InvocationTargetException ex) { - ex.printStackTrace(); - throw new RuntimeException("FAILED: SwingUtilities.invokeAndWait method failed then creating and showing GUI"); - } - } - - public void start() { - Robot robot; + public static void main(final String[] args) throws Exception { try { - robot = new Robot(); + Robot robot = new Robot(); robot.setAutoDelay(100); - } catch (AWTException e) { - throw new RuntimeException("Robot could not be created"); - } - robot.waitForIdle(); - - Point p; - try { - p = getJEPLocOnScreen(); - } catch (Exception e) { - throw new RuntimeException("Could not get JEditorPane location on screen"); - } + SwingUtilities.invokeAndWait(() -> createAndShowGUI()); - robot.mouseMove(p.x, p.y); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - robot.keyPress(KeyEvent.VK_HOME); - robot.keyRelease(KeyEvent.VK_HOME); - robot.keyPress(KeyEvent.VK_RIGHT); - robot.keyRelease(KeyEvent.VK_RIGHT); - robot.keyPress(KeyEvent.VK_X); - robot.keyRelease(KeyEvent.VK_X); - robot.keyPress(KeyEvent.VK_RIGHT); - robot.keyRelease(KeyEvent.VK_RIGHT); + robot.waitForIdle(); + robot.delay(1000); - robot.waitForIdle(); - - if (!passed) { - throw new RuntimeException("Test failed."); - } - } - - private Point getJEPLocOnScreen() throws Exception { + SwingUtilities.invokeAndWait(() -> { + p = jep.getLocationOnScreen(); + dim = jep.getSize(); + }); - final Point[] result = new Point[1]; + robot.mouseMove(p.x + dim.width / 2, p.y + dim.height / 2); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_HOME); + robot.keyRelease(KeyEvent.VK_HOME); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_RIGHT); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_X); + robot.keyRelease(KeyEvent.VK_X); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_RIGHT); + robot.waitForIdle(); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - result[0] = jep.getLocationOnScreen(); + if (!passed) { + throw new RuntimeException("Test failed."); } - }); - - return result[0]; + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } } - private void createAndShowGUI() { + private static void createAndShowGUI() { jep = new JEditorPane(); String text = "abc"; - JFrame f = new JFrame(); + f = new JFrame("bug4506788"); jep.setEditorKit(new StyledEditorKit()); jep.setText(text); jep.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { + System.out.println("getDot " + e.getDot()); passed = (e.getDot() == 3); } }); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/AbstractVectorTest.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/AbstractVectorTest.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/AbstractVectorTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/AbstractVectorTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,11 +35,13 @@ import java.util.stream.Stream; import java.util.stream.Collectors; +import jdk.test.lib.Utils; + import org.testng.Assert; public class AbstractVectorTest { - static final Random RAND = new Random(Integer.getInteger("jdk.incubator.vector.test.random-seed", 1337)); + static final Random RAND = Utils.getRandomInstance(); interface ToBoolF { boolean apply(int i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte128VectorTests */ @@ -4253,7 +4256,7 @@ static void sliceUnaryByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static void unsliceUnaryByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte256VectorTests */ @@ -4253,7 +4256,7 @@ static void sliceUnaryByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static void unsliceUnaryByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte512VectorTests */ @@ -4253,7 +4256,7 @@ static void sliceUnaryByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static void unsliceUnaryByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Byte64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Byte64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte64VectorTests */ @@ -4253,7 +4256,7 @@ static void sliceUnaryByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static void unsliceUnaryByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation ByteMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation ByteMaxVectorTests */ @@ -4258,7 +4261,7 @@ static void sliceUnaryByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4286,7 +4289,7 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4319,7 +4322,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4347,7 +4350,7 @@ static void unsliceUnaryByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4384,8 +4387,8 @@ byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4440,8 +4443,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double128VectorTests */ @@ -3398,7 +3401,7 @@ static void sliceUnaryDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static void unsliceUnaryDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double256VectorTests */ @@ -3398,7 +3401,7 @@ static void sliceUnaryDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static void unsliceUnaryDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double512VectorTests */ @@ -3398,7 +3401,7 @@ static void sliceUnaryDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static void unsliceUnaryDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Double64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Double64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double64VectorTests */ @@ -3398,7 +3401,7 @@ static void sliceUnaryDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static void unsliceUnaryDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation DoubleMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation DoubleMaxVectorTests */ @@ -3404,7 +3407,7 @@ static void sliceUnaryDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3432,7 +3435,7 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3465,7 +3468,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3493,7 +3496,7 @@ static void unsliceUnaryDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3530,8 +3533,8 @@ double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3586,8 +3589,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float128VectorTests */ @@ -3408,7 +3411,7 @@ static void sliceUnaryFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static void unsliceUnaryFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float256VectorTests */ @@ -3408,7 +3411,7 @@ static void sliceUnaryFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static void unsliceUnaryFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float512VectorTests */ @@ -3408,7 +3411,7 @@ static void sliceUnaryFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static void unsliceUnaryFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Float64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Float64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float64VectorTests */ @@ -3408,7 +3411,7 @@ static void sliceUnaryFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static void unsliceUnaryFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation FloatMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation FloatMaxVectorTests */ @@ -3414,7 +3417,7 @@ static void sliceUnaryFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3442,7 +3445,7 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3475,7 +3478,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3503,7 +3506,7 @@ static void unsliceUnaryFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3540,8 +3543,8 @@ float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3596,8 +3599,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int128VectorTests */ @@ -4218,7 +4221,7 @@ static void sliceUnaryInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static void unsliceUnaryInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int256VectorTests */ @@ -4218,7 +4221,7 @@ static void sliceUnaryInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static void unsliceUnaryInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int512VectorTests */ @@ -4218,7 +4221,7 @@ static void sliceUnaryInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static void unsliceUnaryInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Int64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Int64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int64VectorTests */ @@ -4218,7 +4221,7 @@ static void sliceUnaryInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static void unsliceUnaryInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation IntMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation IntMaxVectorTests */ @@ -4223,7 +4226,7 @@ static void sliceUnaryIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4251,7 +4254,7 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4284,7 +4287,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4312,7 +4315,7 @@ static void unsliceUnaryIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4349,8 +4352,8 @@ int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4405,8 +4408,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long128VectorTests */ @@ -4168,7 +4171,7 @@ static void sliceUnaryLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static void unsliceUnaryLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long256VectorTests */ @@ -4168,7 +4171,7 @@ static void sliceUnaryLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static void unsliceUnaryLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long512VectorTests */ @@ -4168,7 +4171,7 @@ static void sliceUnaryLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static void unsliceUnaryLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Long64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Long64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long64VectorTests */ @@ -4168,7 +4171,7 @@ static void sliceUnaryLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static void unsliceUnaryLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation LongMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation LongMaxVectorTests */ @@ -4173,7 +4176,7 @@ static void sliceUnaryLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4201,7 +4204,7 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4234,7 +4237,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4262,7 +4265,7 @@ static void unsliceUnaryLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4299,8 +4302,8 @@ long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4355,8 +4358,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short128VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short128VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short128VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short128VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short128VectorTests */ @@ -4243,7 +4246,7 @@ static void sliceUnaryShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static void unsliceUnaryShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short256VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short256VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short256VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short256VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short256VectorTests */ @@ -4243,7 +4246,7 @@ static void sliceUnaryShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static void unsliceUnaryShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short512VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short512VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short512VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short512VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short512VectorTests */ @@ -4243,7 +4246,7 @@ static void sliceUnaryShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static void unsliceUnaryShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short64VectorLoadStoreTests * diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short64VectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/Short64VectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/Short64VectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short64VectorTests */ @@ -4243,7 +4246,7 @@ static void sliceUnaryShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static void unsliceUnaryShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation ShortMaxVectorLoadStoreTests diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation ShortMaxVectorTests */ @@ -4248,7 +4251,7 @@ static void sliceUnaryShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4276,7 +4279,7 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4309,7 +4312,7 @@ VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4337,7 +4340,7 @@ static void unsliceUnaryShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4374,8 +4377,8 @@ short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4430,8 +4433,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template 2025-04-09 19:45:33.000000000 +0000 @@ -4,7 +4,7 @@ VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template 2025-04-09 19:45:33.000000000 +0000 @@ -1,7 +1,7 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] b = fb.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template 2025-04-09 19:45:33.000000000 +0000 @@ -1,6 +1,6 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template 2025-04-09 19:45:33.000000000 +0000 @@ -3,8 +3,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template 2025-04-09 19:45:33.000000000 +0000 @@ -1,8 +1,8 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] b = fb.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template 2025-04-09 19:45:33.000000000 +0000 @@ -1,6 +1,6 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Unit-header.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Unit-header.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/Unit-header.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/Unit-header.template 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation $vectorteststype$ */ diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template --- openjdk-17-17.0.14+7/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template 2025-04-09 19:45:33.000000000 +0000 @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation #if[MaxBit] * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/internal/jline/AbstractWindowsTerminalTest.java openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/AbstractWindowsTerminalTest.java --- openjdk-17-17.0.14+7/test/jdk/jdk/internal/jline/AbstractWindowsTerminalTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/AbstractWindowsTerminalTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -27,6 +27,7 @@ * @summary Verify the wrapper input stream is used when using Terminal.reader() * @modules jdk.internal.le/jdk.internal.org.jline.terminal * jdk.internal.le/jdk.internal.org.jline.terminal.impl + * jdk.internal.le/jdk.internal.org.jline.terminal.spi * jdk.internal.le/jdk.internal.org.jline.utils */ @@ -39,6 +40,7 @@ import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.Terminal.SignalHandler; import jdk.internal.org.jline.terminal.impl.AbstractWindowsTerminal; +import jdk.internal.org.jline.terminal.spi.SystemStream; public class AbstractWindowsTerminalTest { @@ -56,14 +58,17 @@ return is.read(); } }; - var t = new AbstractWindowsTerminal(out, "test", "vt100", null, false, SignalHandler.SIG_DFL, isWrapper) { + var t = new AbstractWindowsTerminal(null, SystemStream.Output, out, + "test", "vt100", null, false, + SignalHandler.SIG_DFL, "", 0, + "", 0, isWrapper) { @Override - protected int getConsoleMode() { + protected int getConsoleMode(String console) { return -1; } @Override - protected void setConsoleMode(int mode) { + protected void setConsoleMode(String console, int mode) { throw new UnsupportedOperationException("unexpected."); } diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/internal/jline/KeyConversionTest.java openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/KeyConversionTest.java --- openjdk-17-17.0.14+7/test/jdk/jdk/internal/jline/KeyConversionTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/internal/jline/KeyConversionTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -27,6 +27,7 @@ * @summary Verify the conversion from key events to escape sequences works properly. * @modules jdk.internal.le/jdk.internal.org.jline.terminal * jdk.internal.le/jdk.internal.org.jline.terminal.impl + * jdk.internal.le/jdk.internal.org.jline.terminal.spi */ import java.io.IOException; @@ -36,6 +37,7 @@ import jdk.internal.org.jline.terminal.Size; import jdk.internal.org.jline.terminal.Terminal.SignalHandler; import jdk.internal.org.jline.terminal.impl.AbstractWindowsTerminal; +import jdk.internal.org.jline.terminal.spi.SystemStream; public class KeyConversionTest { public static void main(String... args) throws Exception { @@ -58,14 +60,17 @@ void checkKeyConversion(KeyEvent event, String expected) throws IOException { StringBuilder result = new StringBuilder(); - new AbstractWindowsTerminal(new StringWriter(), "", "windows", Charset.forName("UTF-8"), - true, SignalHandler.SIG_DFL, in -> in) { + new AbstractWindowsTerminal(null, SystemStream.Output, + new StringWriter(), "", "windows", + Charset.forName("UTF-8"), true, + SignalHandler.SIG_DFL, "", 0, + "", 0, in -> in) { @Override - protected int getConsoleMode() { + protected int getConsoleMode(String console) { return 0; } @Override - protected void setConsoleMode(int mode) { + protected void setConsoleMode(String console, int mode) { throw new UnsupportedOperationException("Not supported yet."); } @Override diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java openjdk-17-17.0.15+6/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java --- openjdk-17-17.0.14+7/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java 2025-04-09 19:45:33.000000000 +0000 @@ -25,7 +25,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; @@ -34,12 +33,12 @@ /* * @test * @bug 8308184 - * @summary Verify that an application can be launched when the classpath contains large number of - * jars and the java.protocol.handler.pkgs system property is set * @library /test/lib/ * @build jdk.test.lib.util.JarBuilder jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * @run driver LargeClasspathWithPkgPrefix + * @summary Verify that an application can be launched when the classpath contains large number of + * jars and the java.protocol.handler.pkgs system property is set */ public class LargeClasspathWithPkgPrefix { @@ -126,8 +125,7 @@ // java -Djava.protocol.handler.pkgs=foo.bar.some.nonexistent.pkg -cp Foo private static void launchApplication(String classPath) throws Exception { - String java = JDKToolFinder.getJDKTool("java"); - ProcessBuilder pb = new ProcessBuilder(java, + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Djava.protocol.handler.pkgs=foo.bar.some.nonexistent.pkg", "-cp", classPath, "Foo"); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java openjdk-17-17.0.15+6/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java --- openjdk-17-17.0.14+7/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,11 +23,12 @@ /** * @test - * @summary Basic test of VM::getRuntimeArguments + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * jdk.zipfs * @run testng RuntimeArguments + * @summary Basic test of VM::getRuntimeArguments */ import java.io.IOException; @@ -46,7 +47,6 @@ import static org.testng.Assert.*; public class RuntimeArguments { - static final String TEST_CLASSES = System.getProperty("test.classes"); static final List VM_OPTIONS = getInitialOptions(); /* @@ -112,11 +112,9 @@ @Test(dataProvider = "options") public void test(List args, List expected) throws Exception { - // launch a test program - // $ java -classpath RuntimeArguments - Stream options = Stream.concat(args.stream(), - Stream.of("-classpath", TEST_CLASSES, "RuntimeArguments")); - + // launch a test program with classpath set by ProcessTools::createLimitedTestJavaProcessBuilder + // $ java RuntimeArguments + Stream options = Stream.concat(args.stream(), Stream.of("RuntimeArguments")); ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( // The runtime image may be created with jlink --add-options // The initial VM options will be included in the result diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java openjdk-17-17.0.15+6/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java --- openjdk-17-17.0.14+7/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java 2025-04-09 19:45:33.000000000 +0000 @@ -29,6 +29,7 @@ import java.util.List; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import jdk.jfr.Event; @@ -88,69 +89,98 @@ private static void testSetOrderedTrue(Path p) throws Exception { for (boolean reuse : BOOLEAN_STATES) { + System.out.println(); + System.out.println("Testing: testSetOrderedTrue reuse = " + reuse); AtomicReference timestamp = new AtomicReference<>(Instant.MIN); + AtomicBoolean unordered = new AtomicBoolean(false); try (EventStream es = EventStream.openFile(p)) { es.setReuse(reuse); es.setOrdered(true); es.onEvent(e -> { Instant endTime = e.getEndTime(); + printTimestamp(endTime); if (endTime.isBefore(timestamp.get())) { - throw new Error("Events are not ordered! Reuse = " + reuse); + unordered.set(true); } timestamp.set(endTime); }); es.start(); } + if (unordered.get()) { + throw new Exception("Events are not ordered! Reuse = " + reuse); + } } } private static void testSetOrderedFalse(Path p) throws Exception { for (boolean reuse : BOOLEAN_STATES) { + System.out.println(); + System.out.println("Testing: testSetOrderedFalse reuse = " + reuse); AtomicReference timestamp = new AtomicReference<>(Instant.MIN); - AtomicBoolean unoreded = new AtomicBoolean(false); + AtomicBoolean unordered = new AtomicBoolean(false); try (EventStream es = EventStream.openFile(p)) { es.setReuse(reuse); es.setOrdered(false); es.onEvent(e -> { Instant endTime = e.getEndTime(); - System.out.println("testSetOrderedFalse: endTime: " + endTime); + printTimestamp(endTime); if (endTime.isBefore(timestamp.get())) { - unoreded.set(true); - es.close(); + unordered.set(true); } timestamp.set(endTime); }); es.start(); - if (!unoreded.get()) { + if (!unordered.get()) { throw new Exception("Expected at least some events to be out of order! Reuse = " + reuse); } } } } + private static void printTimestamp(Instant timestamp) { + long seconds = timestamp.getEpochSecond(); + long nanos = timestamp.getNano(); + System.out.println(timestamp + " seconds = " + seconds + " nanos = " + nanos); + } + private static Path makeUnorderedRecording() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + while (true) { + CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + try (Recording r = new Recording()) { + r.start(); + List emitters = new ArrayList<>(); + for (int i = 0; i < THREAD_COUNT; i++) { + Emitter e = new Emitter(barrier); + e.start(); + emitters.add(e); + } + // Thread buffers should now have one event each + barrier.await(); + // Add another event to each thread buffer, so + // events are bound to come out of order when they + // are flushed + for (Emitter e : emitters) { + e.join(); + } + r.stop(); + Path p = Utils.createTempFile("recording", ".jfr"); + r.dump(p); + // Order is only guaranteed within a segment. + int segments = countSegments(p); + if (segments < 2) { + return p; + } + System.out.println("File contains more than one segment (" + segments + "). Retrying."); + } + } + } - try (Recording r = new Recording()) { - r.start(); - List emitters = new ArrayList<>(); - for (int i = 0; i < THREAD_COUNT; i++) { - Emitter e = new Emitter(barrier); - e.start(); - emitters.add(e); - } - // Thread buffers should now have one event each - barrier.await(); - // Add another event to each thread buffer, so - // events are bound to come out of order when they - // are flushed - for (Emitter e : emitters) { - e.join(); - } - r.stop(); - Path p = Utils.createTempFile("recording", ".jfr"); - r.dump(p); - return p; + private static int countSegments(Path file) throws Exception { + AtomicInteger segments = new AtomicInteger(); + try (EventStream es = EventStream.openFile(file)) { + es.onFlush(segments::incrementAndGet); + es.start(); + return segments.get(); } } } diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java openjdk-17-17.0.15+6/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java --- openjdk-17-17.0.14+7/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java 2025-04-09 19:45:33.000000000 +0000 @@ -79,7 +79,7 @@ class OldGenMemoryAllocator extends MemoryAllocator { private List list = new ArrayList(); - private int counter = 6000; + private int counter = 5000; @Override public void allocate() { @@ -87,7 +87,7 @@ list.add(new byte[10 * KB]); } else { list = new ArrayList(); - counter = 6000; + counter = 5000; } garbage = list; diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/jfr/startupargs/TestStartDuration.java openjdk-17-17.0.15+6/test/jdk/jdk/jfr/startupargs/TestStartDuration.java --- openjdk-17-17.0.14+7/test/jdk/jdk/jfr/startupargs/TestStartDuration.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/jfr/startupargs/TestStartDuration.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ * @summary Start a recording with duration. Verify recording stops. * @key jfr * @requires vm.hasJFR + * @requires vm.flagless * @library /test/lib /test/jdk * @run main jdk.jfr.startupargs.TestStartDuration */ diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/modules/incubator/DefaultImage.java openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/DefaultImage.java --- openjdk-17-17.0.14+7/test/jdk/jdk/modules/incubator/DefaultImage.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/DefaultImage.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,11 +24,12 @@ /* * @test * @bug 8170859 - * @summary Ensure no incubator modules are resolved by default in the image + * @requires vm.flagless * @library /test/lib * @modules jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils * @run testng DefaultImage + * @summary Ensure no incubator modules are resolved by default in the image */ import java.io.ByteArrayOutputStream; @@ -43,6 +44,7 @@ import java.util.stream.Stream; import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.ProcessTools; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -108,10 +110,8 @@ static ToolResult java(String... opts) throws Throwable { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); - String[] options = Stream.concat(Stream.of(getJava()), Stream.of(opts)) - .toArray(String[]::new); - ProcessBuilder pb = new ProcessBuilder(options); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(opts); int exitValue = executeCommand(pb).outputTo(ps) .errorTo(ps) .getExitValue(); @@ -155,15 +155,6 @@ } } - static String getJava() { - Path image = Paths.get(JAVA_HOME); - boolean isWindows = System.getProperty("os.name").startsWith("Windows"); - Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java"); - if (Files.notExists(java)) - throw new RuntimeException(java + " not found"); - return java.toAbsolutePath().toString(); - } - static boolean isExplodedBuild() { Path modulesPath = Paths.get(JAVA_HOME).resolve("lib").resolve("modules"); return Files.notExists(modulesPath); diff -Nru openjdk-17-17.0.14+7/test/jdk/jdk/modules/incubator/ImageModules.java openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/ImageModules.java --- openjdk-17-17.0.14+7/test/jdk/jdk/modules/incubator/ImageModules.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/jdk/modules/incubator/ImageModules.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,7 @@ /* * @test * @bug 8170859 - * @summary Basic test for incubator modules in jmods and images + * @requires vm.flagless * @library /test/lib * @key intermittent * @modules jdk.compiler jdk.jartool jdk.jlink @@ -32,6 +32,7 @@ * jdk.test.lib.util.FileUtils * jdk.test.lib.compiler.CompilerUtils * @run testng/othervm ImageModules + * @summary Basic test for incubator modules in jmods and images */ import java.io.ByteArrayOutputStream; diff -Nru openjdk-17-17.0.14+7/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java openjdk-17-17.0.15+6/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java --- openjdk-17-17.0.14+7/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,6 @@ import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; -import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; @@ -42,10 +41,8 @@ /** * A generic SwingSet2 demo module - * - * @author Jeff Dinkins */ -public class DemoModule extends JApplet { +public class DemoModule extends JPanel { // The preferred size of the demo private int PREFERRED_WIDTH = 680; @@ -214,10 +211,6 @@ demo.mainImpl(); } - public void init() { - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(getDemoPanel(), BorderLayout.CENTER); - } - void updateDragEnabled(boolean dragEnabled) {} -} \ No newline at end of file +} + diff -Nru openjdk-17-17.0.14+7/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java openjdk-17-17.0.15+6/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java --- openjdk-17-17.0.14+7/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java 2025-04-09 19:45:33.000000000 +0000 @@ -635,20 +635,20 @@ "https://revoked.sfig2.catest.starfieldtech.com"); case "globalsigneccrootcar4" -> - new CATestURLs("https://good.gsr4.demo.pki.goog", - "https://revoked.gsr4.demo.pki.goog"); + new CATestURLs("https://good.gsr4.demosite.pki.goog", + "https://revoked.gsr4.demosite.pki.goog"); case "gtsrootcar1" -> - new CATestURLs("https://good.gtsr1.demo.pki.goog", - "https://revoked.gtsr1.demo.pki.goog"); + new CATestURLs("https://good.gtsr1.demosite.pki.goog", + "https://revoked.gtsr1.demosite.pki.goog"); case "gtsrootcar2" -> - new CATestURLs("https://good.gtsr2.demo.pki.goog", - "https://revoked.gtsr2.demo.pki.goog"); + new CATestURLs("https://good.gtsr2.demosite.pki.goog", + "https://revoked.gtsr2.demosite.pki.goog"); case "gtsrootecccar3" -> - new CATestURLs("https://good.gtsr3.demo.pki.goog", - "https://revoked.gtsr3.demo.pki.goog"); + new CATestURLs("https://good.gtsr3.demosite.pki.goog", + "https://revoked.gtsr3.demosite.pki.goog"); case "gtsrootecccar4" -> - new CATestURLs("https://good.gtsr4.demo.pki.goog", - "https://revoked.gtsr4.demo.pki.goog"); + new CATestURLs("https://good.gtsr4.demosite.pki.goog", + "https://revoked.gtsr4.demosite.pki.goog"); case "microsoftecc2017" -> new CATestURLs("https://acteccroot2017.pki.microsoft.com", diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/awt/image/BytePackedRaster/DitherTest.java openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/DitherTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/awt/image/BytePackedRaster/DitherTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/DitherTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,147 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4184283 + * @summary Checks rendering of dithered byte packed image does not crash. + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.IndexColorModel; +import java.awt.image.MemoryImageSource; +import java.awt.image.WritableRaster; + +public class DitherTest extends Component { + + final static int NOOP = 0; + final static int RED = 1; + final static int GREEN = 2; + final static int BLUE = 3; + final static int ALPHA = 4; + final static int SATURATION = 5; + + final static byte red[] = {(byte)0, (byte)132, (byte)0, (byte)132, (byte)0, (byte)132, + (byte)0, (byte)198, (byte)198, (byte)165, (byte)255, (byte)165, (byte)132, + (byte)255, (byte)0, (byte)255}; + + final static byte green[] = {(byte)0, (byte)0, (byte)130, (byte)130, (byte)0, + (byte)0, (byte)130, (byte)195, (byte)223, (byte)203, (byte)251, (byte)162, + (byte)132, (byte)0, (byte)255, (byte)255}; + + final static byte blue[] = {(byte)0, (byte)0, (byte)0, (byte)0, (byte)132, (byte)132, + (byte)132, (byte)198, (byte)198, (byte)247, (byte)247, (byte)165, (byte)132, + (byte)0, (byte)0, (byte)0}; + + static IndexColorModel cm16 = new IndexColorModel( 4, 16, red, green, blue); + + + public static void main(String args[]) { + + int imageWidth = 256; + int imageHeight = 256; + WritableRaster raster = cm16.createCompatibleWritableRaster(imageWidth, imageHeight); + BufferedImage intermediateImage = new BufferedImage(cm16, raster, false, null); + Image calculatedImage = calculateImage(); + + Graphics2D ig = intermediateImage.createGraphics(); + // Clear background and fill a red rectangle just to prove that we can draw on intermediateImage + ig.setColor(Color.white); + ig.fillRect(0,0,imageWidth,imageHeight); + ig.drawImage(calculatedImage, 0, 0, imageWidth, imageHeight, null); + ig.setColor(Color.red); + ig.fillRect(0,0,5,5); + + BufferedImage destImage = new BufferedImage(imageWidth, imageWidth, BufferedImage.TYPE_INT_RGB); + Graphics2D dg = destImage.createGraphics(); + dg.drawImage(intermediateImage, 0, 0, imageWidth, imageHeight, null); + } + + private static void applymethod(int c[], int method, int step, int total, int vals[]) { + if (method == NOOP) + return; + int val = ((total < 2) + ? vals[0] + : vals[0] + ((vals[1] - vals[0]) * step / (total - 1))); + switch (method) { + case RED: + c[0] = val; + break; + case GREEN: + c[1] = val; + break; + case BLUE: + c[2] = val; + break; + case ALPHA: + c[3] = val; + break; + case SATURATION: + int max = Math.max(Math.max(c[0], c[1]), c[2]); + int min = max * (255 - val) / 255; + if (c[0] == 0) c[0] = min; + if (c[1] == 0) c[1] = min; + if (c[2] == 0) c[2] = min; + break; + } + } + + private static Image calculateImage() { + + int xvals[] = { 0, 255 }; + int yvals[] = { 0, 255 }; + int xmethod = RED; + int ymethod = BLUE; + int width = 256; + int height = 256; + int pixels[] = new int[width * height]; + int c[] = new int[4]; + int index = 0; + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + c[0] = c[1] = c[2] = 0; + c[3] = 255; + if (xmethod < ymethod) { + applymethod(c, xmethod, i, width, xvals); + applymethod(c, ymethod, j, height, yvals); + } else { + applymethod(c, ymethod, j, height, yvals); + applymethod(c, xmethod, i, width, xvals); + } + pixels[index++] = ((c[3] << 24) | + (c[0] << 16) | + (c[1] << 8) | + (c[2] << 0)); + } + } + + DitherTest dt = new DitherTest(); + return dt.createImage(new MemoryImageSource(width, height, ColorModel.getRGBdefault(), pixels, 0, width)); + } +} + diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/awt/image/BytePackedRaster/MultiOp.java openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/MultiOp.java --- openjdk-17-17.0.14+7/test/jdk/sun/awt/image/BytePackedRaster/MultiOp.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/awt/image/BytePackedRaster/MultiOp.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4213160 + * @summary Should generate a black image + */ + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.DataBuffer; +import java.awt.image.DataBufferByte; +import java.awt.image.IndexColorModel; +import java.awt.image.Raster; +import java.awt.image.WritableRaster; +import java.awt.geom.AffineTransform; + +public class MultiOp { + + public static void main(String[] argv) { + + int width = 256; + int height = 256; + + int pixelBits = 2; // 1, 2, 4, or 8 + // 1 and 8 make the code throw ImagingOpException, 2 and 4 + // make the code SEGV on Sol. + + byte[] lut1Arr = new byte[] {0, (byte)255 }; + byte[] lut2Arr = new byte[] {0, (byte)85, (byte)170, (byte)255}; + byte[] lut4Arr = new byte[] {0, (byte)17, (byte)34, (byte)51, + (byte)68, (byte)85,(byte) 102, (byte)119, + (byte)136, (byte)153, (byte)170, (byte)187, + (byte)204, (byte)221, (byte)238, (byte)255}; + byte[] lut8Arr = new byte[256]; + for (int i = 0; i < 256; i++) { + lut8Arr[i] = (byte)i; + } + + // Create the binary image + int bytesPerRow = width * pixelBits / 8; + byte[] imageData = new byte[height * bytesPerRow]; + ColorModel cm = null; + + switch (pixelBits) { + case 1: + cm = new IndexColorModel(pixelBits, lut1Arr.length, + lut1Arr, lut1Arr, lut1Arr); + break; + case 2: + cm = new IndexColorModel(pixelBits, lut2Arr.length, + lut2Arr, lut2Arr, lut2Arr); + break; + case 4: + cm = new IndexColorModel(pixelBits, lut4Arr.length, + lut4Arr, lut4Arr, lut4Arr); + break; + case 8: + cm = new IndexColorModel(pixelBits, lut8Arr.length, + lut8Arr, lut8Arr, lut8Arr); + break; + default: + {new Exception("Invalid # of bit per pixel").printStackTrace();} + } + + DataBuffer db = new DataBufferByte(imageData, imageData.length); + WritableRaster r = Raster.createPackedRaster(db, width, height, + pixelBits, null); + BufferedImage srcImage = new BufferedImage(cm, r, false, null); + + BufferedImage destImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g = destImage.createGraphics(); + AffineTransform af = AffineTransform.getScaleInstance(.5, .5); + // This draw image is the problem + g.drawImage(srcImage, af, null); + int blackPixel = Color.black.getRGB(); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (destImage.getRGB(x, y) != blackPixel) { + throw new RuntimeException("Not black"); + } + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/awt/image/ImageRepresentation/ByteBinaryBitmask.java openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/ByteBinaryBitmask.java --- openjdk-17-17.0.14+7/test/jdk/sun/awt/image/ImageRepresentation/ByteBinaryBitmask.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/ByteBinaryBitmask.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4673490 + * @summary This test verifies that Toolkit images with a 1-bit + * IndexColorModel (known as ByteBinary) and a transparent index are rendered properly. + */ + +import java.awt.Color; +import java.awt.Graphics2D; + +import java.awt.image.BufferedImage; +import java.awt.image.IndexColorModel; + +public class ByteBinaryBitmask { + + public static void main(String argv[]) throws Exception { + + /* Create the image */ + int w = 16, h = 16; + byte[] bw = { (byte)255, (byte)0, }; + IndexColorModel icm = new IndexColorModel(1, 2, bw, bw, bw, 0); + BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY, icm); + Graphics2D g2d = img.createGraphics(); + g2d.setColor(Color.white); + g2d.fillRect(0, 0, w, h); + g2d.setColor(Color.black); + int xoff = 5; + g2d.fillRect(xoff, 5, 1, 10); // 1 pixel wide + + int dw = 200, dh = 50; + BufferedImage dest = new BufferedImage(dw, dh, BufferedImage.TYPE_INT_RGB); + Graphics2D g = dest.createGraphics(); + g.setColor(Color.green); + g.fillRect(0, 0, dw, dh); + int x1 = 10; + int x2 = 50; + int x3 = 90; + int x4 = 130; + g.drawImage(img, x1, 10, null); + g.drawImage(img, x2, 10, null); + g.drawImage(img, x3, 10, null); + g.drawImage(img, x4, 10, null); + + int blackPix = Color.black.getRGB(); + for (int y = 0; y < dh; y++) { + boolean isBlack = false; + for (int x = 0; x < dw; x++) { + int rgb = dest.getRGB(x, y); + if (rgb == blackPix) { + /* Src image has a one pixel wide vertical rect at off "xoff" and + * this is drawn at x1/x2/x3/x4) so the sum of those are the x locations + * to expect black. + */ + if (x != (x1 + xoff) && x != (x2 + xoff) && x != (x3 + xoff) && x!= (x4 + xoff)) { + throw new RuntimeException("wrong x location: " +x); + } + if (isBlack) { + throw new RuntimeException("black after black"); + } + } + isBlack = rgb == blackPix; + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/awt/image/ImageRepresentation/CustomSourceCM.java openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/CustomSourceCM.java --- openjdk-17-17.0.14+7/test/jdk/sun/awt/image/ImageRepresentation/CustomSourceCM.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/awt/image/ImageRepresentation/CustomSourceCM.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 4192756 + * @summary Tests that using a non-default colormodel generates correct images under 16/24 bit mode + */ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics2D; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.DirectColorModel; +import java.awt.image.ComponentColorModel; +import java.awt.image.MemoryImageSource; +import java.util.Arrays; + +/* + * NOTE: This bug only appears under specific conditions. If the background of + * the surface is red, then you are not running under the conditions necessary + * to test for the regression so the results of this test will be inconclusive. + * + * The test should be run under any of the following screen depths/surfaces: + * + * 15-bit, otherwise known as 555 RGB or 32768 (thousands) colors + * 16-bit, otherwise known as 565 RGB or 65536 (thousands) colors + * 24-bit, otherwise known as 16777216 (millions) colors + * + * The test draws 2 rectangles. Both rectangles should be half black (left) + * and half blue (right). If the top rectangle is all black, the test fails. + * If the background is red, the results are inconclusive (see above). +*/ + +public class CustomSourceCM extends Component { + + public static int IMG_W = 80; + public static int IMG_H = 30; + + static void test(int imageType) { + + int w = IMG_W + 20; + int h = IMG_H * 2 + 40; + BufferedImage bi = new BufferedImage(w, h, imageType); + + DirectColorModel dcm; + + /* the next dozen lines or so are intended to help + * ascertain if the destination surface is of the type + * that exhibited the original bug, making the background + * white in those cases. It is not strictly necessary. + * It is only for a manual tester to be able to tell by looking. + * The real test is the check for black and blue later on. + */ + Graphics2D g = bi.createGraphics(); + g.setColor(Color.red); + g.fillRect(0, 0, w, h); + + ColorModel cm = bi.getColorModel(); + if (cm instanceof ComponentColorModel) { + g.setColor(Color.white); + g.fillRect(0, 0, w, h); + } else if (cm instanceof DirectColorModel) { + dcm = (DirectColorModel) cm; + if (dcm.getPixelSize() < 24) { + g.setColor(Color.white); + g.fillRect(0, 0, w, h); + } + } + + // Construct a ColorModel and data for a 16-bit 565 image... + dcm = new DirectColorModel(16, 0x1f, 0x7e0, 0xf800); + + // Create an image which is black on the left, blue on the right. + int[] pixels = new int[IMG_W * IMG_H]; + int blue = dcm.getBlueMask(); + int off = 0; + for (int y = 0; y < IMG_H; y++) { + Arrays.fill(pixels, off, off+IMG_W/2, 0); + Arrays.fill(pixels, off+IMG_W/2, off+IMG_W, blue); + off += IMG_W; + } + MemoryImageSource mis = new MemoryImageSource(IMG_W, IMG_H, dcm, + pixels, 0, IMG_W); + CustomSourceCM comp = new CustomSourceCM(); + Image img = comp.createImage(mis); + + // Draw the image on to the surface. + g.drawImage(img, 10, 10, null); + + // Create a similar effect with 2 fillrects, below the image. + g.setColor(Color.black); + g.fillRect(10, 60, IMG_W/2, IMG_H); + g.setColor(Color.blue); + g.fillRect(10+IMG_W/2, 60, IMG_W/2, IMG_H); + + // Now sample points in the image to confirm they are the expected color. + int bluePix = Color.blue.getRGB(); + int blackPix = Color.black.getRGB(); + int black_topLeft = bi.getRGB(10+IMG_W/4, 10+IMG_H/2); + int blue_topRight = bi.getRGB(10+IMG_W*3/4, 10+IMG_H/2); + int black_bottomLeft = bi.getRGB(10+IMG_W/4, 60+IMG_H/2); + int blue_bottomRight = bi.getRGB(10+IMG_W*3/4, 60+IMG_H/2); + if ((black_topLeft != blackPix) || (black_bottomLeft != blackPix) || + (blue_topRight != bluePix) || (blue_bottomRight != bluePix)) { + + String fileName = "failed " + imageType + ".png"; + try { + javax.imageio.ImageIO.write(bi, "png", new java.io.File(fileName)); + } catch (Exception e) { }; + throw new RuntimeException("unexpected colors"); + } + } + + public static void main(String argv[]) { + test(BufferedImage.TYPE_USHORT_555_RGB); + test(BufferedImage.TYPE_USHORT_565_RGB); + test(BufferedImage.TYPE_3BYTE_BGR); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/GdiRendering/GdiBlitOffscreenTest.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiBlitOffscreenTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/GdiRendering/GdiBlitOffscreenTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiBlitOffscreenTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4725045 + * @key headful + * @summary verifies that there are no artifacts due to using + * GDI for copies to the back buffer (GDI should only be used + * for copies to the screen) + * @run main GdiBlitOffscreenTest +*/ + +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.Point; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +public class GdiBlitOffscreenTest { + + static volatile JFrame f; + static final int imageW = 100, imageH = 100, FW = 500, FH = 500; + static volatile BufferedImage greenImage; + + public static void main(String[] args) throws Exception { + + // First, create an image. + greenImage = new BufferedImage(imageW, imageH, + BufferedImage.TYPE_INT_RGB); + Graphics redG = greenImage.getGraphics(); + redG.setColor(Color.green); + redG.fillRect(0, 0, imageW, imageH); + redG.setColor(Color.white); + redG.drawString("Passed!", 30, 80); + + Robot robot = new Robot(); + try { + SwingUtilities.invokeAndWait(GdiBlitOffscreenTest::createUI); + robot.delay(1000); + robot.waitForIdle(); + Point p = f.getLocationOnScreen(); + Color c = robot.getPixelColor(p.x+FW/2, p.y+FH/2); + if (!c.equals(Color.green)) { + throw new RuntimeException("Color is " + c); + } + } finally { + if (f != null) { + SwingUtilities.invokeAndWait(f::dispose); + } + } + } + + private static void createUI() { + f = new JFrame("GdiBlitOffscreenTest"); + f.setSize(FW, FH); + f.setVisible(true); + + // copy the image to the window. + Graphics g = f.getGraphics(); + g.drawImage(greenImage, 0, 0, null); + + // Now, get on with the rest of the test + JComponent app = new GdiBlitOffscreenTestComponent(imageW, imageH, greenImage); + app.setSize(500, 500); + f.getContentPane().add(app); + f.validate(); + f.repaint(); + } +} + +class GdiBlitOffscreenTestComponent extends JComponent { + + int imageW, imageH; + Image theImage; + + public GdiBlitOffscreenTestComponent(int imageW, int imageH, + Image theImage) + { + this.theImage = theImage; + this.imageW = imageW; + this.imageH = imageH; + } + + public void paintComponent(Graphics g) { + int imageX = (getWidth() - imageW) / 2; + int imageY = (getHeight() - imageH) / 2; + g.setColor(Color.blue); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(Color.red); + g.fillRect(imageX, imageY, imageW, imageH); + g.setColor(Color.white); + g.drawString("Failed!", imageX + 30, imageY + 80); + g.drawImage(theImage, imageX, imageY, null); + } + +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/GdiRendering/GdiLockTest.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiLockTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/GdiRendering/GdiLockTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/GdiRendering/GdiLockTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4693644 + * @summary verifies that there are no artifacts due to copying with GDI + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual GdiLockTest +*/ + +import java.awt.Color; +import java.awt.Component; +import java.awt.Frame; +import java.awt.Graphics; + +public class GdiLockTest { + + static final String INSTRUCTIONS = """ + A window will open up next to these instructions. + The text you see in that window should blink on and off. + If it never disappears, then the test has failed. + """; + + public static void main(String[] argv) throws Exception { + PassFailJFrame.builder() + .title("GdiLockTest") + .instructions(INSTRUCTIONS) + .testTimeOut(5) + .rows(5) + .columns(45) + .testUI(GdiLockTest::createUI) + .build() + .awaitAndCheck(); + } + + private static Frame createUI() { + Frame f = new Frame("GdiLockTest"); + f.setSize(300, 300); + GdiLockTestComponent test = new GdiLockTestComponent(); + Thread t = new Thread(test); + f.add(test); + t.start(); + return f; + } +} + +class GdiLockTestComponent extends Component implements Runnable { + + boolean textVisible = true; + + public void paint(Graphics g) { + g.setColor(Color.white); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(Color.black); + if (!textVisible) { + g.setClip(200, 200, 300, 300); + } + g.drawString("This text should be blinking", 10, 30); + if (!textVisible) { + g.setClip(0, 0, getWidth(), getHeight()); + } + } + + public void run() { + while (true) { + repaint(); + textVisible = !textVisible; + try { + Thread.sleep(500); + } catch (Exception e) {} + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/DrawRoundRect0Bug.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/DrawRoundRect0Bug.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/DrawRoundRect0Bug.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/DrawRoundRect0Bug.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4515761 + * @summary verify that drawRoundRect produces correct output for 0 w/h + */ + +import java.awt.Color; +import static java.awt.Color.*; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +public class DrawRoundRect0Bug { + + public static void main(String argv[]) { + BufferedImage img = new BufferedImage(250, 250, BufferedImage.TYPE_INT_RGB); + Graphics2D g = img.createGraphics(); + + g.setColor(white); + g.fillRect(0, 0, img.getWidth(), img.getHeight()); + + g.setColor(green); + g.drawLine(150, 90, 150, 110); + if (img.getRGB(150, 100) != green.getRGB()) { + throw new RuntimeException("Vertical line not green"); + } + + g.setColor(blue); + g.drawRoundRect(160, 90, 0, 20, 4, 4); + if (img.getRGB(160, 100) != blue.getRGB()) { + throw new RuntimeException("Vertical (ie zero width) round rect not blue"); + } + + g.setColor(green); + g.drawLine(150, 140, 170, 140); + if (img.getRGB(160, 140) != green.getRGB()) { + throw new RuntimeException("Horizontal line not green"); + } + + g.setColor(blue); + g.drawRoundRect(150, 150, 20, 0, 4, 4); + if (img.getRGB(160, 150) != blue.getRGB()) { + throw new RuntimeException("Horizontal (ie zero height) round rect not blue"); + } + } + +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/RevalidateBug.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/RevalidateBug.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/RevalidateBug.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/RevalidateBug.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4652373 + * @summary verify that SunGraphics2D survives surface revalidation + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual RevalidateBug + * @requires (os.family == "windows") + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Rectangle; +import javax.swing.JComponent; +import javax.swing.JFrame; + +public class RevalidateBug { + + private static final String INSTRUCTIONS = """ + This bug only reproduces on Windows systems with a task manager that can lock the computer. + + This test draws a grayscale gradient in a window. + + After the gradient becomes visible above, use ctrl-alt-del to bring up + the task manager and lock the computer. + Then unlock the computer and the gradient should be repainted to pass. + + If the gradient does not appear after unlocking (or if the test gets + an error on its own after unlocking the computer) then it fails. + """; + + public static void main(String[] argv) throws Exception { + PassFailJFrame.builder() + .title("RevalidateBug") + .instructions(INSTRUCTIONS) + .testTimeOut(5) + .rows(12) + .columns(50) + .testUI(RevalidateBug::createUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createUI() { + + JComponent comp = new JComponent() { + + protected void paintComponent(Graphics g) { + super.paintComponent(g); + System.out.println("paintComponent"); + Graphics2D g2d = (Graphics2D) g; + + Insets insets = getInsets(); + Rectangle rect = + new Rectangle(insets.left, insets.top, + getWidth() - insets.right - insets.left, + getHeight() - insets.top - insets.bottom); + g2d.setPaint(new GradientPaint(rect.x, rect.y, Color.white, + rect.x + rect.width, rect.y, Color.black)); + + System.out.println(rect + " w:" + getWidth() + " h:"+getHeight()); + + g2d.fillRect(0, 0, getWidth(), getHeight()); + } + + public Dimension getPreferredSize() { + return new Dimension(500, 500); + } + }; + + JFrame f = new JFrame("RevalidateTest"); + f.add(comp); + f.pack(); + return f; + } + +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/ScaledPolyTest.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/ScaledPolyTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/SunGraphics2D/ScaledPolyTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/SunGraphics2D/ScaledPolyTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4516037 + * @summary verify that scaled Polygons honor the transform + */ + +import java.awt.Color; +import static java.awt.Color.*; +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.image.BufferedImage; + +public class ScaledPolyTest { + + public static void main(String[] args) { + + Polygon poly = new Polygon(); + poly.addPoint(20, 10); + poly.addPoint(30, 30); + poly.addPoint(10, 30); + poly.addPoint(20, 10); + + int height = 300; + int width = 300; + BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics2D g2d = bi.createGraphics(); + g2d.setColor(Color.white); + g2d.fillRect(0, 0, bi.getWidth(), bi.getHeight()); + + g2d.translate(10, 10); + g2d.scale(2, 2); + g2d.setColor(Color.yellow); + g2d.fill(poly); + g2d.setColor(Color.blue); + g2d.draw(poly); + + /* + * Examine each row of the image. + * If the stroked polygon is correctly aligned on the filled polygon, + * if there is anything except white on the line, + * the transition will always be white+->blue+->yellow*->blue*->white+ + */ + int bluePix = blue.getRGB(); + int yellowPix = yellow.getRGB(); + int whitePix = white.getRGB(); + for (int y = 0; y < height; y++ ) { + int x = 0; + int pix = whitePix; + + while (pix == whitePix && x < width) pix = bi.getRGB(x++, y); + if (pix == whitePix && x == width) continue; // all white row. + + if (pix != bluePix) throw new RuntimeException("Expected blue"); + + while (pix == bluePix) pix = bi.getRGB(x++, y); + + if (pix == yellowPix) { + while (pix == yellowPix) pix = bi.getRGB(x++, y); + if (pix != bluePix) throw new RuntimeException("Expected blue"); + while (pix == bluePix) pix = bi.getRGB(x++, y); + if (pix != whitePix) throw new RuntimeException("Expected white"); + } + + while (pix == whitePix && x < width) pix = bi.getRGB(x++, y); + if (pix == whitePix && x == width) { + continue; + } else { + throw new RuntimeException("Expected white to finish the row"); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/java2d/pipe/DrawImageBgTest.java openjdk-17-17.0.15+6/test/jdk/sun/java2d/pipe/DrawImageBgTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/java2d/pipe/DrawImageBgTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/java2d/pipe/DrawImageBgTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4532352 + * @summary This test verifies that the specified background color is rendered + * in the special case of: + * Graphics.drawImage(Image img, int dx1, int dy1, int dx2, int dy2, + * int sx1, int sy1, int sx2, int sy2, + * Color bgColor, ImageObserver observer) + * where no scaling takes place because the source and destination + * bounds have the same width and height. + */ + +import java.io.File; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import javax.imageio.ImageIO; + +public class DrawImageBgTest { + + public static void main(String argv[]) throws Exception { + + int dx, dy, dw, dh; + int sx, sy, sw, sh; + + int iw = 250, ih = 250; + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + String prefix = dir+sep; + BufferedImage img = ImageIO.read(new File(prefix + "duke.gif")); + BufferedImage dest = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB); + + Graphics2D g = dest.createGraphics(); + g.setColor(Color.blue); + g.fillRect(0, 0, iw, ih); + + // source and destination dimensions are different, results in scaling + dx = 10; + dy = 10; + dw = 100; + dh = 200; + sx = 10; + sy = 10; + sw = 50; + sh = 100; + g.drawImage(img, + dx, dy, dx + dw, dy + dh, + sx, sy, sx + sw, sy + sh, + Color.yellow, null); + + int pix1 = dest.getRGB(dx + 1, dy + 1); + + // source and destination dimensions are the same, no scaling + dx = 120; + dy = 10; + sx = 10; + sy = 10; + sw = dw = 50; + sh = dh = 100; + g.drawImage(img, + dx, dy, dx + dw, dy + dh, + sx, sy, sx + sw, sy + sh, + Color.yellow, null); + + int pix2 = dest.getRGB(dx + 1, dy + 1); + int yellow = Color.yellow.getRGB(); + + if (pix1 != yellow || pix2 != yellow) { + ImageIO.write(dest, "gif", new File("op.gif")); + throw new RuntimeException("pix1=" + Integer.toHexString(pix1) + + " pix2=" + Integer.toHexString(pix2)); + } + } +} Binary files /srv/release.debian.org/tmp/ZDZE4Qh09I/openjdk-17-17.0.14+7/test/jdk/sun/java2d/pipe/duke.gif and /srv/release.debian.org/tmp/cyUoXnCLTp/openjdk-17-17.0.15+6/test/jdk/sun/java2d/pipe/duke.gif differ diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/pkcs11/PKCS11Test.java openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/PKCS11Test.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/pkcs11/PKCS11Test.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/PKCS11Test.java 2025-04-09 19:45:33.000000000 +0000 @@ -53,9 +53,11 @@ import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.test.lib.Platform; +import jdk.test.lib.Utils; import jdk.test.lib.artifacts.Artifact; import jdk.test.lib.artifacts.ArtifactResolver; import jdk.test.lib.artifacts.ArtifactResolverException; @@ -481,14 +483,13 @@ return null; } - String base = getBase(); - + String nssConfigDir = copyNssFiles(); String libfile = libdir + System.mapLibraryName(nss_library); String customDBdir = System.getProperty("CUSTOM_DB_DIR"); String dbdir = (customDBdir != null) ? customDBdir : - base + SEP + "nss" + SEP + "db"; + nssConfigDir + SEP + "db"; // NSS always wants forward slashes for the config path dbdir = dbdir.replace('\\', '/'); @@ -498,7 +499,7 @@ System.setProperty("pkcs11test.nss.db", dbdir); return (customConfig != null) ? customConfig : - base + SEP + "nss" + SEP + customConfigName; + nssConfigDir + SEP + customConfigName; } // Generate a vector of supported elliptic curves of a given provider @@ -725,6 +726,31 @@ } } + //Copy the nss config files to the current directory for tests. Returns the destination path + private static String copyNssFiles() throws Exception { + String nss = "nss"; + String db = "db"; + Path nssDirSource = Path.of(getBase()).resolve(nss); + Path nssDirDestination = Path.of(".").resolve(nss); + + // copy files from nss directory + copyFiles(nssDirSource, nssDirDestination); + // copy files from nss/db directory + copyFiles(nssDirSource.resolve(db), nssDirDestination.resolve(db)); + return nssDirDestination.toString(); + } + + private static void copyFiles(Path dirSource, Path dirDestination) throws IOException { + List sourceFiles = Arrays + .stream(dirSource.toFile().listFiles()) + .filter(File::isFile) + .map(File::toPath) + .collect(Collectors.toList()); + List destFiles = Utils.copyFiles(sourceFiles, dirDestination, + StandardCopyOption.REPLACE_EXISTING); + destFiles.forEach((Path file) -> file.toFile().setWritable(true)); + } + public abstract void main(Provider p) throws Exception; protected boolean skipTest(Provider p) { diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh --- openjdk-17-17.0.14+7/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ # @library /test/lib/ # @build jdk.test.lib.util.ForceGC # jdk.test.lib.Platform +# jdk.test.lib.Utils # @run shell MultipleLogins.sh # set a few environment variables so that the shell-script can run stand-alone diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/KeyStore/DKSTest.java openjdk-17-17.0.15+6/test/jdk/sun/security/provider/KeyStore/DKSTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/KeyStore/DKSTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/KeyStore/DKSTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -80,7 +80,7 @@ public static void main(String[] args) throws Exception { if (args.length == 0) { // Environment variable and system properties referred in domains.cfg used by this Test. - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(List.of( "-Dtest.src=" + TEST_SRC , "-Duser.dir=" + USER_DIR, "DKSTest", "run")); pb.environment().putAll(System.getenv()); pb.environment().put("KEYSTORE_PWD", "test12"); diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,16 +26,15 @@ * @bug 4215035 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirs + * @run main ExtDirs */ /* - * Run this test manually with: - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.policy==./ExtDirs.policy \ - * -Djava.security.debug=parser \ - * ExtDirs + * @test + * @bug 4215035 + * @summary standard extensions path is hard-coded in default + * system policy file + * @run main/othervm/policy=ExtDirs.policy ExtDirs */ public class ExtDirs { diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy 2025-04-09 19:45:33.000000000 +0000 @@ -1,4 +1,4 @@ -grant codebase "${java.ext.dirs}" { +grant codebase "file:${test.classes}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy 2025-04-09 19:45:33.000000000 +0000 @@ -1,4 +1,4 @@ -grant codebase "file:${{java.ext.dirs}}/*" { +grant codebase "file:${test.classes}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy 2025-04-09 19:45:33.000000000 +0000 @@ -1,4 +1,4 @@ -grant codebase "file:${{java.ext.dirs}}" { +grant codebase "file:${test.classes}/*" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy 2025-04-09 19:45:33.000000000 +0000 @@ -1,4 +1,4 @@ -grant codebase "${{java.ext.dirs}}" { +grant codebase "file:${test.classes}/-" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,30 +26,17 @@ * @bug 4993819 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirsChange + * @run main/othervm/policy=ExtDirsChange.policy ExtDirsChange */ -/* - * Run this test manually with: - * javac ExtDirChange - * rm ExtDirsA*.class ExtDirsB*.class - * java -Djava.security.manager \ - * -Dtest.src=. \ - * -Djava.security.policy=ExtDirsChange.policy \ - * -Djava.security.debug=parser \ - * -cp ExtDirsA/a.jar:ExtDirsB/b.jar:. \ - * ExtDirsChange - */ - -import java.io.File; import java.security.*; public class ExtDirsChange { public static void main(String args[]) throws Exception { - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); - // Uses default security policy and java.ext.dirs + // Uses default security policy and java.policy.dirs try { ExtDirsA a = new ExtDirsA(); a.go(); @@ -58,14 +45,14 @@ System.out.println("Setup OK"); } - // Change java.ext.dirs and refresh policy + // Change java.policy.dirs and refresh policy AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - // Change java.ext.dirs - System.setProperty("java.ext.dirs", - "ExtDirsA" + File.pathSeparator + "ExtDirsB"); - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + // Change java.policy.dirs + System.setProperty("java.policy.dirs", + System.getProperty("test.classes")); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); return null; } }); @@ -79,7 +66,7 @@ System.out.println("Setup before refresh OK"); } - // Refresh policy using updated java.ext.dirs + // Refresh policy using updated java.policy.dirs AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Policy.getPolicy().refresh(); @@ -99,13 +86,13 @@ } // Test with blank java.ext.dir - // Change java.ext.dirs and refresh policy + // Change java.policy.dirs and refresh policy AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - // Change java.ext.dirs - System.setProperty("java.ext.dirs", " "); - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + // Change java.policy.dirs + System.setProperty("java.policy.dirs", " "); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); Policy.getPolicy().refresh(); return null; } diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy 2025-04-09 19:45:33.000000000 +0000 @@ -1,8 +1,16 @@ -grant codebase "file:${test.src}/*" { - permission java.security.AllPermission; +grant { + permission java.util.PropertyPermission "test.classes", "read"; + permission java.security.SecurityPermission "getPolicy"; + permission java.security.SecurityPermission "setPolicy"; }; -grant codebase "${java.ext.dirs}" { +grant codebase "file:${test.classes}/*" { + permission java.util.PropertyPermission "java.policy.dirs", "read, write"; + permission java.util.PropertyPermission "user.name", "write"; + permission java.util.PropertyPermission "user.home", "write"; +}; + +grant codebase "file:${java.policy.dirs}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,34 @@ * @bug 4993819 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirsDefaultPolicy + * @run main ExtDirsDefaultPolicy */ /* - * Run this test manually with: - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.debug=parser \ - * ExtDirsDefaultPolicy - * - * To test other varients of the ${{java.ext.dirs}} protocol, remove - * the grant statement for java.ext.dirs in $JAVA_HOME/lib/security/java.policy - * and then run against the 3 different policy files. - * - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.debug=parser \ - * -Djava.security.policy=ExtDirs{1,2,3}.policy \ - * ExtDirsDefaultPolicy + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file + * + * @run main/othervm/policy=ExtDirs1.policy ExtDirsDefaultPolicy + */ + +/* + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file + * + * @run main/othervm/policy=ExtDirs2.policy ExtDirsDefaultPolicy + */ + +/* + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file + * + * @run main/othervm/policy=ExtDirs3.policy ExtDirsDefaultPolicy */ public class ExtDirsDefaultPolicy { diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java openjdk-17-17.0.15+6/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ * @bug 6998583 8141039 * @summary NativeSeedGenerator is making 8192 byte read requests from * entropy pool on each init. - * @run main/othervm -Djava.security.egd=file:/dev/random SeedGeneratorChoice + * @run main/othervm -Djava.security.egd=file:/dev/urandom SeedGeneratorChoice * @run main/othervm -Djava.security.egd=file:filename SeedGeneratorChoice */ diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Camerfirma.java openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Camerfirma.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Camerfirma.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Camerfirma.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.File; +import java.security.Security; +import java.time.*; +import java.util.*; +import javax.net.ssl.*; + +/** + * @test + * @bug 8346587 + * @summary Check that TLS Server certificates chaining back to distrusted + * Camerfirma roots are invalid + * @library /test/lib + * @modules java.base/sun.security.validator + * @run main/othervm Camerfirma after policyOn invalid + * @run main/othervm Camerfirma after policyOff valid + * @run main/othervm Camerfirma before policyOn valid + * @run main/othervm Camerfirma before policyOff valid + */ + +public class Camerfirma { + + private static final String certPath = "chains" + File.separator + "camerfirma"; + + // Each of the roots have a test certificate chain stored in a file + // named "-chain.pem". + private static String[] rootsToTest = new String[] { + "camerfirmachamberscommerceca", "camerfirmachambersca", + "camerfirmachambersignca"}; + + // Date after the restrictions take effect + private static final ZonedDateTime DISTRUST_DATE = + LocalDate.of(2025, 04, 16).atStartOfDay(ZoneOffset.UTC); + + public static void main(String[] args) throws Exception { + + // All of the test certificates are signed with SHA-1 so we need + // to remove the constraint that disallows SHA-1 certificates. + String prop = Security.getProperty("jdk.certpath.disabledAlgorithms"); + String newProp = prop.replace(", SHA1 jdkCA & usage TLSServer", ""); + Security.setProperty("jdk.certpath.disabledAlgorithms", newProp); + + Distrust distrust = new Distrust(args); + + X509TrustManager[] tms = new X509TrustManager[]{ + distrust.getTMF("PKIX", null), + distrust.getTMF("SunX509", null) + }; + + Date notBefore = distrust.getNotBefore(DISTRUST_DATE); + distrust.testCertificateChain(certPath, notBefore, tms, rootsToTest); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/Distrust.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -198,7 +198,13 @@ public boolean[] getSubjectUniqueID() { return cert.getSubjectUniqueID(); } - public boolean[] getKeyUsage() { return cert.getKeyUsage(); } + public boolean[] getKeyUsage() { + // Turn on the Digital Signature bit. Some certs that we want + // to use as test certs don't have this bit turned on. + boolean[] withDigitalSignature = cert.getKeyUsage(); + withDigitalSignature[0] = true; + return withDigitalSignature; + } public int getBasicConstraints() { return cert.getBasicConstraints(); } public byte[] getEncoded() throws CertificateEncodingException { return cert.getEncoded(); diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersca-chain.pem openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersca-chain.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersca-chain.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersca-chain.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,64 @@ +Owner: CN=Camerfirma Corporate Server II - 2015, + L=Madrid (see current address at https://www.camerfirma.com/address), + SERIALNUMBER=A82743287, + O=AC Camerfirma S.A., OU=AC CAMERFIRMA, C=ES +Issuer: CN=Chambers of Commerce Root - 2008, + O=AC Camerfirma S.A., SERIALNUMBER=A82743287, + L=Madrid (see current address at www.camerfirma.com/address), C=EU +Serial number: 621ff31c489ba136 +Valid from: Thu Jan 15 01:21:16 PST 2015 until: Tue Dec 15 01:21:16 PST 2037 +Certificate fingerprints: + SHA1: FE:72:7A:78:EA:0C:03:35:CD:DA:9C:2E:D7:5F:D4:D4:6F:35:C2:EF + SHA256: 66:EA:E2:70:9B:54:CD:D1:69:31:77:B1:33:2F:F0:36:CD:D0:F7:23:DB:30:39:ED:31:15:55:A6:CB:F5:FF:3E +Signature algorithm name: SHA256withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 + +-----BEGIN CERTIFICATE----- +MIIIkzCCBnugAwIBAgIIYh/zHEiboTYwDQYJKoZIhvcNAQELBQAwga4xCzAJBgNV +BAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQg +d3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcx +GzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMg +b2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwHhcNMTUwMTE1MDkyMTE2WhcNMzcxMjE1 +MDkyMTE2WjCB0zELMAkGA1UEBhMCRVMxFjAUBgNVBAsMDUFDIENBTUVSRklSTUEx +GzAZBgNVBAoMEkFDIENhbWVyZmlybWEgUy5BLjESMBAGA1UEBRMJQTgyNzQzMjg3 +MUswSQYDVQQHDEJNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgaHR0cHM6 +Ly93d3cuY2FtZXJmaXJtYS5jb20vYWRkcmVzcykxLjAsBgNVBAMMJUNhbWVyZmly +bWEgQ29ycG9yYXRlIFNlcnZlciBJSSAtIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQC3ndKNpFufVq9v+15dRoT9oVkgwEfDdsPw0Ly0R+eM5MOk +35zEil/+hqEMbQmcvosAh6I8iAskkXasqh+SMbMIjvXbDyNILeGzsoP0uz3btHM7 +oN3yHXDhhd1NGNocP54Wehe9+RE3WP0yEEo+D2YmMwUHuv4KiXtveiPksv+Xkkz5 +auqppPMaYlD6y49AEsGY2zOEUI8PO4+tOxUKhvsiMuW817vH3VdmMwOjRe0SdYAi +YLQIiyqJGNdEo3u+fw8UXxaJSRXhmF+jUn5DvdzWWNAxxwAKy95EPlpLQsx/7t2W +2ntoELPHGJk4V+/yA0d2olLEqBADkRtP2HiC0wly+zp7OGmjtfjbqLrVjmo/mLP3 +zpmYbpUtubrHiY0rlW6wo5FZLcTUvcAxFjxLWVIELPjnTebOuHvoJTb97rhA1Oqq +woq5FWJHFI9idzXzFLO0LX/4ugI9LZWxmvWW0O4CePtnhp0aNE/GgAw6lMx7bjZe +DXxxQnUDEE/mAqOHRUCnvRUSKVbuBBE0oz5fz3nUwcWVVgrm/jkgqTX4EqnZe+yB +mKV6hFEYV+1oVh7kzNN4Hg7nzGuByS7cCuBEwULFhfUja1Bu9EqgndJ3CV0XCWIA +XVhJnPNPi6y4W11jLJ7XSGSz3sCh21g0Gpgi2pXHGDB65Jc/QJHZ5ZaHCrzFnwID +AQABo4ICjDCCAogwEgYDVR0TAQH/BAgwBgEB/wIBAjAdBgNVHQ4EFgQUY+nw8FYA +aGWwIWwOXNcZCJ0INGUwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKe +FxmhgbSkgbEwga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBj +dXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIw +EAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEp +MCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiCCQCj2kJ+ +pLGu2jB6BggrBgEFBQcBAQRuMGwwQgYIKwYBBQUHMAKGNmh0dHA6Ly93d3cuY2Ft +ZXJmaXJtYS5jb20vY2VydHMvcm9vdF9jaGFtYmVycy0yMDA4LmNydDAmBggrBgEF +BQcwAYYaaHR0cDovL29jc3AuY2FtZXJmaXJtYS5jb20wDgYDVR0PAQH/BAQDAgEG +MCcGA1UdJQQgMB4GCCsGAQUFBwMEBggrBgEFBQcDAgYIKwYBBQUHAwEwPgYDVR0g +BDcwNTAzBgRVHSAAMCswKQYIKwYBBQUHAgEWHWh0dHBzOi8vcG9saWN5LmNhbWVy +ZmlybWEuY29tMHgGA1UdHwRxMG8wNaAzoDGGL2h0dHA6Ly9jcmwuY2FtZXJmaXJt +YS5jb20vY2hhbWJlcnNyb290LTIwMDguY3JsMDagNKAyhjBodHRwOi8vY3JsMS5j +YW1lcmZpcm1hLmNvbS9jaGFtYmVyc3Jvb3QtMjAwOC5jcmwwDQYJKoZIhvcNAQEL +BQADggIBAKhqaZwalwf89f4wPqfcE/lrsHdx8+q9RG46ouBXhTJMqXjwstXOZSL4 +3Dqs3GaVuMPIM9OG7CK0I93mAt+FWtr49ACFTyPBxPg/knrZ4RHyEto+/6w0WZ9H +owNw0aUg3ZAkhIvMRPVou8PrVukqj2lGKIh3hRdrbHwYwwmKKNlWBoC9gWk3mTYU +zfNt/KTzQCCl5+s6YDa+XInMLWaGd/pE/e++a22vY24cv7kN3NAFMjAMELPwh9ic +zLoPX8B52r+GgwpKY0c0hZdVTii6psLQ+BenyMlh+6lHRBOlTCSRtNi16o7H8fRq +CY2wyQi7N+EmdY1DhvECCi1nLbOnIx1bSAW0cVwPVrjQ/vsAxPNc3SGe/Xnanm3a +zAgFspzeuAhxxG0VKOvtPBnPQNsQ0cK664+IrWRsfa6aYhEfKvfsn5o4HpBWDobf +zrtNbqjjOuiM6JkT+DxXo5UK7t2q75KCJiimTtAuPcZ5wErZISLvZ34BodIHL2xK +b3Vww7K2FE1QaNsuQkGbUk++B9/+vV3H57vzskObdFWeWKSCpxIil4vZwIIH17zn +WU+O2WIY1F0aO9zp3E7qwfmYT4MJ38NF9R7FSlxRlgVc1uUHu/iyUU4N1O6F3VdX +P2Y+tgLFZLYV4kApfXk5l9h94dgKyfVcIpvS6yVpLfONPnlCNOxy +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachamberscommerceca-chain.pem openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachamberscommerceca-chain.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachamberscommerceca-chain.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachamberscommerceca-chain.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,48 @@ +Owner: CN=AC Camerfirma Certificados Camerales, + O=AC Camerfirma SA, SERIALNUMBER=A82743287, + L=Madrid (see current address at www.camerfirma.com/address), + EMAILADDRESS=ac_camerfirma_cc@camerfirma.com, C=ES +Issuer: CN=Chambers of Commerce Root, OU=http://www.chambersign.org, + O=AC Camerfirma SA CIF A82743287, C=EU +Serial number: 5 +Valid from: Mon Feb 09 07:42:47 PST 2004 until: Thu Feb 09 07:42:47 PST 2034 +Certificate fingerprints: + SHA1: 9F:36:B4:BE:9D:AF:1C:91:01:B2:D7:61:58:FB:95:CB:53:82:01:10 + SHA256: C7:D8:43:81:E1:1F:7C:57:46:77:1A:F5:B0:50:DC:51:FC:6F:DA:D6:F6:F3:5B:B5:3A:3D:E9:13:82:2E:A0:9E +Signature algorithm name: SHA1withRSA (weak) +Subject Public Key Algorithm: 2048-bit RSA key +Version: 3 + +-----BEGIN CERTIFICATE----- +MIIFwDCCBKigAwIBAgIBBTANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEn +MCUGA1UEChMeQUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQL +ExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMg +b2YgQ29tbWVyY2UgUm9vdDAeFw0wNDAyMDkxNTQyNDdaFw0zNDAyMDkxNTQyNDda +MIHgMQswCQYDVQQGEwJFUzEuMCwGCSqGSIb3DQEJARYfYWNfY2FtZXJmaXJtYV9j +Y0BjYW1lcmZpcm1hLmNvbTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBh +ZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ +QTgyNzQzMjg3MRkwFwYDVQQKExBBQyBDYW1lcmZpcm1hIFNBMS0wKwYDVQQDEyRB +QyBDYW1lcmZpcm1hIENlcnRpZmljYWRvcyBDYW1lcmFsZXMwggEgMA0GCSqGSIb3 +DQEBAQUAA4IBDQAwggEIAoIBAQCjxnvvj01f36lgGhihRYVf1fAPEXsTJKrY4aLQ +cEUSh5szZE7VTtGiyMTMc2uCmnaXafjYHK8Lgmy6T9xxGEZ5OS4x6rgtuPyy13AP +tu3X3Y2kPVLu7ZMw5HoQC64wBj6YcnxTnBwmVW05DjzRXp6OyBIEKEaAB9vv2qEl +fh/Y234FG6Wd/ut1s0ScRZAo+6CSMNQxaY+ryXKD11uWkzWXJa9UZOasG7z4uPqc +Gr4/Hz2/CTLDTgp0xkMJYuzOztpUvOACrxlkS2utKUwVlAikJnboNwf/en94RbHN +zkKc5t0SAbzCf57ueawbzxSdPa+SAC25FNur64FKkfdq5PPjAgEDo4IB5TCCAeEw +EgYDVR0TAQH/BAgwBgEB/wIBCzA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vY3Js +LmNoYW1iZXJzaWduLm9yZy9jaGFtYmVyc3Jvb3QuY3JsMB0GA1UdDgQWBBS2H06d +HGiRLjdyYOFGj1qlKjExuTCBqwYDVR0jBIGjMIGggBTjlPWxTenboSlbV4tNdgZ2 +4dGiiqGBhKSBgTB/MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJt +YSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJz +aWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdIIBADAO +BgNVHQ8BAf8EBAMCAYYwKgYDVR0RBCMwIYEfYWNfY2FtZXJmaXJtYV9jY0BjYW1l +cmZpcm1hLmNvbTAnBgNVHRIEIDAegRxjaGFtYmVyc3Jvb3RAY2hhbWJlcnNpZ24u +b3JnMFsGA1UdIARUMFIwUAYLKwYBBAGBhy4KCQEwQTA/BggrBgEFBQcCARYzaHR0 +cDovL2Nwcy5jYW1lcmZpcm1hLmNvbS9jcHMvYWNfY2FtZXJmaXJtYV9jYy5odG1s +MA0GCSqGSIb3DQEBBQUAA4IBAQBl8KoPBYL//EBonqQWS0N+hLfxImP1eQ6nac+v +R5QfF/0w+VCTkShfKwHaa6V/W1dPlVwXSECuvXHkX6DYrtxFGGFB6qxuP1rkIpRs +sTkAlpvOx3REiFjIkhsijKd/ijvqxjbMbuYU+EFACK/jQIRoj+LEEZ+haiqbALZB +Iqq/26HTqX0itDosBj6M94YWcIpbTDefQNWCGsSnZcw2+k+az/wAOZT6xAxlnEim +HpDDlgRsmaLrHpDPDoIRYOih0gbJTnn4mKex9Wgr0sZ+XFl03j+bvcXL1tiuQnwb +9dMRDe/OdXABT35W4ZzLbpost65ZW3Tx+oi/bLbmu6pbKCgs +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersignca-chain.pem openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersignca-chain.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersignca-chain.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/ssl/X509TrustManagerImpl/distrust/chains/camerfirma/camerfirmachambersignca-chain.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,62 @@ +Owner: CN=AC Camerfirma - 2009, + L=Madrid (see current address at https://www.camerfirma.com/address), + SERIALNUMBER=A82743287, O=AC Camerfirma S.A., C=ES +Issuer: CN=Global Chambersign Root - 2008, + O=AC Camerfirma S.A., SERIALNUMBER=A82743287, + L=Madrid (see current address at www.camerfirma.com/address), C=EU +Serial number: 2 +Valid from: Mon Mar 16 10:16:25 PDT 2009 until: Sun Mar 11 10:16:25 PDT 2029 +Certificate fingerprints: + SHA1: BA:BA:69:CF:D5:CC:C9:4D:05:6B:5B:E7:80:5F:E2:03:CB:EB:5C:57 + SHA256: B6:8D:5D:9B:4E:A6:35:95:7C:0C:32:15:C2:0D:35:B2:21:7B:69:E3:49:C7:A3:04:C4:F9:7F:20:C4:08:1F:88 +Signature algorithm name: SHA1withRSA (weak) +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 + +-----BEGIN CERTIFICATE----- +MIIIPzCCBiegAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBrDELMAkGA1UEBhMCRVUx +QzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2Ft +ZXJmaXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UE +ChMSQUMgQ2FtZXJmaXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNp +Z24gUm9vdCAtIDIwMDgwHhcNMDkwMzE2MTcxNjI1WhcNMjkwMzExMTcxNjI1WjCB +qjELMAkGA1UEBhMCRVMxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjESMBAG +A1UEBRMJQTgyNzQzMjg3MUswSQYDVQQHE0JNYWRyaWQgKHNlZSBjdXJyZW50IGFk +ZHJlc3MgYXQgaHR0cHM6Ly93d3cuY2FtZXJmaXJtYS5jb20vYWRkcmVzcykxHTAb +BgNVBAMTFEFDIENhbWVyZmlybWEgLSAyMDA5MIICIjANBgkqhkiG9w0BAQEFAAOC +Ag8AMIICCgKCAgEAmbHxFEYTJmMdPcYiPlWUGZu2+tQo4voohYi3dwCwoVuGdHSp +kyoqs1B3YGx4u5KT4n0A7+Bb8YQ/QzbNy7UQ4JXAK+rT8JpNeKIvfN4lHnQJaChE +4fdn0KpvHWymaNq2k+EbQClquZB6OsTLvsivwSuSnyLcUw5rbajj53wq77fwB12y +phMjwz2AnD1BvHZd3vLOaH1jRQP3zzNmyjT/Oj6+jdux7SBKlJWgQEaKflwcvYyc +DPFPhGM4KPwEGX61PCrS+l8Lw0Kdy6K4lE+GrfgJrXM5m1Ey1R0c9McYQQPAtYcm +cOnHHgkJdEAFVDa76T9C+lcMP6DNckbJIyc/ENrmM2v4rq/JnsJKEEx0VLyLizQx +cGU3gp4ckg0ImQ9hV3H/DLWEqfrPuD++zaV81gpstnc9+pLg0Jibvwg3qvIr7nS5 +acc//qqxH0iJGYoStHW5J5HoM9HcBvhACq5rjzjrNLPYSJqbPJwBHKcql/uUjQ6S +SVWe3/CeJp6/vGuY1aRXAk9c/8oO0ZDrLKE8LsUgZesTLnWGd1LQcyQf6UMG1nb9 +5C3eZRkCVpKma6Hl/SUQNukerlbLOU9InFGNPdeEVq1Jo62XeEi8KMbTPdXou6Yl +rpe99dFnOUjVOdY7gfBGSgIVJjORqf/V70jwsxcYz7j6PKl0XulJs06vpSECAwEA +AaOCAmowggJmMBIGA1UdEwEB/wQIMAYBAf8CAQIwHQYDVR0OBBYEFMgAD/zGUvyf +2ztkLjK5bi5x82V5MIHhBgNVHSMEgdkwgdaAFLkJypwe29NsOmuu7VTxW5MGNS5e +oYGypIGvMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUgY3Vy +cmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAG +A1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAl +BgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwOIIJAMnN0+nVfSPO +MH0GCCsGAQUFBwEBBHEwbzBFBggrBgEFBQcwAoY5aHR0cDovL3d3dy5jYW1lcmZp +cm1hLmNvbS9jZXJ0cy9yb290X2NoYW1iZXJzaWduLTIwMDguY3J0MCYGCCsGAQUF +BzABhhpodHRwOi8vb2NzcC5jYW1lcmZpcm1hLmNvbTAOBgNVHQ8BAf8EBAMCAQYw +PgYDVR0gBDcwNTAzBgRVHSAAMCswKQYIKwYBBQUHAgEWHWh0dHBzOi8vcG9saWN5 +LmNhbWVyZmlybWEuY29tMH4GA1UdHwR3MHUwOKA2oDSGMmh0dHA6Ly9jcmwuY2Ft +ZXJmaXJtYS5jb20vY2hhbWJlcnNpZ25yb290LTIwMDguY3JsMDmgN6A1hjNodHRw +Oi8vY3JsMS5jYW1lcmZpcm1hLmNvbS9jaGFtYmVyc2lnbnJvb3QtMjAwOC5jcmww +DQYJKoZIhvcNAQEFBQADggIBABNYG4jBwoI7e8pCuUyDc6rwpE9H6AgrUdL7O1xK +TgTjDGBrMOBK+ZPS4Si8J3yZngvSrL694a1HmiiblJ+CmCdNGli2nBBM+OPK3tQB +4TW6hgkIe3vSNg/9o9y6+MAJcm8Kn0nPCBkSRME87NwvpehtekuF1G2ng1KDVwAn +F+eCXfNanEwY++vWbJAuPE69Z/0+rCgNyH1PzihiNu6vrUlSlLWKaG34O1DEttX+ +SsWTpEbpH9w5y9Vmw6WQ/B5nfhPM551HaMbiGgSxT9jHmf8APYQ3iT8EktcdTAdw +m1miiyxfKG+WjPT7P/x8Np1spJZw+sNIDTLdZ0T1XQ6obVkBTFUDSULKW8949HDu +VSwdl9Hu9lkDzzh9tyVYwwjEWVFZOiD/4TPVLfphf4ZEiyHt5YpNd9kZJIGGDxdc +CdtzPm2dQODFpv72LnPQHbuBQPJ71zkoAmyeM/1Qj0DlrFsPcYnbRasck1VmYgDc +Xc0+is0wcgCd7Gpx1zpEeVqwMD96am2xZPzd6nsbXvo+6TzsKLRMJo6nOERwrzuI +F+/eq3WXxYMt2UenJsHqwSgPJRMdl3SFz0+SZN0viHeLuwb7qaHN74qC6GP8yHGp +2xe6Z11mJDPLDSrQQ2dOceSJ1LurJgLP7amYmFlWwVnmM7LnfShhMWMV+MDrICnL +2ksL +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8281234 + * @summary The -protected option is not always checked in keytool and jarsigner + * @library /test/lib + * @modules java.base/sun.security.tools.keytool + * java.base/sun.security.x509 + */ + +import jdk.test.lib.Asserts; +import jdk.test.lib.SecurityTools; +import jdk.test.lib.util.JarUtils; +import sun.security.tools.keytool.CertAndKeyGen; +import sun.security.x509.X500Name; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.*; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarFile; + +public class AutoKeyStore { + + public static void main(String[] args) throws Exception { + + JarUtils.createJarFile(Path.of("unsigned.jar"), Path.of("."), + Files.writeString(Path.of("file"), "hello")); + + SecurityTools.keytool(""" + -J--add-exports -Jjava.base/sun.security.tools.keytool=ALL-UNNAMED + -J--add-exports -Jjava.base/sun.security.x509=ALL-UNNAMED + -providerClass AutoKeyStore$AutoProvider + -providerPath $test.classes + -storetype AUTO -keystore NONE -protected + -list + """).shouldHaveExitValue(0) + .shouldContain("Keystore type: AUTO") + .shouldContain("Keystore provider: AUTO") + .shouldContain("PrivateKeyEntry"); + + SecurityTools.jarsigner(""" + -J--add-exports -Jjava.base/sun.security.tools.keytool=ALL-UNNAMED + -J--add-exports -Jjava.base/sun.security.x509=ALL-UNNAMED + -J-cp -J$test.classes + -providerClass AutoKeyStore$AutoProvider + -storetype AUTO -keystore NONE -protected + -signedJar signed.jar + unsigned.jar + one + """).shouldHaveExitValue(0) + .shouldContain("jar signed."); + + Asserts.assertTrue(new JarFile("signed.jar") + .getEntry("META-INF/ONE.EC") != null); + } + + public static class AutoProvider extends Provider { + public AutoProvider() { + super("AUTO", "1.1.1", "auto"); + put("KeyStore.AUTO", "AutoKeyStore$KeyStoreImpl"); + } + } + + // This keystore is not based on file. Whenever it's loaded + // a self-sign certificate is generated inside + public static class KeyStoreImpl extends KeyStoreSpi { + + private PrivateKey pri; + private PublicKey pub; + private X509Certificate cert; + + @Override + public Key engineGetKey(String alias, char[] password) { + return pri; + } + + @Override + public Certificate[] engineGetCertificateChain(String alias) { + return new Certificate[] { cert }; + } + + @Override + public Certificate engineGetCertificate(String alias) { + return cert; + } + + @Override + public Date engineGetCreationDate(String alias) { + return new Date(); + } + + @Override + public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineDeleteEntry(String alias) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public Enumeration engineAliases() { + return Collections.enumeration(List.of("one")); + } + + @Override + public boolean engineContainsAlias(String alias) { + return alias.equalsIgnoreCase("one"); + } + + @Override + public int engineSize() { + return 1; + } + + @Override + public boolean engineIsKeyEntry(String alias) { + return true; + } + + @Override + public boolean engineIsCertificateEntry(String alias) { + return false; + } + + @Override + public String engineGetCertificateAlias(Certificate cert) { + return "one"; + } + + @Override + public void engineStore(OutputStream stream, char[] password) { + } + + @Override + public void engineLoad(InputStream stream, char[] password) throws IOException { + try { + CertAndKeyGen cag = new CertAndKeyGen("EC", "SHA256withECDSA"); + cag.generate("secp256r1"); + pri = cag.getPrivateKey(); + pub = cag.getPublicKey(); + cert = cag.getSelfCertificate(new X500Name("CN=one"), 3600); + } catch (Exception e) { + throw new IOException("Not loaded"); + } + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java 2025-04-09 19:45:33.000000000 +0000 @@ -244,9 +244,8 @@ * @see "concise_jarsigner.sh" */ String[] getExpectedJarSignerOutputUpdatedContentNotValidatedBySignerA( - String jarFilename, String digestalg, String firstAddedFilename, String secondAddedFilename) { - final String TS = ".{28,29}"; // matches a timestamp + final String TS = ".{28,34}"; // matches a timestamp List expLines = new ArrayList<>(); expLines.add("s k *\\d+ " + TS + " META-INF/MANIFEST[.]MF"); expLines.add(" *\\d+ " + TS + " META-INF/B[.]SF"); @@ -348,7 +347,6 @@ assertMatchByLines( fromFirstToSecondEmptyLine(o.getStdout().split("\\R")), getExpectedJarSignerOutputUpdatedContentNotValidatedBySignerA( - jarFilename4, digestalg, firstAddedFilename, secondAddedFilename)); // double-check reading the files with a verifying JarFile diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/RemovedFiles.java openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/RemovedFiles.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/RemovedFiles.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/RemovedFiles.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8309841 + * @summary Jarsigner should print a warning if an entry is removed + * @library /test/lib + */ + +import jdk.test.lib.SecurityTools; +import jdk.test.lib.util.JarUtils; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.jar.Attributes; +import java.util.jar.Manifest; + +public class RemovedFiles { + + private static final String NONEXISTENT_ENTRIES_FOUND + = "This jar contains signed entries for files that do not exist. See the -verbose output for more details."; + + public static void main(String[] args) throws Exception { + JarUtils.createJarFile( + Path.of("a.jar"), + Path.of("."), + Files.writeString(Path.of("a"), "a"), + Files.writeString(Path.of("b"), "b")); + SecurityTools.keytool("-genkeypair -storepass changeit -keystore ks -alias x -dname CN=x -keyalg ed25519"); + SecurityTools.jarsigner("-storepass changeit -keystore ks a.jar x"); + + // All is fine at the beginning. + SecurityTools.jarsigner("-verify a.jar") + .shouldNotContain(NONEXISTENT_ENTRIES_FOUND); + + // Remove an entry after signing. There will be a warning. + JarUtils.deleteEntries(Path.of("a.jar"), "a"); + SecurityTools.jarsigner("-verify a.jar") + .shouldContain(NONEXISTENT_ENTRIES_FOUND); + SecurityTools.jarsigner("-verify -verbose a.jar") + .shouldContain(NONEXISTENT_ENTRIES_FOUND) + .shouldContain("Warning: nonexistent signed entries: [a]"); + + // Remove one more entry. + JarUtils.deleteEntries(Path.of("a.jar"), "b"); + SecurityTools.jarsigner("-verify a.jar") + .shouldContain(NONEXISTENT_ENTRIES_FOUND); + SecurityTools.jarsigner("-verify -verbose a.jar") + .shouldContain(NONEXISTENT_ENTRIES_FOUND) + .shouldContain("Warning: nonexistent signed entries: [a, b]"); + + // Re-sign will not clear the warning. + SecurityTools.jarsigner("-storepass changeit -keystore ks a.jar x"); + SecurityTools.jarsigner("-verify a.jar") + .shouldContain(NONEXISTENT_ENTRIES_FOUND); + + // Unfortunately, if there is a non-file entry in manifest, there will be + // a false alarm. See https://bugs.openjdk.org/browse/JDK-8334261. + var man = new Manifest(); + man.getMainAttributes().putValue("Manifest-Version", "1.0"); + man.getEntries().computeIfAbsent("Hello", key -> new Attributes()) + .putValue("Foo", "Bar"); + JarUtils.createJarFile(Path.of("b.jar"), + man, + Path.of("."), + Path.of("a")); + SecurityTools.jarsigner("-storepass changeit -keystore ks b.jar x"); + SecurityTools.jarsigner("-verbose -verify b.jar") + .shouldContain("Warning: nonexistent signed entries: [Hello]") + .shouldContain(NONEXISTENT_ENTRIES_FOUND); + + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ * its usages, please look through the README. * * @library /test/lib ../warnings - * @compile -source 1.7 -target 1.7 JdkUtils.java + * @compile -source 1.8 -target 1.8 JdkUtils.java * @run main/manual/othervm Compatibility */ @@ -67,7 +67,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import jdk.test.lib.Platform; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.JarUtils; @@ -460,7 +459,7 @@ if (RSA.equals(keyAlgorithm) || DSA.equals(keyAlgorithm)) { return new int[] { 1024, 2048, 0 }; // 0 is no keysize specified } else if (EC.equals(keyAlgorithm)) { - return new int[] { 384, 571, 0 }; // 0 is no keysize specified + return new int[] { 384, 521, 0 }; // 0 is no keysize specified } else { throw new RuntimeException("problem determining key sizes"); } @@ -717,7 +716,7 @@ try { String match = "^ (" + " Signature algorithm: " + signItem.certInfo. - expectedSigalg() + ", " + signItem.certInfo. + expectedSigalg(signItem) + ", " + signItem.certInfo. expectedKeySize() + "-bit key" + ")|(" + " Digest algorithm: " + signItem.expectedDigestAlg() @@ -845,6 +844,7 @@ if (isWeakAlg(signItem.expectedDigestAlg()) && line.contains(Test.WEAK_ALGORITHM_WARNING)) continue; + if (line.contains(Test.WEAK_KEY_WARNING)) continue; if (Test.CERTIFICATE_SELF_SIGNED.equals(line)) continue; if (Test.HAS_EXPIRED_CERT_VERIFYING_WARNING.equals(line) && signItem.certInfo.expired) continue; @@ -1036,15 +1036,9 @@ long start = System.currentTimeMillis(); try { String[] cmd; - if (Platform.isWindows()) { - cmd = new String[args.length + 3]; - System.arraycopy(args, 0, cmd, 3, args.length); - } else { - cmd = new String[args.length + 4]; - cmd[3] = "-J-Djava.security.egd=file:/dev/./urandom"; - System.arraycopy(args, 0, cmd, 4, args.length); - } + cmd = new String[args.length + 3]; + System.arraycopy(args, 0, cmd, 3, args.length); cmd[0] = toolPath; cmd[1] = "-J-Duser.language=en"; cmd[2] = "-J-Duser.country=US"; @@ -1189,19 +1183,56 @@ } private String expectedSigalg() { - return (DEFAULT.equals(this.digestAlgorithm) ? this.digestAlgorithm - : "SHA-256").replace("-", "") + "with" + - keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + } + + private String expectedSigalg(SignItem signer) { + if (!DEFAULT.equals(digestAlgorithm)) { + return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + + } else { + // default algorithms documented for jarsigner here: + // https://docs.oracle.com/en/java/javase/17/docs/specs/man/jarsigner.html#supported-algorithms + // https://docs.oracle.com/en/java/javase/20/docs/specs/man/jarsigner.html#supported-algorithms + int expectedKeySize = expectedKeySize(); + switch (keyAlgorithm) { + case DSA: + return "SHA256withDSA"; + case RSA: { + if ((signer.jdkInfo.majorVersion >= 20 && expectedKeySize < 624) + || (signer.jdkInfo.majorVersion < 20 && expectedKeySize <= 3072)) { + return "SHA256withRSA"; + } else if (expectedKeySize <= 7680) { + return "SHA384withRSA"; + } else { + return "SHA512withRSA"; + } + } + case EC: { + if (signer.jdkInfo.majorVersion < 20 && expectedKeySize < 384) { + return "SHA256withECDSA"; + } else if (expectedKeySize < 512) { + return "SHA384withECDSA"; + } else { + return "SHA512withECDSA"; + } + } + default: + throw new RuntimeException("Unsupported/expected key algorithm: " + keyAlgorithm); + } + } } private int expectedKeySize() { if (keySize != 0) return keySize; // defaults - if (RSA.equals(keyAlgorithm) || DSA.equals(keyAlgorithm)) { + if (RSA.equals(keyAlgorithm)) { + return jdkInfo.majorVersion >= 20 ? 3072 : 2048; + } else if (DSA.equals(keyAlgorithm)) { return 2048; } else if (EC.equals(keyAlgorithm)) { - return 256; + return jdkInfo.majorVersion >= 20 ? 384 : 256; } else { throw new RuntimeException("problem determining key size"); } @@ -1397,7 +1428,9 @@ } String expectedDigestAlg() { - return digestAlgorithm != null ? digestAlgorithm : "SHA-256"; + return digestAlgorithm != null + ? digestAlgorithm + : jdkInfo.majorVersion >= 20 ? "SHA-384" : "SHA-256"; } private SignItem tsaDigestAlgorithm(String tsaDigestAlgorithm) { @@ -1546,7 +1579,7 @@ s_values_add.accept(i -> i.unsignedJar + " -> " + i.signedJar); s_values_add.accept(i -> i.certInfo.toString()); s_values_add.accept(i -> i.jdkInfo.version); - s_values_add.accept(i -> i.certInfo.expectedSigalg()); + s_values_add.accept(i -> i.certInfo.expectedSigalg(i)); s_values_add.accept(i -> null2Default(i.digestAlgorithm, i.expectedDigestAlg())); s_values_add.accept(i -> i.tsaIndex == -1 ? "" : diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/warnings/Test.java openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/warnings/Test.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/tools/jarsigner/warnings/Test.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/tools/jarsigner/warnings/Test.java 2025-04-09 19:45:33.000000000 +0000 @@ -148,6 +148,9 @@ = "algorithm is considered a security risk. " + "This algorithm will be disabled in a future update."; + static final String WEAK_KEY_WARNING + = "This key size will be disabled in a future update."; + static final String JAR_SIGNED = "jar signed."; static final String JAR_VERIFIED = "jar verified."; diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/validator/samedn.sh openjdk-17-17.0.15+6/test/jdk/sun/security/validator/samedn.sh --- openjdk-17-17.0.14+7/test/jdk/sun/security/validator/samedn.sh 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/validator/samedn.sh 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ # -# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -62,10 +62,11 @@ $KT -genkeypair -alias ca2 -dname CN=CA -keyalg rsa -sigalg sha1withrsa -ext bc -startdate -1y $KT -genkeypair -alias user -dname CN=User -keyalg rsa -# 2. Signing: ca -> user +# 2. Signing: ca -> user. The startdate is set to 1 minute in the past to ensure the certificate +# is valid at the time of validation and to prevent any issues with timing discrepancies -$KT -certreq -alias user | $KT -gencert -rfc -alias ca1 > samedn1.certs -$KT -certreq -alias user | $KT -gencert -rfc -alias ca2 > samedn2.certs +$KT -certreq -alias user | $KT -gencert -rfc -alias ca1 -startdate -1M > samedn1.certs +$KT -certreq -alias user | $KT -gencert -rfc -alias ca2 -startdate -1M > samedn2.certs # 3. Append the ca file diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8311546 + * @summary Adopt de-facto standards on x509 Name Constraints with leading dot. Certs + * can be generated by running generate-certs.sh + * @run main LeadingPeriod + */ + +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.security.Security; +import java.security.cert.*; + +public class LeadingPeriod { + + public static void main(String[] args) throws Exception { + String certs = System.getProperty("test.src", "./") + "/certs/"; + validate(certs + "withoutLeadingPeriod"); + validate(certs + "withLeadingPeriod"); + } + + public static void validate(String certPath) throws Exception { + byte[] targetCertBytes = Files.readAllBytes(Paths.get(certPath + "/leaf.pem")); + byte[] caCertBytes = Files.readAllBytes(Paths.get(certPath + "/ca.pem")); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + Certificate caCert = cf.generateCertificate(new ByteArrayInputStream(caCertBytes)); + Certificate targetCert = cf.generateCertificate(new ByteArrayInputStream(targetCertBytes)); + + TrustAnchor anchor = new TrustAnchor((X509Certificate) caCert, null); + + PKIXParameters params = new PKIXParameters(Collections.singleton(anchor)); + + // Disable certificate revocation checking + params.setRevocationEnabled(false); + + // Set validity date, so that validation won't fail when cert expires + params.setDate(((X509Certificate)targetCert).getNotBefore()); + + CertPath path = cf.generateCertPath(List.of(targetCert, caCert)); + + CertPathValidator validator = CertPathValidator.getInstance("PKIX"); + validator.validate(path, params); + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,91 @@ +#!/usr/bin/env bash + +set -e + +############################################################### +# CA with a leading period in the name constraint # +############################################################### +mkdir -p withLeadingPeriod + +openssl req \ + -newkey rsa:1024 \ + -keyout withLeadingPeriod/ca.key \ + -out withLeadingPeriod/ca.csr \ + -subj "/C=US/O=Example/CN=Example CA with period" \ + -nodes + +openssl x509 \ + -req \ + -in withLeadingPeriod/ca.csr \ + -extfile openssl.cnf \ + -extensions withLeadingPeriod \ + -signkey withLeadingPeriod/ca.key \ + -out withLeadingPeriod/ca.pem + +# leaf certificate +openssl req \ + -newkey rsa:1024 \ + -keyout withLeadingPeriod/leaf.key \ + -out withLeadingPeriod/leaf.csr \ + -subj '/CN=demo.example.com' \ + -addext 'subjectAltName = DNS:demo.example.com' \ + -nodes + +openssl x509 \ + -req \ + -in withLeadingPeriod/leaf.csr \ + -CAcreateserial \ + -CA withLeadingPeriod/ca.pem \ + -CAkey withLeadingPeriod/ca.key \ + -out withLeadingPeriod/leaf.pem + + +# ################################################################## +# # CA without a leading period in the name contraint # +# ################################################################## +mkdir -p withoutLeadingPeriod + +openssl req \ + -newkey rsa:1024 \ + -keyout withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/ca.csr \ + -subj "/C=US/O=Example/CN=Example CA without period" \ + -nodes + +openssl x509 \ + -req \ + -in withoutLeadingPeriod/ca.csr \ + -extfile openssl.cnf \ + -extensions withoutLeadingPeriod \ + -signkey withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/ca.pem + +# leaf certificate +openssl req \ + -newkey rsa:1024 \ + -keyout withoutLeadingPeriod/leaf.key \ + -out withoutLeadingPeriod/leaf.csr \ + -subj '/CN=demo.example.com' \ + -addext 'subjectAltName = DNS:demo.example.com' \ + -nodes + +openssl x509 \ + -req \ + -in withoutLeadingPeriod/leaf.csr \ + -CAcreateserial \ + -CA withoutLeadingPeriod/ca.pem \ + -CAkey withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/leaf.pem + + +# # Verify both leaf certificates + +set +e +openssl verify \ + -CAfile withLeadingPeriod/ca.pem \ + withLeadingPeriod/leaf.pem + +openssl verify \ + -CAfile withoutLeadingPeriod/ca.pem \ + withoutLeadingPeriod/leaf.pem + \ No newline at end of file diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,40 @@ +# +# OpenSSL configuration file. +# + +[ withLeadingPeriod ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign +nameConstraints = critical,permitted;DNS:.example.com + +[ withoutLeadingPeriod ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign +nameConstraints = critical,permitted;DNS:example.com + +[ v3_ca ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign + + +[req] +distinguished_name = req_distinguished_name +x509_extensions = v3_ca # The extentions to add to self signed certs +req_extensions = v3_req # The extensions to add to req's + +prompt = no + +[req_distinguished_name] +C = US +O = Example +CN = example.com + +[v3_req] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = serverAuth diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICgzCCAeygAwIBAgIJANBGv+BGZZHtMA0GCSqGSIb3DQEBCwUAMEAxCzAJBgNV +BAYTAlVTMRAwDgYDVQQKDAdFeGFtcGxlMR8wHQYDVQQDDBZFeGFtcGxlIENBIHdp +dGggcGVyaW9kMB4XDTIzMTAxOTIwNTE0NVoXDTIzMTExODIwNTE0NVowQDELMAkG +A1UEBhMCVVMxEDAOBgNVBAoMB0V4YW1wbGUxHzAdBgNVBAMMFkV4YW1wbGUgQ0Eg +d2l0aCBwZXJpb2QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPfaISk+Dvzk +m3AY7IDZYrGWpwxHciacalrsrOFl3mj3FQ/kVhofDri3mE7bxNKWyHNcbt+Cteck +TsGKBH85QsIifju7hqlrR+UbYtQF9/REkxX72gzim4xGk9KmKkuGpT5aZgvTE5eg +ZumJ9XxCjGn5nbsdJoqAE/9B96GqXJvlAgMBAAGjgYQwgYEwHQYDVR0OBBYEFG8h +vtka47iFUsc+3wmQ3LQRXUv3MB8GA1UdIwQYMBaAFG8hvtka47iFUsc+3wmQ3LQR +XUv3MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIEMB4GA1UdHgEB/wQU +MBKgEDAOggwuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADgYEAkPeCbKokI067 +Dt2bommouO7LhTXivjMsByfZs8i9LZUVJz5Is+mDC36nLy4U3+QhofRLlEkWyOlE +033xBtm4YPsazpur79PJtvZemV0KwwMtKCoJYNlcy2llmdKjUwe4PsPnJPqH2KL5 +Cxios1gil8XL5OCmEUSCT9uBblh+9gk= +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB0jCCATsCCQCgOCS7vOUOXTANBgkqhkiG9w0BAQsFADBAMQswCQYDVQQGEwJV +UzEQMA4GA1UECgwHRXhhbXBsZTEfMB0GA1UEAwwWRXhhbXBsZSBDQSB3aXRoIHBl +cmlvZDAeFw0yMzEwMTkyMDUxNDVaFw0yMzExMTgyMDUxNDVaMBsxGTAXBgNVBAMM +EGRlbW8uZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxi +O4r50rNBbHu/blOSRfo9Vqei+QFS7fPwme68FOcvG+uYXf7zluO59V+8O4RPO+ZJ +W6meZvtpOCWFvlSMhBLTRz350LuSPWF+/tnbiyEv487Vi6Tp7kxJytIcMtH/sWkw +hF0Og8YYt3Xm2aLYPxZHGkvOccjau5X1xG1YiULzAgMBAAEwDQYJKoZIhvcNAQEL +BQADgYEA8OXnFO3yZSVmQfYvC2o9amYa7tNUPHgvEjp7xDlPkvL5zF+n8k0hT0kt +pv4BXzRqVIWsZcNi3H1wk6LMeUXi8EWCOR6gclWI0wZkWBhtoh8SCd2VJRmcv+zG +EnInCapszNKN05KEzaFOQv0QayILBUGgHTTXOgbEmryLHXg6zik= +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICiDCCAfGgAwIBAgIJALUX88nU2b75MA0GCSqGSIb3DQEBCwUAMEMxCzAJBgNV +BAYTAlVTMRAwDgYDVQQKDAdFeGFtcGxlMSIwIAYDVQQDDBlFeGFtcGxlIENBIHdp +dGhvdXQgcGVyaW9kMB4XDTIzMTAxOTIwNTE0NVoXDTIzMTExODIwNTE0NVowQzEL +MAkGA1UEBhMCVVMxEDAOBgNVBAoMB0V4YW1wbGUxIjAgBgNVBAMMGUV4YW1wbGUg +Q0Egd2l0aG91dCBwZXJpb2QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANmH +HqVoDjgoS60aPhQisqEL3as81tPXxXgnp5M0TE+Lb0z/kXS2mkqYYhzcZneBhVyI +oGTnSnTSh6S1r/gE80x+hH4ZrLZR7jJMRDA9Q7RTOZBNgozS4XnE3AV/EjrIzHJ1 +IEt1ezoj2QNdVOv7UHprHGoARl9tdxre4MVUv4S3AgMBAAGjgYMwgYAwHQYDVR0O +BBYEFFG0Mvse4c5C01o8kvKiM4MKMJTCMB8GA1UdIwQYMBaAFFG0Mvse4c5C01o8 +kvKiM4MKMJTCMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIEMB0GA1Ud +HgEB/wQTMBGgDzANggtleGFtcGxlLmNvbTANBgkqhkiG9w0BAQsFAAOBgQC0CKS0 +JOR8hfUkZHBo52PrF3IKs33wczH5mfV+HLTdSeKtBD0Vj/7DoT0Yx2k5n6vpwA/x +LTSMC4wUo4hb5164ks45iloU0FrA+n9fWbeqwhQb+DW5MSOgoVLkW+rcdKbDatTO +ENcKZsqiG3aKM7pS7mQa+kUUpXWBUgVnhcsYtQ== +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1TCCAT4CCQDLscehyPPGXjANBgkqhkiG9w0BAQsFADBDMQswCQYDVQQGEwJV +UzEQMA4GA1UECgwHRXhhbXBsZTEiMCAGA1UEAwwZRXhhbXBsZSBDQSB3aXRob3V0 +IHBlcmlvZDAeFw0yMzEwMTkyMDUxNDVaFw0yMzExMTgyMDUxNDVaMBsxGTAXBgNV +BAMMEGRlbW8uZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB +AMZM9Prp5DkAe4pkLqn4v8DFamMtWVqPlYacJacGzBkuzBn8VNQQw4qnf6wiVHBj +uXLHrUCbldtKFK4XdVukmVyYSLR5BBPxA20fjZcsrBZW7u/14qWmIZW7G0xphezg +6g33qNPq9CPqVHR+IrfEmjWnLjc2KrZ3OQElpJOGp48hAgMBAAEwDQYJKoZIhvcN +AQELBQADgYEAYbIuAQKTXsgaBP3pyMqxPHvklDI7wJjEapbKDsOXYmKMb33pmFSD +ntQFZuOKYNV2rAqQaV/3kiWKyR4vO/gsCfuFeW8kxkhZEXX9CNU0Z6mKcvy274A4 +K0gqYGki8hyCc5IMWTUAX2TLdq8W1hwfbjeiNqTY21e+6lIa3kcuLC0= +-----END CERTIFICATE----- diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8179502 + * @summary Enhance OCSP, CRL and Certificate Fetch Timeouts + * @modules java.base/sun.security.x509 + * java.base/sun.security.util + * @library /test/lib ../../../../java/security/testlibrary + * @build CertificateBuilder + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1 AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1s AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=4 AIACertTimeout 1000 true + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1500ms AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=4500ms AIACertTimeout 1000 true + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.enableAIAcaIssuers=false + * -Dcom.sun.security.cert.readtimeout=20000ms AIACertTimeout 10000 false + */ + +import com.sun.net.httpserver.*; +import java.io.*; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.security.cert.*; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.spec.*; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import sun.security.testlibrary.CertificateBuilder; + +import sun.security.x509.*; +import sun.security.util.*; + +public class AIACertTimeout { + + private static final boolean logging = true; + + // PKI and server components we will need for this test + private static KeyPair rootKp; // Root CA keys + private static X509Certificate rootCert; + private static KeyPair intKp; // Intermediate CA keys + private static X509Certificate intCert; + private static KeyPair eeKp; // End-entity keys + private static X509Certificate eeCert; + + public static void main(String[] args) throws Exception { + int servTimeoutMsec = (args != null && args.length >= 1) ? + Integer.parseInt(args[0]) : -1; + boolean expectedPass = args != null && args.length >= 2 && + Boolean.parseBoolean(args[1]); + + createAuthorities(); + CaCertHttpServer aiaServer = new CaCertHttpServer(intCert, + servTimeoutMsec); + try { + aiaServer.start(); + createEE(aiaServer.getAddress()); + + X509CertSelector target = new X509CertSelector(); + target.setCertificate(eeCert); + PKIXParameters params = new PKIXBuilderParameters(Set.of( + new TrustAnchor(rootCert, null)), target); + params.setRevocationEnabled(false); + + try { + CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX"); + CertPathBuilderResult result = cpb.build(params); + if (expectedPass) { + int pathLen = result.getCertPath().getCertificates().size(); + if (pathLen != 2) { + throw new RuntimeException("Expected 2 certificates " + + "in certpath, got " + pathLen); + } + } else { + throw new RuntimeException("Missing expected CertPathBuilderException"); + } + } catch (CertPathBuilderException cpve) { + if (!expectedPass) { + log("Cert path building failed as expected: " + cpve); + } else { + throw cpve; + } + } + } finally { + aiaServer.stop(); + } + } + + private static class CaCertHttpServer { + + private final X509Certificate caCert; + private final HttpServer server; + private final int timeout; + + public CaCertHttpServer(X509Certificate cert, int timeout) + throws IOException { + caCert = Objects.requireNonNull(cert, "Null CA cert disallowed"); + server = HttpServer.create(); + this.timeout = timeout; + if (timeout > 0) { + log("Created HttpServer with timeout of " + timeout + " msec."); + } else { + log("Created HttpServer with no timeout"); + } + } + + public void start() throws IOException { + server.bind(new InetSocketAddress("localhost", 0), 0); + server.createContext("/cacert", t -> { + try (InputStream is = t.getRequestBody()) { + is.readAllBytes(); + } + try { + if (timeout > 0) { + // Sleep in order to simulate network latency + log("Server sleeping for " + timeout + " msec."); + Thread.sleep(timeout); + } + + byte[] derCert = caCert.getEncoded(); + t.getResponseHeaders().add("Content-Type", + "application/pkix-cert"); + t.sendResponseHeaders(200, derCert.length); + try (OutputStream os = t.getResponseBody()) { + os.write(derCert); + } + } catch (InterruptedException | + CertificateEncodingException exc) { + throw new IOException(exc); + } + }); + server.setExecutor(null); + server.start(); + log("Started HttpServer: Listening on " + server.getAddress()); + } + + public void stop() { + server.stop(0); + } + + public InetSocketAddress getAddress() { + return server.getAddress(); + } + } + + + /** + * Creates the CA PKI components necessary for this test. + */ + private static void createAuthorities() throws Exception { + CertificateBuilder cbld = new CertificateBuilder(); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); + keyGen.initialize(new ECGenParameterSpec("secp256r1")); + + // Generate Root, IntCA, EE keys + rootKp = keyGen.genKeyPair(); + log("Generated Root CA KeyPair"); + intKp = keyGen.genKeyPair(); + log("Generated Intermediate CA KeyPair"); + eeKp = keyGen.genKeyPair(); + log("Generated End Entity Cert KeyPair"); + + // Make a 3 year validity starting from 60 days ago + long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60); + long end = start + TimeUnit.DAYS.toMillis(1085); + + boolean[] kuBitSettings = {true, false, false, false, false, true, + true, false, false}; + + // Set up the Root CA Cert + cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany"). + setPublicKey(rootKp.getPublic()). + setSerialNumber(new BigInteger("1")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(rootKp.getPublic()). + addAuthorityKeyIdExt(rootKp.getPublic()). + addBasicConstraintsExt(true, true, -1). + addKeyUsageExt(kuBitSettings); + + // Make our Root CA Cert! + rootCert = cbld.build(null, rootKp.getPrivate(), "SHA256withECDSA"); + log("Root CA Created:\n" + certInfo(rootCert)); + + // Make a 2 year validity starting from 30 days ago + start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30); + end = start + TimeUnit.DAYS.toMillis(730); + + // Now that we have the root keystore we can create our + // intermediate CA. + cbld.reset(); + cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany"). + setPublicKey(intKp.getPublic()). + setSerialNumber(new BigInteger("100")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(intKp.getPublic()). + addAuthorityKeyIdExt(rootKp.getPublic()). + addBasicConstraintsExt(true, true, -1). + addKeyUsageExt(kuBitSettings); + + // Make our Intermediate CA Cert! + intCert = cbld.build(rootCert, rootKp.getPrivate(), "SHA256withECDSA"); + log("Intermediate CA Created:\n" + certInfo(intCert)); + } + + /** + * Creates the end entity certificate from the previously generated + * intermediate CA cert. + * + * @param aiaAddr the address/port of the server that will hold the issuer + * certificate. This will be used to create an AIA URI. + */ + private static void createEE(InetSocketAddress aiaAddr) throws Exception { + // Make a 1 year validity starting from 7 days ago + long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7); + long end = start + TimeUnit.DAYS.toMillis(365); + boolean[] kuBits = {true, false, false, false, false, false, + false, false, false}; + List ekuOids = List.of("1.3.6.1.5.5.7.3.1", + "1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.4"); + String aiaUri = String.format("http://%s:%d/cacert", + aiaAddr.getHostName(), aiaAddr.getPort()); + + CertificateBuilder cbld = new CertificateBuilder(); + cbld.setSubjectName("CN=Oscar T. Grouch, O=SomeCompany"). + setPublicKey(eeKp.getPublic()). + setSerialNumber(new BigInteger("4096")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(eeKp.getPublic()). + addAuthorityKeyIdExt(intKp.getPublic()). + addKeyUsageExt(kuBits).addExtendedKeyUsageExt(ekuOids). + addAIAExt(List.of("CAISSUER|" + aiaUri)); + + // Build the cert + eeCert = cbld.build(intCert, intKp.getPrivate(), "SHA256withECDSA"); + log("EE Certificate Created:\n" + certInfo(eeCert)); + } + + /** + * Helper routine that dumps only a few cert fields rather than + * the whole toString() output. + * + * @param cert an X509Certificate to be displayed + * + * @return the String output of the issuer, subject and + * serial number + */ + private static String certInfo(X509Certificate cert) { + StringBuilder sb = new StringBuilder(); + sb.append("Issuer: ").append(cert.getIssuerX500Principal()). + append("\n"); + sb.append("Subject: ").append(cert.getSubjectX500Principal()). + append("\n"); + sb.append("Serial: ").append(cert.getSerialNumber()).append("\n"); + return sb.toString(); + } + + private static void log(String str) { + if (logging) { + System.out.println("[" + Thread.currentThread().getName() + "] " + + str); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java --- openjdk-17-17.0.14+7/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,55 +23,70 @@ /* * @test - * @bug 8191808 + * @bug 8191808 8179502 * @summary check that CRL download is interrupted if it takes too long + * @modules java.base/sun.security.x509 + * java.base/sun.security.util * @library /test/lib - * @run main/othervm -Dcom.sun.security.crl.readtimeout=1 CRLReadTimeout + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1 + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1s + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=4 + * CRLReadTimeout 1000 true + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1500ms + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=4500ms + * CRLReadTimeout 1000 true */ -import java.io.File; -import java.io.InputStream; -import java.io.IOException; +import java.io.*; +import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; +import java.security.GeneralSecurityException; import java.security.KeyStore; -import java.security.cert.CertificateFactory; -import java.security.cert.CertPath; -import java.security.cert.CertPathValidator; -import java.security.cert.CertPathValidatorException; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXRevocationChecker; -import static java.security.cert.PKIXRevocationChecker.Option.*; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; +import java.security.PrivateKey; +import java.security.cert.*; +import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Set; -import com.sun.net.httpserver.HttpServer; +import java.util.concurrent.TimeUnit; + +import static java.security.cert.PKIXRevocationChecker.Option.*; +import com.sun.net.httpserver.HttpServer; import jdk.test.lib.SecurityTools; import jdk.test.lib.process.OutputAnalyzer; +import sun.security.util.SignatureUtil; +import sun.security.x509.*; public class CRLReadTimeout { + public static final String PASS = "changeit"; + public static X509CRL crl; + public static void main(String[] args) throws Exception { - String timeout = System.getProperty("com.sun.security.crl.readtimeout"); - if (timeout == null) { - timeout = "15"; - } - System.out.println("Testing timeout of " + timeout + " seconds"); + int serverTimeout = (args != null && args[0] != null) ? + Integer.parseInt(args[0]) : 15000; + boolean expectedPass = args != null && args[1] != null && + Boolean.parseBoolean(args[1]); + System.out.println("Server timeout is " + serverTimeout + " msec."); + System.out.println("Test is expected to " + (expectedPass ? "pass" : "fail")); - CrlHttpServer crlServer = new CrlHttpServer(Integer.parseInt(timeout)); + CrlHttpServer crlServer = new CrlHttpServer(serverTimeout); try { crlServer.start(); - testTimeout(crlServer.getPort()); + testTimeout(crlServer.getPort(), expectedPass); } finally { crlServer.stop(); } } - private static void testTimeout(int port) throws Exception { + private static void testTimeout(int port, boolean expectedPass) + throws Exception { // create certificate chain with two certs, root and end-entity keytool("-alias duke -dname CN=duke -genkey -keyalg RSA"); @@ -82,10 +97,10 @@ + "-ext crl=uri:http://localhost:" + port + "/crl"); keytool("-importcert -file duke.cert -alias duke"); - KeyStore ks = KeyStore.getInstance(new File("ks"), - "changeit".toCharArray()); + KeyStore ks = KeyStore.getInstance(new File("ks"), PASS.toCharArray()); X509Certificate cert = (X509Certificate)ks.getCertificate("duke"); X509Certificate root = (X509Certificate)ks.getCertificate("root"); + crl = genCrl(ks, "root", PASS); // validate chain CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); @@ -100,28 +115,60 @@ cpv.validate(cp, params); // unwrap soft fail exceptions and check for SocketTimeoutException - boolean expected = false; - for (CertPathValidatorException softFail:prc.getSoftFailExceptions()) { - Throwable cause = softFail.getCause(); - while (cause != null) { - if (cause instanceof SocketTimeoutException) { - expected = true; + List softExc = prc.getSoftFailExceptions(); + if (expectedPass) { + if (softExc.size() > 0) { + throw new RuntimeException("Expected to pass, found " + + softExc.size() + " soft fail exceptions"); + } + } else { + boolean foundSockTOExc = false; + for (CertPathValidatorException softFail : softExc) { + Throwable cause = softFail.getCause(); + while (cause != null) { + if (cause instanceof SocketTimeoutException) { + foundSockTOExc = true; + break; + } + cause = cause.getCause(); + } + if (foundSockTOExc) { break; } - cause = cause.getCause(); } - if (expected) { - break; + if (!foundSockTOExc) { + throw new Exception("SocketTimeoutException not thrown"); } } - if (!expected) { - throw new Exception("SocketTimeoutException not thrown"); - } } private static OutputAnalyzer keytool(String cmd) throws Exception { - return SecurityTools.keytool("-storepass changeit " - + "-keystore ks " + cmd); + return SecurityTools.keytool("-storepass " + PASS + + " -keystore ks " + cmd); + } + + private static X509CRL genCrl(KeyStore ks, String issAlias, String pass) + throws GeneralSecurityException, IOException { + // Create an empty CRL with a 1-day validity period. + X509Certificate issuerCert = (X509Certificate)ks.getCertificate(issAlias); + PrivateKey issuerKey = (PrivateKey)ks.getKey(issAlias, pass.toCharArray()); + + long curTime = System.currentTimeMillis(); + Date thisUp = new Date(curTime - TimeUnit.SECONDS.toMillis(43200)); + Date nextUp = new Date(curTime + TimeUnit.SECONDS.toMillis(43200)); + CRLExtensions exts = new CRLExtensions(); + var aki = new AuthorityKeyIdentifierExtension(new KeyIdentifier( + issuerCert.getPublicKey()), null, null); + var crlNum = new CRLNumberExtension(BigInteger.ONE); + exts.set(aki.getId(), aki); + exts.set(crlNum.getId(), crlNum); + X509CRLImpl crl = new X509CRLImpl( + new X500Name(issuerCert.getSubjectX500Principal().toString()), + thisUp, nextUp, null, exts); + crl.sign(issuerKey, + SignatureUtil.getDefaultSigAlgForKey(issuerKey)); + System.out.println("ISSUED CRL:\n" + crl); + return crl; } private static class CrlHttpServer { @@ -136,15 +183,23 @@ public void start() throws IOException { server.bind(new InetSocketAddress(0), 0); - server.createContext("/", t -> { + server.createContext("/crl", t -> { try (InputStream is = t.getRequestBody()) { is.readAllBytes(); } try { - // sleep for 2 seconds longer to force timeout - Thread.sleep((timeout + 2)*1000); - } catch (InterruptedException ie) { - throw new IOException(ie); + // Sleep in order to simulate network latency + Thread.sleep(timeout); + + byte[] derCrl = crl.getEncoded(); + t.getResponseHeaders().add("Content-Type", + "application/pkix-crl"); + t.sendResponseHeaders(200, derCrl.length); + try (OutputStream os = t.getResponseBody()) { + os.write(derCrl); + } + } catch (InterruptedException | CRLException exc) { + throw new IOException(exc); } }); server.setExecutor(null); diff -Nru openjdk-17-17.0.14+7/test/jdk/sun/util/resources/TimeZone/IntlTest.java openjdk-17-17.0.15+6/test/jdk/sun/util/resources/TimeZone/IntlTest.java --- openjdk-17-17.0.14+7/test/jdk/sun/util/resources/TimeZone/IntlTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/sun/util/resources/TimeZone/IntlTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * IntlTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public class IntlTest { - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected IntlTest() { - // Create a hashtable containing all the test methods. - testMethods = new Hashtable(); - Method[] methods = getClass().getDeclaredMethods(); - for( int i=0; i paths; if (contentsOnly) { - try (var pathStream = Files.walk(root, 0)) { + try (var pathStream = Files.list(root)) { paths = pathStream.collect(Collectors.toList()); } } else { @@ -664,26 +664,40 @@ assertTrue(path.toFile().exists(), String.format( "Check [%s] path exists", path)); } else { - assertFalse(path.toFile().exists(), String.format( + assertTrue(!path.toFile().exists(), String.format( "Check [%s] path doesn't exist", path)); } } - public static void assertPathNotEmptyDirectory(Path path) { - if (Files.isDirectory(path)) { + public static void assertDirectoryNotEmpty(Path path) { + assertDirectoryExists(path, Optional.of(false)); + } + + public static void assertDirectoryEmpty(Path path) { + assertDirectoryExists(path, Optional.of(true)); + } + + public static void assertDirectoryExists(Path path, Optional isEmptyCheck) { + assertPathExists(path, true); + boolean isDirectory = Files.isDirectory(path); + if (isEmptyCheck.isEmpty() || !isDirectory) { + assertTrue(isDirectory, String.format("Check [%s] is a directory", path)); + } else { ThrowingRunnable.toRunnable(() -> { try (var files = Files.list(path)) { - TKit.assertFalse(files.findFirst().isEmpty(), String.format - ("Check [%s] is not an empty directory", path)); + boolean actualIsEmpty = files.findFirst().isEmpty(); + if (isEmptyCheck.get()) { + TKit.assertTrue(actualIsEmpty, String.format("Check [%s] is not an empty directory", path)); + } else { + TKit.assertTrue(!actualIsEmpty, String.format("Check [%s] is an empty directory", path)); + } } }).run(); - } + } } public static void assertDirectoryExists(Path path) { - assertPathExists(path, true); - assertTrue(path.toFile().isDirectory(), String.format( - "Check [%s] is a directory", path)); + assertDirectoryExists(path, Optional.empty()); } public static void assertFileExists(Path path) { diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java 2025-04-09 19:45:33.000000000 +0000 @@ -392,6 +392,9 @@ } private static Object fromString(String value, Class toType) { + if (toType.isEnum()) { + return Enum.valueOf(toType, value); + } Function converter = conv.get(toType); if (converter == null) { throw new RuntimeException(String.format( diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java 2025-04-09 19:45:33.000000000 +0000 @@ -61,6 +61,22 @@ return Path.of(cmd.getArgumentValue("--install-dir", cmd::name)); } + // Tests have problems on windows where path in the temp dir are too long + // for the wix tools. We can't use a tempDir outside the TKit's WorkDir, so + // we minimize both the tempRoot directory name (above) and the tempDir name + // (below) to the extension part (which is necessary to differenciate between + // the multiple PackageTypes that will be run for one JPackageCommand). + // It might be beter if the whole work dir name was shortened from: + // jtreg_open_test_jdk_tools_jpackage_share_jdk_jpackage_tests_BasicTest_java. + public static Path getTempDirectory(JPackageCommand cmd, Path tempRoot) { + String ext = cmd.outputBundle().getFileName().toString(); + int i = ext.lastIndexOf("."); + if (i > 0 && i < (ext.length() - 1)) { + ext = ext.substring(i+1); + } + return tempRoot.resolve(ext); + } + private static void runMsiexecWithRetries(Executor misexec) { Executor.Result result = null; for (int attempt = 0; attempt < 8; ++attempt) { @@ -132,7 +148,9 @@ BiConsumer installExe = (cmd, install) -> { cmd.verifyIsOfType(PackageType.WIN_EXE); Executor exec = new Executor().setExecutable(cmd.outputBundle()); - if (!install) { + if (install) { + exec.addArgument("/qn").addArgument("/norestart"); + } else { exec.addArgument("uninstall"); } runMsiexecWithRetries(exec); @@ -257,7 +275,7 @@ Path shortcutPath = shortcutsRoot.resolve(startMenuShortcutPath); verifyShortcut(shortcutPath, exists); if (!exists) { - TKit.assertPathNotEmptyDirectory(shortcutPath.getParent()); + TKit.assertDirectoryNotEmpty(shortcutPath.getParent()); } } diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderBase.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderBase.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderBase.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderBase.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import jdk.jpackage.test.TKit; - -public class EmptyFolderBase { - - // Note: To specify file use ".txt" extension. - // Note: createDirStrcture() will call mkdir() or createNewFile() for paths defined - // in dirStruct, so make sure paths are defined in order. - - // folder-empty - // folder-not-empty - // folder-not-empty/folder-empty - // folder-not-empty/another-folder-empty - // folder-not-empty/folder-non-empty2 - // folder-not-empty/folder-non-empty2/file.txt - private static final String [] DIR_STRUCT = { - "folder-empty", - "folder-not-empty", - "folder-not-empty" + File.separator + "folder-empty", - "folder-not-empty" + File.separator + "another-folder-empty", - "folder-not-empty" + File.separator + "folder-non-empty2", - "folder-not-empty" + File.separator + "folder-non-empty2" + File.separator + - "file.txt" - }; - - // See dirStruct - public static void createDirStrcture(Path inputPath) throws IOException { - File input = new File(inputPath.toString()); - input.mkdir(); - - for (String p : DIR_STRUCT) { - File f = new File(input, p); - if (p.endsWith(".txt")) { - f.createNewFile(); - } else { - f.mkdir(); - } - } - } - - public static void validateDirStrcture(Path appDirPath) { - for (String p : DIR_STRUCT) { - Path path = appDirPath.resolve(p); - TKit.assertPathExists(path, true); - } - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.nio.file.Path; -import jdk.jpackage.internal.ApplicationLayout; -import jdk.jpackage.test.PackageTest; -import jdk.jpackage.test.PackageType; -import jdk.jpackage.test.Annotations.Test; - -/** - * Tests generation of packages with input folder containing empty folders. - */ - -/* - * @test - * @summary jpackage with input containing empty folders - * @library ../helpers - * @library /test/lib - * @key jpackagePlatformPackage - * @build EmptyFolderBase - * @build jdk.jpackage.test.* - * @build EmptyFolderPackageTest - * @modules jdk.jpackage/jdk.jpackage.internal - * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=EmptyFolderPackageTest - */ -public class EmptyFolderPackageTest { - - @Test - public static void test() throws Exception { - new PackageTest().configureHelloApp() - .addInitializer(cmd -> { - Path input = cmd.inputDir(); - EmptyFolderBase.createDirStrcture(input); - }) - .addInstallVerifier(cmd -> { - if (cmd.packageType() == PackageType.WIN_MSI) { - if (cmd.isPackageUnpacked("Not running file " - + "structure check for empty folders")) { - return; - } - } - - ApplicationLayout appLayout = cmd.appLayout(); - Path appDir = appLayout.appDirectory(); - EmptyFolderBase.validateDirStrcture(appDir); - }) - .run(); - } -} diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderTest.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderTest.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/EmptyFolderTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/EmptyFolderTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,44 +21,113 @@ * questions. */ +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; -import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.internal.ApplicationLayout; +import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.PackageType; +import jdk.jpackage.test.TKit; /** - * Tests generation of app image with input folder containing empty folders. + * Tests generation of packages and app image with input folder containing empty folders. + */ + +/* + * @test + * @summary jpackage for package with input containing empty folders + * @library ../helpers + * @library /test/lib + * @key jpackagePlatformPackage + * @build jdk.jpackage.test.* + * @build EmptyFolderTest + * @modules jdk.jpackage/jdk.jpackage.internal + * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main + * --jpt-run=EmptyFolderTest.testPackage */ /* * @test - * @summary jpackage with input containing empty folders + * @summary jpackage for app image with input containing empty folders * @library ../helpers * @library /test/lib - * @build EmptyFolderBase * @build jdk.jpackage.test.* * @build EmptyFolderTest * @modules jdk.jpackage/jdk.jpackage.internal * @run main/othervm -Xmx512m jdk.jpackage.test.Main - * --jpt-run=EmptyFolderTest + * --jpt-run=EmptyFolderTest.testAppImage */ + public class EmptyFolderTest { @Test - public static void test() throws Exception { - JPackageCommand cmd = JPackageCommand.helloAppImage(); + public static void testPackage() { + new PackageTest() + .configureHelloApp() + .addInitializer(EmptyFolderTest::createDirTree) + .addInitializer(cmd -> { + cmd.setArgumentValue("--name", "EmptyFolderPackageTest"); + }) + .addInstallVerifier(EmptyFolderTest::validateDirTree) + .run(); + } + + @Test + public static void testAppImage() throws IOException { + var cmd = JPackageCommand.helloAppImage(); // Add more files into input folder - Path input = cmd.inputDir(); - EmptyFolderBase.createDirStrcture(input); + createDirTree(cmd); // Create app image cmd.executeAndAssertHelloAppImageCreated(); - // Verify directory strcture - ApplicationLayout appLayout = cmd.appLayout(); - Path appDir = appLayout.appDirectory(); - EmptyFolderBase.validateDirStrcture(appDir); + // Verify directory structure + validateDirTree(cmd); + } + + private static void createDirTree(JPackageCommand cmd) throws IOException { + var baseDir = cmd.inputDir(); + for (var path : DIR_STRUCT) { + path = baseDir.resolve(path); + if (isFile(path)) { + Files.createDirectories(path.getParent()); + Files.write(path, new byte[0]); + } else { + Files.createDirectories(path); + } + } + } + + private static void validateDirTree(JPackageCommand cmd) { + var outputBaseDir = cmd.appLayout().appDirectory(); + var inputBaseDir = cmd.inputDir(); + for (var path : DIR_STRUCT) { + Path outputPath = outputBaseDir.resolve(path); + if (isFile(outputPath)) { + TKit.assertFileExists(outputPath); + } else if (!PackageType.WINDOWS.contains(cmd.packageType())) { + TKit.assertDirectoryExists(outputPath); + } else if (inputBaseDir.resolve(path).toFile().list().length == 0) { + // MSI packages don't support empty folders + TKit.assertPathExists(outputPath, false); + } else { + TKit.assertDirectoryNotEmpty(outputPath); + } + } + } + + private static boolean isFile(Path path) { + return path.getFileName().toString().endsWith(".txt"); } + // Note: To specify file use ".txt" extension. + private static final Path [] DIR_STRUCT = { + Path.of("folder-empty"), + Path.of("folder-not-empty"), + Path.of("folder-not-empty", "folder-empty"), + Path.of("folder-not-empty", "another-folder-empty"), + Path.of("folder-not-empty", "folder-non-empty2", "file.txt") + }; } diff -Nru openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java --- openjdk-17-17.0.14+7/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.util.ArrayList; import java.util.function.Function; import java.util.function.Predicate; -import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Stream; import jdk.jpackage.test.TKit; @@ -43,6 +42,8 @@ import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.Annotations.Parameter; +import static jdk.jpackage.test.WindowsHelper.getTempDirectory; + /* * @test * @summary jpackage basic testing @@ -263,64 +264,64 @@ cmd.executeAndAssertHelloAppImageCreated(); } + public static enum TestTempType { + TEMPDIR_EMPTY, + TEMPDIR_NOT_EMPTY, + TEMPDIR_NOT_EXIST, + } + /** * Test --temp option. Doesn't make much sense for app image as temporary * directory is used only on Windows. Test it in packaging mode. - * @throws IOException */ @Test - @Parameter("true") - @Parameter("false") - public void testTemp(boolean withExistingTempDir) throws IOException { + @Parameter("TEMPDIR_EMPTY") + @Parameter("TEMPDIR_NOT_EMPTY") + @Parameter("TEMPDIR_NOT_EXIST") + public void testTemp(TestTempType type) throws IOException { final Path tempRoot = TKit.createTempDirectory("tmp"); - // This Test has problems on windows where path in the temp dir are too long - // for the wix tools. We can't use a tempDir outside the TKit's WorkDir, so - // we minimize both the tempRoot directory name (above) and the tempDir name - // (below) to the extension part (which is necessary to differenciate between - // the multiple PackageTypes that will be run for one JPackageCommand). - // It might be beter if the whole work dir name was shortened from: - // jtreg_open_test_jdk_tools_jpackage_share_jdk_jpackage_tests_BasicTest_java. - Function getTempDir = cmd -> { - String ext = cmd.outputBundle().getFileName().toString(); - int i = ext.lastIndexOf("."); - if (i > 0 && i < (ext.length() - 1)) { - ext = ext.substring(i+1); - } - return tempRoot.resolve(ext); - }; - Supplier createTest = () -> { - return new PackageTest() - .configureHelloApp() - // Force save of package bundle in test work directory. - .addInitializer(JPackageCommand::setDefaultInputOutput) - .addInitializer(cmd -> { - Path tempDir = getTempDir.apply(cmd); - if (withExistingTempDir) { - Files.createDirectories(tempDir); - } else { - Files.createDirectories(tempDir.getParent()); + var pkgTest = new PackageTest() + .configureHelloApp() + // Force save of package bundle in test work directory. + .addInitializer(JPackageCommand::setDefaultInputOutput) + .addInitializer(cmd -> { + Path tempDir = getTempDirectory(cmd, tempRoot); + switch (type) { + case TEMPDIR_EMPTY -> Files.createDirectories(tempDir); + case TEMPDIR_NOT_EXIST -> Files.createDirectories(tempDir.getParent()); + case TEMPDIR_NOT_EMPTY -> { + Files.createDirectories(tempDir); + TKit.createTextFile(tempDir.resolve("foo.txt"), List.of( + "Hello Duke!")); + } } cmd.addArguments("--temp", tempDir); + } + ); + + if (TestTempType.TEMPDIR_NOT_EMPTY.equals(type)) { + pkgTest.setExpectedExitCode(1).addBundleVerifier(cmd -> { + // Check jpackage didn't use the supplied directory. + Path tempDir = getTempDirectory(cmd, tempRoot); + String[] tempDirContents = tempDir.toFile().list(); + TKit.assertStringListEquals(List.of("foo.txt"), List.of( + tempDirContents), String.format( + "Check the contents of the supplied temporary directory [%s]", + tempDir)); + TKit.assertStringListEquals(List.of("Hello Duke!"), + Files.readAllLines(tempDir.resolve(tempDirContents[0])), + "Check the contents of the file in the supplied temporary directory"); }); - }; + } else { + pkgTest.addBundleVerifier(cmd -> { + // Check jpackage used the supplied directory. + Path tempDir = getTempDirectory(cmd, tempRoot); + TKit.assertDirectoryNotEmpty(tempDir); + }); + } - createTest.get() - .addBundleVerifier(cmd -> { - // Check jpackage actually used the supplied directory. - Path tempDir = getTempDir.apply(cmd); - TKit.assertNotEquals(0, tempDir.toFile().list().length, - String.format( - "Check jpackage wrote some data in the supplied temporary directory [%s]", - tempDir)); - }) - .run(PackageTest.Action.CREATE); - - createTest.get() - // Temporary directory should not be empty, - // jpackage should exit with error. - .setExpectedExitCode(1) - .run(PackageTest.Action.CREATE); + pkgTest.run(PackageTest.Action.CREATE); } @Test diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/doclet/testCopyFiles/TestCopyFiles.java 2025-04-09 19:45:33.000000000 +0000 @@ -259,6 +259,7 @@ public void testDocFilesInPackagesSource7UsingClassPath() { javadoc("-d", "packages-out-src7-cp", "-source", "7", + "-sourcepath", testSrc("packages"), "-classpath", testSrc("packages"), "p1"); checkExit(Exit.OK); diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/lib/javadoc/tester/JavadocTester.java 2025-04-09 19:45:33.000000000 +0000 @@ -422,12 +422,14 @@ String charsetArg = null; String docencodingArg = null; String encodingArg = null; + boolean haveSourcePath = false; for (int i = 0; i < args.length - 2; i++) { switch (args[i]) { case "-d" -> outputDir = Path.of(args[++i]); case "-charset" -> charsetArg = args[++i]; case "-docencoding" -> docencodingArg = args[++i]; case "-encoding" -> encodingArg = args[++i]; + case "-sourcepath", "--source-path", "--module-source-path" -> haveSourcePath = true; } } @@ -449,6 +451,16 @@ charset = Charset.defaultCharset(); } + // explicitly set the source path if none specified + // to override the javadoc tool default to use the classpath + if (!haveSourcePath) { + var newArgs = new String[args.length + 2]; + newArgs[0] = "-sourcepath"; + newArgs[1] = testSrc; + System.arraycopy(args, 0, newArgs, 2, args.length); + args = newArgs; + } + out.println("args: " + Arrays.toString(args)); // log.setOutDir(outputDir); diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java 2025-04-09 19:45:33.000000000 +0000 @@ -22,10 +22,6 @@ */ package sampleapi; -import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.api.JavacTool; -import com.sun.tools.javac.util.Context; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -34,17 +30,22 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import static java.util.stream.Collectors.toList; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; + +import com.sun.source.util.JavacTask; +import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.api.JavacTool; +import com.sun.tools.javac.util.Context; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import sampleapi.generator.ModuleGenerator; +import sampleapi.generator.ModuleGenerator; import sampleapi.generator.PackageGenerator; public class SampleApi { diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,17 +23,23 @@ package sampleapi.generator; -import java.io.File; -import java.io.BufferedInputStream; -import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Set; + import javax.lang.model.element.Modifier; import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCIdent; +import com.sun.tools.javac.tree.JCTree.JCLiteral; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCNewArray; +import com.sun.tools.javac.tree.JCTree.JCNewClass; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; -import java.util.HashMap; -import java.util.Map; class DocCommentGenerator { diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,22 +23,25 @@ package sampleapi.generator; -import java.util.ArrayList; import java.util.Set; + import javax.lang.model.element.Modifier; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; -import com.sun.tools.javac.tree.DocCommentTable; -import com.sun.tools.javac.parser.ScannerFactory; +import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.parser.Scanner; -import com.sun.tools.javac.parser.Tokens.Token; +import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; -import com.sun.source.tree.Tree.Kind; +import com.sun.tools.javac.parser.Tokens.Token; +import com.sun.tools.javac.tree.DocCommentTable; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.util.Context; -import sampleapi.util.*; +import sampleapi.util.PoorDocCommentTable; class Documentifier { diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java 2025-04-09 19:45:33.000000000 +0000 @@ -22,31 +22,26 @@ */ package sampleapi.generator; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + import com.sun.source.tree.ModuleTree.ModuleKind; import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.parser.Scanner; -import com.sun.tools.javac.parser.ScannerFactory; -import com.sun.tools.javac.parser.Tokens; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCDirective; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.TreeMaker; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.ListBuffer; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.ArrayList; +import com.sun.tools.javac.util.Names; + import org.w3c.dom.Element; import org.w3c.dom.NodeList; import sampleapi.SampleApi; -import sampleapi.util.PoorDocCommentTable; - -import static com.sun.tools.javac.parser.Tokens.Comment.CommentStyle.JAVADOC; /** * diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java 2025-04-09 19:45:33.000000000 +0000 @@ -26,33 +26,45 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; + import javax.xml.parsers.DocumentBuilderFactory; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Name; -import com.sun.tools.javac.util.Names; -import com.sun.tools.javac.util.List; -import com.sun.tools.javac.util.ListBuffer; -import com.sun.tools.javac.tree.TreeMaker; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symtab; -import java.nio.file.Path; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCPackageDecl; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.Names; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; -import sampleapi.util.*; +import sampleapi.util.SimpleMultiplier; public class PackageGenerator { diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java --- openjdk-17-17.0.14+7/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java 2025-04-09 19:45:33.000000000 +0000 @@ -23,8 +23,8 @@ package sampleapi.util; -import java.util.StringTokenizer; import java.util.ArrayList; +import java.util.StringTokenizer; /* * The class implements unknown number of nested loops. The number of modifiers diff -Nru openjdk-17-17.0.14+7/test/langtools/jdk/jshell/ExecPtyGetFlagsToSetTest.java openjdk-17-17.0.15+6/test/langtools/jdk/jshell/ExecPtyGetFlagsToSetTest.java --- openjdk-17-17.0.14+7/test/langtools/jdk/jshell/ExecPtyGetFlagsToSetTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/jdk/jshell/ExecPtyGetFlagsToSetTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -26,7 +26,7 @@ * @bug 8224184 * @summary Control Char check for pty * @modules jdk.internal.le/jdk.internal.org.jline.terminal - * jdk.internal.le/jdk.internal.org.jline.terminal.impl + * jdk.internal.le/jdk.internal.org.jline.terminal.impl.exec * jdk.internal.le/jdk.internal.org.jline.terminal.spi * @requires (os.family == "linux") | (os.family == "aix") */ @@ -35,12 +35,13 @@ import jdk.internal.org.jline.terminal.Attributes; import jdk.internal.org.jline.terminal.Attributes.ControlChar; import jdk.internal.org.jline.terminal.Attributes.LocalFlag; -import jdk.internal.org.jline.terminal.impl.ExecPty; +import jdk.internal.org.jline.terminal.impl.exec.ExecPty; +import jdk.internal.org.jline.terminal.spi.SystemStream; import jdk.internal.org.jline.terminal.spi.TerminalProvider; public class ExecPtyGetFlagsToSetTest extends ExecPty { - public ExecPtyGetFlagsToSetTest(String name, TerminalProvider.Stream stream) { - super(name, stream); + public ExecPtyGetFlagsToSetTest(TerminalProvider provider, SystemStream stream, String name) { + super(provider, stream, name); } @Override @@ -50,7 +51,7 @@ public static void main(String[] args) { ExecPtyGetFlagsToSetTest testPty = - new ExecPtyGetFlagsToSetTest("stty", TerminalProvider.Stream.Output); + new ExecPtyGetFlagsToSetTest(null, SystemStream.Output, "stty"); Attributes attr = new Attributes(); Attributes current = new Attributes(); diff -Nru openjdk-17-17.0.14+7/test/langtools/tools/javac/newlines/NewLineTest.java openjdk-17-17.0.15+6/test/langtools/tools/javac/newlines/NewLineTest.java --- openjdk-17-17.0.14+7/test/langtools/tools/javac/newlines/NewLineTest.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/tools/javac/newlines/NewLineTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -58,8 +58,9 @@ .options("-J-Dline.separator='@'") .run(Task.Expect.FAIL); - List lines = Files.readAllLines(javacOutput.toPath(), - Charset.defaultCharset()); + String encoding = System.getProperty("native.encoding"); + Charset cs = (encoding != null) ? Charset.forName(encoding) : Charset.defaultCharset(); + List lines = Files.readAllLines(javacOutput.toPath(), cs); if (lines.size() != 1) { throw new AssertionError("The compiler output should have one line only"); } diff -Nru openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOption.java openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.java --- openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOption.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,10 +1,10 @@ /** * @test /nodynamiccopyright/ * @bug 8072480 - * @summary Verify that javac rejects Java 8 program with --release 7 + * @summary Verify that javac rejects Java 17 program with --release 11 * @compile ReleaseOption.java - * @compile/fail/ref=ReleaseOption-release7.out -XDrawDiagnostics --release 7 -Xlint:-options ReleaseOption.java + * @compile/fail/ref=ReleaseOption.out -XDrawDiagnostics --release 11 ReleaseOption.java */ -interface ReleaseOption extends java.util.stream.Stream { +interface ReleaseOption extends java.util.random.RandomGenerator { } diff -Nru openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOption.out openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.out --- openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOption.out 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOption.out 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,2 @@ +ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.random +1 error diff -Nru openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOptionThroughAPI.java openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOptionThroughAPI.java --- openjdk-17-17.0.14+7/test/langtools/tools/javac/options/release/ReleaseOptionThroughAPI.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/tools/javac/options/release/ReleaseOptionThroughAPI.java 2025-04-09 19:45:33.000000000 +0000 @@ -50,11 +50,11 @@ PrintWriter outWriter = new PrintWriter(out)) { Iterable input = fm.getJavaFileObjects(System.getProperty("test.src") + "/ReleaseOption.java"); - List options = Arrays.asList("--release", "7", "-XDrawDiagnostics", "-Xlint:-options"); + List options = Arrays.asList("--release", "11", "-XDrawDiagnostics", "-d", "."); compiler.getTask(outWriter, fm, null, options, null, input).call(); String expected = - "ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.stream" + lineSep + + "ReleaseOption.java:9:49: compiler.err.doesnt.exist: java.util.random" + lineSep + "1 error" + lineSep; if (!expected.equals(out.toString())) { throw new AssertionError("Unexpected output: " + out.toString()); diff -Nru openjdk-17-17.0.14+7/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java openjdk-17-17.0.15+6/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java --- openjdk-17-17.0.14+7/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java 2025-04-09 19:45:33.000000000 +0000 @@ -40,6 +40,8 @@ import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; @@ -137,7 +139,7 @@ */ class TestTypeScanner extends TypeScanner { Element elem; - NavigableMap toBeFound; + NavigableMap> toBeFound; int count = 0; Set seen = new HashSet<>(); @@ -145,10 +147,10 @@ super(types); this.elem = elem; - NavigableMap testByPos = new TreeMap<>(); + NavigableMap> testByPos = new TreeMap<>(); for (AnnotationMirror test : tests) { for (int pos : getPosn(test)) { - testByPos.put(pos, test); + testByPos.computeIfAbsent(pos, ArrayList::new).add(test); } } this.toBeFound = testByPos; @@ -170,17 +172,18 @@ out.println("scan " + count + ": " + t); if (toBeFound.size() > 0) { if (toBeFound.firstKey().equals(count)) { - AnnotationMirror test = toBeFound.pollFirstEntry().getValue(); - String annoType = getAnnoType(test); - AnnotationMirror anno = getAnnotation(t, annoType); - if (anno == null) { - error(elem, "annotation not found on " + count + ": " + t); - } else { - String v = getValue(anno, "value").toString(); - if (v.equals(getExpect(test))) { - out.println("found " + anno + " as expected"); + for (AnnotationMirror test : toBeFound.pollFirstEntry().getValue()) { + String annoType = getAnnoType(test); + AnnotationMirror anno = getAnnotation(t, annoType); + if (anno == null) { + error(elem, "annotation not found on " + count + ": " + t); } else { - error(elem, "Unexpected value: " + v + ", expected: " + getExpect(test)); + String v = getValue(anno, "value").toString(); + if (v.equals(getExpect(test))) { + out.println("found " + anno + " as expected"); + } else { + error(elem, "Unexpected value: " + v + ", expected: " + getExpect(test)); + } } } } else if (count > toBeFound.firstKey()) { @@ -405,6 +408,12 @@ int value(); } + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + public @interface TD { + int value(); + } + // Test cases // TODO: add more cases for arrays @@ -527,6 +536,10 @@ @Test(posn=1, annoType=TA.class, expect="23") public Set<@TA(23) ? super Object> f9; + @Test(posn=0, annoType=TA.class, expect="1") + @Test(posn=0, annoType=TD.class, expect="2") + public @TA(1) @TD(2) int f10; + // Test type use annotations on uses of type variables @Test(posn=5, annoType = TA.class, expect = "25") @Test(posn=5, annoType = TB.class, expect = "26") diff -Nru openjdk-17-17.0.14+7/test/lib/jdk/test/lib/Platform.java openjdk-17-17.0.15+6/test/lib/jdk/test/lib/Platform.java --- openjdk-17-17.0.14+7/test/lib/jdk/test/lib/Platform.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/lib/jdk/test/lib/Platform.java 2025-04-09 19:45:33.000000000 +0000 @@ -35,6 +35,7 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static java.util.Locale.ROOT; public class Platform { public static final String vmName = privilegedGetProperty("java.vm.name"); @@ -134,7 +135,7 @@ } private static boolean isOs(String osname) { - return osName.toLowerCase().startsWith(osname.toLowerCase()); + return osName.toLowerCase(ROOT).startsWith(osname.toLowerCase(ROOT)); } public static String getOsName() { @@ -175,15 +176,15 @@ } public static boolean isDebugBuild() { - return (jdkDebug.toLowerCase().contains("debug")); + return (jdkDebug.toLowerCase(ROOT).contains("debug")); } public static boolean isSlowDebugBuild() { - return (jdkDebug.toLowerCase().equals("slowdebug")); + return (jdkDebug.toLowerCase(ROOT).equals("slowdebug")); } public static boolean isFastDebugBuild() { - return (jdkDebug.toLowerCase().equals("fastdebug")); + return (jdkDebug.toLowerCase(ROOT).equals("fastdebug")); } public static String getVMVersion() { @@ -346,8 +347,8 @@ } public static boolean isOracleLinux7() { - if (System.getProperty("os.name").toLowerCase().contains("linux") && - System.getProperty("os.version").toLowerCase().contains("el")) { + if (System.getProperty("os.name").toLowerCase(ROOT).contains("linux") && + System.getProperty("os.version").toLowerCase(ROOT).contains("el")) { Pattern p = Pattern.compile("el(\\d+)"); Matcher m = p.matcher(System.getProperty("os.version")); if (m.find()) { diff -Nru openjdk-17-17.0.14+7/test/lib/jdk/test/lib/SecurityTools.java openjdk-17-17.0.15+6/test/lib/jdk/test/lib/SecurityTools.java --- openjdk-17-17.0.14+7/test/lib/jdk/test/lib/SecurityTools.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/lib/jdk/test/lib/SecurityTools.java 2025-04-09 19:45:33.000000000 +0000 @@ -40,9 +40,8 @@ /** * Run security tools (including jarsigner and keytool) in a new process. * The en_US locale is always used so a test can always match output to - * English text. {@code /dev/urandom} is used as entropy source so tool will - * not block because of entropy scarcity. {@code -Jvm-options} is supported - * as an argument. + * English text. An argument can be a normal string, + * {@code -Jvm-options}, {@code $sysProp} or {@code -J$sysProp}. */ public class SecurityTools { @@ -58,15 +57,19 @@ JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK(tool) .addVMArg("-Duser.language=en") .addVMArg("-Duser.country=US"); - if (!Platform.isWindows()) { - launcher.addVMArg("-Djava.security.egd=file:/dev/./urandom"); - } for (String arg : args) { if (arg.startsWith("-J")) { - launcher.addVMArg(arg.substring(2)); + String jarg = arg.substring(2); + if (jarg.length() > 1 && jarg.charAt(0) == '$') { + launcher.addVMArg(System.getProperty(jarg.substring(1))); + } else { + launcher.addVMArg(jarg); + } } else if (Platform.isWindows() && arg.isEmpty()) { // JDK-6518827: special handling for empty argument on Windows launcher.addToolArg("\"\""); + } else if (arg.length() > 1 && arg.charAt(0) == '$') { + launcher.addToolArg(System.getProperty(arg.substring(1))); } else { launcher.addToolArg(arg); } diff -Nru openjdk-17-17.0.14+7/test/lib/jdk/test/lib/util/ForceGC.java openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/ForceGC.java --- openjdk-17-17.0.14+7/test/lib/jdk/test/lib/util/ForceGC.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/ForceGC.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,29 +78,30 @@ ReferenceQueue queue = new ReferenceQueue<>(); Object obj = new Object(); PhantomReference ref = new PhantomReference<>(obj, queue); - obj = null; - Reference.reachabilityFence(obj); - Reference.reachabilityFence(ref); - - int retries = (int)(timeout / 200); - for (; retries >= 0; retries--) { - if (booleanSupplier.getAsBoolean()) { - return true; - } - - System.gc(); + try { + obj = null; - try { - // The remove() will always block for the specified milliseconds - // if the reference has already been removed from the queue. - // But it is fine. For most cases, the 1st GC is sufficient - // to trigger and complete the cleanup. - queue.remove(200L); - } catch (InterruptedException ie) { - // ignore, the loop will try again + int retries = (int) (timeout / 200); + for (; retries >= 0; retries--) { + if (booleanSupplier.getAsBoolean()) { + return true; + } + + System.gc(); + + try { + // The remove() will always block for the specified milliseconds + // if the reference has already been removed from the queue. + // But it is fine. For most cases, the 1st GC is sufficient + // to trigger and complete the cleanup. + queue.remove(200L); + } catch (InterruptedException ie) { + // ignore, the loop will try again + } } + } finally { + Reference.reachabilityFence(ref); } - return booleanSupplier.getAsBoolean(); } } diff -Nru openjdk-17-17.0.14+7/test/lib/jdk/test/lib/util/JarUtils.java openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/JarUtils.java --- openjdk-17-17.0.14+7/test/lib/jdk/test/lib/util/JarUtils.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/lib/jdk/test/lib/util/JarUtils.java 2025-04-09 19:45:33.000000000 +0000 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -320,6 +320,57 @@ updateJar(src, dest, Map.of(JarFile.MANIFEST_NAME, bout.toByteArray())); } + /** + * Remove entries from a ZIP file. + * + * Each entry can be a name or a name ending with "*". + * + * @return number of removed entries + * @throws IOException if there is any I/O error + */ + public static int deleteEntries(Path jarfile, String... patterns) + throws IOException { + Path tmpfile = Files.createTempFile("jar", "jar"); + int count = 0; + + try (OutputStream out = Files.newOutputStream(tmpfile); + JarOutputStream jos = new JarOutputStream(out)) { + try (JarFile jf = new JarFile(jarfile.toString())) { + Enumeration jentries = jf.entries(); + top: while (jentries.hasMoreElements()) { + JarEntry jentry = jentries.nextElement(); + String name = jentry.getName(); + for (String pattern : patterns) { + if (pattern.endsWith("*")) { + if (name.startsWith(pattern.substring( + 0, pattern.length() - 1))) { + // Go directly to next entry. This + // one is not written into `jos` and + // therefore removed. + count++; + continue top; + } + } else { + if (name.equals(pattern)) { + // Same as above + count++; + continue top; + } + } + } + // No pattern matched, file retained + jos.putNextEntry(copyEntry(jentry)); + jf.getInputStream(jentry).transferTo(jos); + } + } + } + + // replace the original JAR file + Files.move(tmpfile, jarfile, StandardCopyOption.REPLACE_EXISTING); + + return count; + } + private static void updateEntry(JarOutputStream jos, String name, Object content) throws IOException { if (content instanceof Boolean) { diff -Nru openjdk-17-17.0.14+7/test/lib-test/jdk/test/lib/util/JarUtilsTest.java openjdk-17-17.0.15+6/test/lib-test/jdk/test/lib/util/JarUtilsTest.java --- openjdk-17-17.0.14+7/test/lib-test/jdk/test/lib/util/JarUtilsTest.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/lib-test/jdk/test/lib/util/JarUtilsTest.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 8309841 + * @summary Unit Test for a common Test API in jdk.test.lib.util.JarUtils + * @library /test/lib + */ + +import jdk.test.lib.Asserts; +import jdk.test.lib.util.JarUtils; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Set; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.stream.Collectors; + +public class JarUtilsTest { + public static void main(String[] args) throws Exception { + Files.createDirectory(Path.of("bx")); + JarUtils.createJarFile(Path.of("a.jar"), + Path.of("."), + Files.writeString(Path.of("a"), ""), + Files.writeString(Path.of("b1"), ""), + Files.writeString(Path.of("b2"), ""), + Files.writeString(Path.of("bx/x"), ""), + Files.writeString(Path.of("c"), ""), + Files.writeString(Path.of("e1"), ""), + Files.writeString(Path.of("e2"), "")); + checkContent("a", "b1", "b2", "bx/x", "c", "e1", "e2"); + + JarUtils.deleteEntries(Path.of("a.jar"), "a"); + checkContent("b1", "b2", "bx/x", "c", "e1", "e2"); + + // Note: b* covers everything starting with b, even bx/x + JarUtils.deleteEntries(Path.of("a.jar"), "b*"); + checkContent("c", "e1", "e2"); + + // d* does not match + JarUtils.deleteEntries(Path.of("a.jar"), "d*"); + checkContent("c", "e1", "e2"); + + // multiple patterns + JarUtils.deleteEntries(Path.of("a.jar"), "d*", "e*"); + checkContent("c"); + } + + static void checkContent(String... expected) throws IOException { + try (var jf = new JarFile("a.jar")) { + Asserts.assertEquals(Set.of(expected), + jf.stream().map(JarEntry::getName).collect(Collectors.toSet())); + } + } +} diff -Nru openjdk-17-17.0.14+7/test/micro/org/openjdk/bench/java/security/Signatures.java openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/security/Signatures.java --- openjdk-17-17.0.14+7/test/micro/org/openjdk/bench/java/security/Signatures.java 1970-01-01 00:00:00.000000000 +0000 +++ openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/security/Signatures.java 2025-04-09 19:45:33.000000000 +0000 @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.java.security; + +import org.openjdk.jmh.annotations.*; + +import java.security.*; +import java.security.spec.*; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.SECONDS) +@State(Scope.Thread) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(jvmArgsAppend = {"-Xms1024m", "-Xmx1024m", "-Xmn768m", "-XX:+UseParallelGC"}, value = 3) +public class Signatures { + private static Signature signer; + + @Param({"64", "512", "2048", "16384"}) + private static int messageLength; + + @Param({"secp256r1", "secp384r1", "secp521r1"}) + private String algorithm; + + private static byte[] message; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + String signName = switch (algorithm) { + case "secp256r1" -> "SHA256withECDSA"; + case "secp384r1" -> "SHA384withECDSA"; + case "secp521r1" -> "SHA512withECDSA"; + default -> throw new RuntimeException(); + }; + + AlgorithmParameters params = + AlgorithmParameters.getInstance("EC", "SunEC"); + params.init(new ECGenParameterSpec(algorithm)); + ECGenParameterSpec ecParams = + params.getParameterSpec(ECGenParameterSpec.class); + + KeyPairGenerator kpg = + KeyPairGenerator.getInstance("EC", "SunEC"); + kpg.initialize(ecParams); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(signName, "SunEC"); + signer.initSign(kp.getPrivate()); + } + + @Benchmark + public byte[] sign() throws SignatureException { + signer.update(message); + return signer.sign(); + } + + public static class EdDSA extends Signatures { + @Param({"Ed25519", "Ed448"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + KeyPairGenerator kpg = + KeyPairGenerator.getInstance(algorithm, "SunEC"); + NamedParameterSpec spec = new NamedParameterSpec(algorithm); + kpg.initialize(spec); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm, "SunEC"); + signer.initSign(kp.getPrivate()); + } + } + + public static class DSA extends Signatures { + @Param({"SHA256withDSA", "SHA384withDSA", "SHA512withDSA"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256withDSA" -> 2048; + case "SHA384withDSA" -> 3072; + case "SHA512withDSA" -> 3072; + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm); + signer.initSign(kp.getPrivate()); + } + } + + public static class RSA extends Signatures { + @Param({"SHA256withRSA", "SHA384withRSA", "SHA512withRSA"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256withRSA" -> 2048; + case "SHA384withRSA" -> 3072; + case "SHA512withRSA" -> 4096; + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm); + signer.initSign(kp.getPrivate()); + } + } + + public static class RSASSAPSS extends Signatures { + @Param({"SHA256", "SHA384", "SHA512"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256" -> 2048; + case "SHA384" -> 3072; + case "SHA512" -> 4096; + default -> throw new RuntimeException(); + }; + + PSSParameterSpec spec = switch (algorithm) { + case "SHA256" -> + new PSSParameterSpec( + "SHA-256", "MGF1", + MGF1ParameterSpec.SHA256, + 32, PSSParameterSpec.TRAILER_FIELD_BC); + case "SHA384" -> + new PSSParameterSpec( + "SHA-384", "MGF1", + MGF1ParameterSpec.SHA384, + 48, PSSParameterSpec.TRAILER_FIELD_BC); + case "SHA512" -> + new PSSParameterSpec( + "SHA-512", "MGF1", + MGF1ParameterSpec.SHA512, + 64, PSSParameterSpec.TRAILER_FIELD_BC); + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSASSA-PSS"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance("RSASSA-PSS"); + signer.setParameter(spec); + signer.initSign(kp.getPrivate()); + } + } +} + diff -Nru openjdk-17-17.0.14+7/test/micro/org/openjdk/bench/java/util/Base64Decode.java openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/util/Base64Decode.java --- openjdk-17-17.0.14+7/test/micro/org/openjdk/bench/java/util/Base64Decode.java 2025-01-04 20:25:18.000000000 +0000 +++ openjdk-17-17.0.15+6/test/micro/org/openjdk/bench/java/util/Base64Decode.java 2025-04-09 19:45:33.000000000 +0000 @@ -47,7 +47,7 @@ "112", "512", "1000", "20000", "50000"}) private int maxNumBytes; - @Param({"4"}) + @Param({"4", "32", "76", "128"}) private int lineSize; private byte[] lineSeparator = {'\r', '\n'};