diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000000..d3f63784ecec --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,5 @@ + + + +--------- +- [ ] I confirm that I make this contribution in accordance with the [OpenJDK Interim AI Policy](https://openjdk.org/legal/ai). diff --git a/.jcheck/conf b/.jcheck/conf index 8bd21f7117b3..fd9a62ff0a58 100644 --- a/.jcheck/conf +++ b/.jcheck/conf @@ -1,7 +1,7 @@ [general] project=jdk-updates jbs=JDK -version=21.0.11 +version=21.0.12 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists diff --git a/make/Global.gmk b/make/Global.gmk index e5e76b475b94..fae21f0b4280 100644 --- a/make/Global.gmk +++ b/make/Global.gmk @@ -103,6 +103,7 @@ help: $(info $(_) # method is 'auto', 'ignore' or 'fail' (default)) $(info $(_) TEST="test1 ..." # Use the given test descriptor(s) for testing, e.g.) $(info $(_) # make test TEST="jdk_lang gtest:all") + $(info $(_) TEST_DEPS="dependency1 ..." # Specify additional dependencies for running tests, e.g docs-jdk) $(info $(_) JTREG="OPT1=x;OPT2=y" # Control the JTREG test harness, use 'help' to list) $(info $(_) GTEST="OPT1=x;OPT2=y" # Control the GTEST test harness, use 'help' to list) $(info $(_) MICRO="OPT1=x;OPT2=y" # Control the MICRO test harness, use 'help' to list) diff --git a/make/InitSupport.gmk b/make/InitSupport.gmk index 31c80e2f7267..e38f9e105475 100644 --- a/make/InitSupport.gmk +++ b/make/InitSupport.gmk @@ -50,7 +50,7 @@ ifeq ($(HAS_SPEC),) # Make control variables, handled by Init.gmk INIT_CONTROL_VARIABLES += LOG CONF CONF_NAME SPEC JOBS TEST_JOBS CONF_CHECK \ - COMPARE_BUILD JTREG GTEST MICRO TEST_OPTS TEST_VM_OPTS + COMPARE_BUILD JTREG GTEST MICRO TEST_OPTS TEST_VM_OPTS TEST_DEPS # All known make control variables MAKE_CONTROL_VARIABLES := $(INIT_CONTROL_VARIABLES) TEST JDK_FILTER SPEC_FILTER diff --git a/make/Main.gmk b/make/Main.gmk index dd2a8e42f281..f470feb6bfef 100644 --- a/make/Main.gmk +++ b/make/Main.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2011, 2023, 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 @@ -774,13 +774,13 @@ $(eval $(call SetupTarget, build-microbenchmark, \ $(eval $(call SetupTarget, test, \ MAKEFILE := RunTests, \ ARGS := TEST="$(TEST)", \ - DEPS := jdk-image test-image, \ + DEPS := jdk-image test-image $(TEST_DEPS), \ )) $(eval $(call SetupTarget, exploded-test, \ MAKEFILE := RunTests, \ ARGS := TEST="$(TEST)" JDK_IMAGE_DIR=$(JDK_OUTPUTDIR), \ - DEPS := exploded-image test-image, \ + DEPS := exploded-image test-image $(TEST_DEPS), \ )) ifeq ($(JCOV_ENABLED), true) @@ -1061,8 +1061,8 @@ else test-make-compile-commands: compile-commands # Declare dependency for all generated test targets - $(foreach t, $(filter-out test-make%, $(ALL_TEST_TARGETS)), $(eval $t: jdk-image test-image)) - $(foreach t, $(ALL_EXPLODED_TEST_TARGETS), $(eval $t: exploded-image test-image)) + $(foreach t, $(filter-out test-make%, $(ALL_TEST_TARGETS)), $(eval $t: jdk-image test-image $(TEST_DEPS))) + $(foreach t, $(ALL_EXPLODED_TEST_TARGETS), $(eval $t: exploded-image test-image $(TEST_DEPS))) interim-image: $(INTERIM_JMOD_TARGETS) @@ -1293,9 +1293,13 @@ test-hotspot-jtreg-native: test-hotspot_native_sanity test-hotspot-gtest: exploded-test-gtest test-jdk-jtreg-native: test-jdk_native_sanity +# Set dependencies for doc tests +$(eval $(call AddTestDependency, docs_all, docs-jdk)) +test-docs: test-docs_all + ALL_TARGETS += $(RUN_TEST_TARGETS) run-test exploded-run-test check \ test-hotspot-jtreg test-hotspot-jtreg-native test-hotspot-gtest \ - test-jdk-jtreg-native + test-jdk-jtreg-native test-docs ################################################################################ ################################################################################ diff --git a/make/MainSupport.gmk b/make/MainSupport.gmk index 34137c502d4a..aa0bf8f8ac8f 100644 --- a/make/MainSupport.gmk +++ b/make/MainSupport.gmk @@ -132,6 +132,15 @@ define CleanModule $(call Clean-include, $1) endef +define AddTestDependency + test-$(strip $1): $2 + + exploded-test-$(strip $1): $2 + + ifneq ($(filter $(TEST), $1), ) + TEST_DEPS += $2 + endif +endef ################################################################################ diff --git a/make/RunTests.gmk b/make/RunTests.gmk index b490f9f77489..f61125f53315 100644 --- a/make/RunTests.gmk +++ b/make/RunTests.gmk @@ -263,6 +263,7 @@ jaxp_JTREG_PROBLEM_LIST += $(TOPDIR)/test/jaxp/ProblemList.txt langtools_JTREG_PROBLEM_LIST += $(TOPDIR)/test/langtools/ProblemList.txt hotspot_JTREG_PROBLEM_LIST += $(TOPDIR)/test/hotspot/jtreg/ProblemList.txt lib-test_JTREG_PROBLEM_LIST += $(TOPDIR)/test/lib-test/ProblemList.txt +docs_JTREG_PROBLEM_LIST += $(TOPDIR)/test/docs/ProblemList.txt ################################################################################ # Parse test selection @@ -866,6 +867,8 @@ define SetupRunJtregTestBody $1_JTREG_BASIC_OPTIONS += -e:TEST_IMAGE_DIR=$(TEST_IMAGE_DIR) + $1_JTREG_BASIC_OPTIONS += -e:DOCS_JDK_IMAGE_DIR=$$(DOCS_JDK_IMAGE_DIR) + ifneq ($$(JTREG_FAILURE_HANDLER_OPTIONS), ) $1_JTREG_LAUNCHER_OPTIONS += -Djava.library.path="$(JTREG_FAILURE_HANDLER_DIR)" endif diff --git a/make/autoconf/toolchain.m4 b/make/autoconf/toolchain.m4 index 069ced05f329..a2b576ac1ab3 100644 --- a/make/autoconf/toolchain.m4 +++ b/make/autoconf/toolchain.m4 @@ -380,7 +380,7 @@ AC_DEFUN_ONCE([TOOLCHAIN_POST_DETECTION], [ # Restore old path, except for the microsoft toolchain, which requires the # toolchain path to remain in place. Otherwise the compiler will not work in - # some siutations in later configure checks. + # some situations in later configure checks. if test "x$TOOLCHAIN_TYPE" != "xmicrosoft"; then PATH="$OLD_PATH" fi @@ -389,10 +389,6 @@ AC_DEFUN_ONCE([TOOLCHAIN_POST_DETECTION], # This is necessary since AC_PROG_CC defaults CFLAGS to "-g -O2" CFLAGS="$ORG_CFLAGS" CXXFLAGS="$ORG_CXXFLAGS" - - # filter out some unwanted additions autoconf may add to CXX; we saw this on macOS with autoconf 2.72 - UTIL_GET_NON_MATCHING_VALUES(cxx_filtered, $CXX, -std=c++11 -std=gnu++11) - CXX="$cxx_filtered" ]) # Check if a compiler is of the toolchain type we expect, and save the version diff --git a/make/autoconf/util.m4 b/make/autoconf/util.m4 index 76426005f81d..c87411c8ab3f 100644 --- a/make/autoconf/util.m4 +++ b/make/autoconf/util.m4 @@ -26,6 +26,70 @@ m4_include([util_paths.m4]) ############################################################################### +# Overwrite the existing version of AC_PROG_CC with our own custom variant. +# Unlike the regular AC_PROG_CC, the compiler list must always be passed. +AC_DEFUN([AC_PROG_CC], +[ + AC_LANG_PUSH(C) + AC_ARG_VAR([CC], [C compiler command]) + AC_ARG_VAR([CFLAGS], [C compiler flags]) + + _AC_ARG_VAR_LDFLAGS() + _AC_ARG_VAR_LIBS() + _AC_ARG_VAR_CPPFLAGS() + + AC_CHECK_TOOLS(CC, [$1]) + + test -z "$CC" && AC_MSG_FAILURE([no acceptable C compiler found in \$PATH]) + + # Provide some information about the compiler. + _AS_ECHO_LOG([checking for _AC_LANG compiler version]) + set X $ac_compile + ac_compiler=$[2] + for ac_option in --version -v -V -qversion -version; do + _AC_DO_LIMIT([$ac_compiler $ac_option >&AS_MESSAGE_LOG_FD]) + done + + m4_expand_once([_AC_COMPILER_EXEEXT]) + m4_expand_once([_AC_COMPILER_OBJEXT]) + + _AC_PROG_CC_G + + AC_LANG_POP(C) +]) + +############################################################################### +# Overwrite the existing version of AC_PROG_CXX with our own custom variant. +# Unlike the regular AC_PROG_CXX, the compiler list must always be passed. +AC_DEFUN([AC_PROG_CXX], +[ + AC_LANG_PUSH(C++) + AC_ARG_VAR([CXX], [C++ compiler command]) + AC_ARG_VAR([CXXFLAGS], [C++ compiler flags]) + + _AC_ARG_VAR_LDFLAGS() + _AC_ARG_VAR_LIBS() + _AC_ARG_VAR_CPPFLAGS() + + AC_CHECK_TOOLS(CXX, [$1]) + + # Provide some information about the compiler. + _AS_ECHO_LOG([checking for _AC_LANG compiler version]) + set X $ac_compile + ac_compiler=$[2] + for ac_option in --version -v -V -qversion; do + _AC_DO_LIMIT([$ac_compiler $ac_option >&AS_MESSAGE_LOG_FD]) + done + + m4_expand_once([_AC_COMPILER_EXEEXT]) + m4_expand_once([_AC_COMPILER_OBJEXT]) + + _AC_PROG_CXX_G + + AC_LANG_POP(C++) +]) + +################################################################################ # Create a function/macro that takes a series of named arguments. The call is # similar to AC_DEFUN, but the setup of the function looks like this: # UTIL_DEFUN_NAMED([MYFUNC], [FOO *BAR], [$@], [ diff --git a/make/common/FindTests.gmk b/make/common/FindTests.gmk index b12630349c0d..5bdce82efa3c 100644 --- a/make/common/FindTests.gmk +++ b/make/common/FindTests.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2017, 2019, 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 @@ -43,7 +43,7 @@ $(eval $(call IncludeCustomExtension, common/FindTests.gmk)) TEST_BASEDIRS += $(TOPDIR)/test $(TOPDIR) # JTREG_TESTROOTS might have been set by a custom extension -JTREG_TESTROOTS += $(addprefix $(TOPDIR)/test/, hotspot/jtreg jdk langtools jaxp lib-test) +JTREG_TESTROOTS += $(addprefix $(TOPDIR)/test/, hotspot/jtreg jdk langtools jaxp lib-test docs) # Extract the names of the Jtreg group files from the TEST.ROOT files. The # TEST.ROOT files being properties files can be interpreted as makefiles so diff --git a/make/conf/jib-profiles.js b/make/conf/jib-profiles.js index 62559c10c8b1..1aa445d88e9b 100644 --- a/make/conf/jib-profiles.js +++ b/make/conf/jib-profiles.js @@ -952,7 +952,7 @@ var getJibProfilesProfiles = function (input, common, data) { // Profiles used to run tests using Jib for internal dependencies. var testedProfile = input.testedProfile; - if (testedProfile == null) { + if (testedProfile == null || testedProfile == "docs") { testedProfile = input.build_os + "-" + input.build_cpu; } var testedProfileJdk = testedProfile + ".jdk"; @@ -994,25 +994,38 @@ var getJibProfilesProfiles = function (input, common, data) { testOnlyProfilesPrebuilt["run-test-prebuilt"]["dependencies"].push(testedProfile + ".jdk_symbols"); } + var testOnlyProfilesPrebuiltDocs = { + "run-test-prebuilt-docs": clone(testOnlyProfilesPrebuilt["run-test-prebuilt"]) + }; + + testOnlyProfilesPrebuiltDocs["run-test-prebuilt-docs"].dependencies.push("docs.doc_api_spec", "tidy"); + testOnlyProfilesPrebuiltDocs["run-test-prebuilt-docs"].environment["DOCS_JDK_IMAGE_DIR"] + = input.get("docs.doc_api_spec", "install_path"); + testOnlyProfilesPrebuiltDocs["run-test-prebuilt-docs"].environment["TIDY"] + = input.get("tidy", "home_path") + "/bin/tidy"; + testOnlyProfilesPrebuiltDocs["run-test-prebuilt-docs"].labels = "test-docs"; + // If actually running the run-test-prebuilt profile, verify that the input // variable is valid and if so, add the appropriate target_* values from // the tested profile. Use testImageProfile value as backup. - if (input.profile == "run-test-prebuilt") { + if (input.profile == "run-test-prebuilt" || input.profile == "run-test-prebuilt-docs") { if (profiles[testedProfile] == null && profiles[testImageProfile] == null) { error("testedProfile is not defined: " + testedProfile + " " + testImageProfile); } } - if (profiles[testedProfile] != null) { - testOnlyProfilesPrebuilt["run-test-prebuilt"]["target_os"] - = profiles[testedProfile]["target_os"]; - testOnlyProfilesPrebuilt["run-test-prebuilt"]["target_cpu"] - = profiles[testedProfile]["target_cpu"]; - } else if (profiles[testImageProfile] != null) { - testOnlyProfilesPrebuilt["run-test-prebuilt"]["target_os"] - = profiles[testImageProfile]["target_os"]; - testOnlyProfilesPrebuilt["run-test-prebuilt"]["target_cpu"] - = profiles[testImageProfile]["target_cpu"]; + function updateProfileTargets(profiles, testedProfile, testImageProfile, targetProfile, runTestProfile) { + var profileToCheck = profiles[testedProfile] || profiles[testImageProfile]; + + if (profileToCheck != null) { + targetProfile[runTestProfile]["target_os"] = profileToCheck["target_os"]; + targetProfile[runTestProfile]["target_cpu"] = profileToCheck["target_cpu"]; + } } + + updateProfileTargets(profiles, testedProfile, testImageProfile, testOnlyProfilesPrebuilt, "run-test-prebuilt"); + updateProfileTargets(profiles, testedProfile, testImageProfile, testOnlyProfilesPrebuiltDocs, "run-test-prebuilt-docs"); + + profiles = concatObjects(profiles, testOnlyProfilesPrebuiltDocs); profiles = concatObjects(profiles, testOnlyProfilesPrebuilt); // On macosx add the devkit bin dir to the path in all the run-test profiles. @@ -1062,6 +1075,8 @@ var getJibProfilesProfiles = function (input, common, data) { } profiles["run-test-prebuilt"] = concatObjects(profiles["run-test-prebuilt"], runTestPrebuiltSrcFullExtra); + profiles["run-test-prebuilt-docs"] = concatObjects(profiles["run-test-prebuilt-docs"], + runTestPrebuiltSrcFullExtra); } // Generate the missing platform attributes diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf index de764d3f0212..35cc3011cc7a 100644 --- a/make/conf/version-numbers.conf +++ b/make/conf/version-numbers.conf @@ -28,15 +28,15 @@ DEFAULT_VERSION_FEATURE=21 DEFAULT_VERSION_INTERIM=0 -DEFAULT_VERSION_UPDATE=11 +DEFAULT_VERSION_UPDATE=12 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2026-04-21 +DEFAULT_VERSION_DATE=2026-07-21 DEFAULT_VERSION_CLASSFILE_MAJOR=65 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 DEFAULT_ACCEPTABLE_BOOT_VERSIONS="20 21" DEFAULT_JDK_SOURCE_TARGET_VERSION=21 -DEFAULT_PROMOTED_VERSION_PRE= +DEFAULT_PROMOTED_VERSION_PRE=ea diff --git a/src/hotspot/cpu/arm/c1_LIRAssembler_arm.cpp b/src/hotspot/cpu/arm/c1_LIRAssembler_arm.cpp index 45786898458b..3bab1d17616e 100644 --- a/src/hotspot/cpu/arm/c1_LIRAssembler_arm.cpp +++ b/src/hotspot/cpu/arm/c1_LIRAssembler_arm.cpp @@ -152,8 +152,14 @@ void LIR_Assembler::osr_entry() { int monitor_offset = (method()->max_locals() + 2 * (number_of_locks - 1)) * BytesPerWord; for (int i = 0; i < number_of_locks; i++) { int slot_offset = monitor_offset - (i * 2 * BytesPerWord); - __ ldr(R1, Address(OSR_buf, slot_offset + 0*BytesPerWord)); - __ ldr(R2, Address(OSR_buf, slot_offset + 1*BytesPerWord)); + if (slot_offset >= 4096 - BytesPerWord) { + __ add_slow(R2, OSR_buf, slot_offset); + __ ldr(R1, Address(R2, 0*BytesPerWord)); + __ ldr(R2, Address(R2, 1*BytesPerWord)); + } else { + __ ldr(R1, Address(OSR_buf, slot_offset + 0*BytesPerWord)); + __ ldr(R2, Address(OSR_buf, slot_offset + 1*BytesPerWord)); + } __ str(R1, frame_map()->address_for_monitor_lock(i)); __ str(R2, frame_map()->address_for_monitor_object(i)); } diff --git a/src/hotspot/cpu/ppc/c2_MacroAssembler_ppc.cpp b/src/hotspot/cpu/ppc/c2_MacroAssembler_ppc.cpp index d504c71e2b8b..608f8f919463 100644 --- a/src/hotspot/cpu/ppc/c2_MacroAssembler_ppc.cpp +++ b/src/hotspot/cpu/ppc/c2_MacroAssembler_ppc.cpp @@ -594,9 +594,11 @@ void C2_MacroAssembler::count_positives(Register src, Register cnt, Register res bind(Lslow); // Fallback to slow version. subf(tmp0, src, result); // Bytes known positive. - subf_(tmp0, tmp0, cnt); // Remaining Bytes. + clrldi(tmp1, cnt, 32); // Clear garbage from upper 32 bits. + subf_(tmp0, tmp0, tmp1); // Remaining Bytes. beq(CCR0, Ldone); mtctr(tmp0); + bind(Lloop); lbz(tmp0, 0, result); andi_(tmp0, tmp0, 0x80); diff --git a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp index adc40748fe7c..7e847e651844 100644 --- a/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp +++ b/src/hotspot/cpu/ppc/macroAssembler_ppc.cpp @@ -4440,7 +4440,7 @@ void MacroAssembler::push_cont_fastpath() { Label done; ld_ptr(R0, JavaThread::cont_fastpath_offset(), R16_thread); cmpld(CCR0, R1_SP, R0); - ble(CCR0, done); + ble(CCR0, done); // if (SP <= _cont_fastpath) goto done; st_ptr(R1_SP, JavaThread::cont_fastpath_offset(), R16_thread); bind(done); } @@ -4449,7 +4449,7 @@ void MacroAssembler::pop_cont_fastpath() { Label done; ld_ptr(R0, JavaThread::cont_fastpath_offset(), R16_thread); cmpld(CCR0, R1_SP, R0); - ble(CCR0, done); + blt(CCR0, done); // if (SP < _cont_fastpath) goto done; li(R0, 0); st_ptr(R0, JavaThread::cont_fastpath_offset(), R16_thread); bind(done); diff --git a/src/hotspot/cpu/ppc/registerMap_ppc.cpp b/src/hotspot/cpu/ppc/registerMap_ppc.cpp new file mode 100644 index 000000000000..e26e85df555f --- /dev/null +++ b/src/hotspot/cpu/ppc/registerMap_ppc.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2026 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. + * + * 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 "runtime/registerMap.hpp" + +address RegisterMap::pd_location(VMReg base_reg, int slot_idx) const { + if (base_reg->is_VectorSRegister()) { + // Not all physical slots belonging to a VectorRegister have corresponding + // valid VMReg locations in the RegisterMap. + // (See RegisterSaver::push_frame_reg_args_and_save_live_registers.) + // However, the slots are always saved to the stack in a contiguous region + // of memory so we can calculate the address of the upper slots by + // offsetting from the base address. + assert(base_reg->is_concrete(), "must pass base reg"); + address base_location = location(base_reg, nullptr); + if (base_location != nullptr) { + intptr_t offset_in_bytes = slot_idx * VMRegImpl::stack_slot_size; + return base_location + offset_in_bytes; + } else { + return nullptr; + } + } else { + return location(base_reg->next(slot_idx), nullptr); + } +} diff --git a/src/hotspot/cpu/ppc/registerMap_ppc.hpp b/src/hotspot/cpu/ppc/registerMap_ppc.hpp index 01eb642107cb..607c712d10f2 100644 --- a/src/hotspot/cpu/ppc/registerMap_ppc.hpp +++ b/src/hotspot/cpu/ppc/registerMap_ppc.hpp @@ -1,6 +1,6 @@ /* - * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. - * Copyright (c) 2012, 2013 SAP SE. All rights reserved. + * Copyright (c) 2000, 2026, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026 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 @@ -35,9 +35,7 @@ // Since there is none, we just return null. address pd_location(VMReg reg) const { return nullptr; } - address pd_location(VMReg base_reg, int slot_idx) const { - return location(base_reg->next(slot_idx), nullptr); - } + address pd_location(VMReg base_reg, int slot_idx) const; // no PD state to clear or copy: void pd_clear() {} diff --git a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp index 2281c083b98c..0790eceddc25 100644 --- a/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp +++ b/src/hotspot/cpu/ppc/sharedRuntime_ppc.cpp @@ -105,7 +105,7 @@ class RegisterSaver { // During deoptimization only the result registers need to be restored // all the other values have already been extracted. - static void restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes); + static void restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes, bool save_vectors); // Constants and data structures: @@ -355,6 +355,7 @@ OopMap* RegisterSaver::push_frame_reg_args_and_save_live_registers(MacroAssemble __ li(R30, offset); __ stxvd2x(as_VectorSRegister(reg_num), R30, R1_SP); + // RegisterMap::pd_location only uses the first VMReg for each VectorRegister. if (generate_oop_map) { map->set_callee_saved(VMRegImpl::stack2reg(offset>>2), RegisterSaver_LiveVSRegs[i].vmreg); @@ -528,10 +529,14 @@ void RegisterSaver::restore_argument_registers_and_pop_frame(MacroAssembler*masm } // Restore the registers that might be holding a result. -void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes) { +void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes, bool save_vectors) { const int regstosave_num = sizeof(RegisterSaver_LiveRegs) / sizeof(RegisterSaver::LiveRegType); - const int register_save_size = regstosave_num * reg_size; // VS registers not relevant here. + const int vecregstosave_num = save_vectors ? (sizeof(RegisterSaver_LiveVSRegs) / + sizeof(RegisterSaver::LiveRegType)) + : 0; + const int register_save_size = regstosave_num * reg_size + vecregstosave_num * vs_reg_size; + const int register_save_offset = frame_size_in_bytes - register_save_size; // restore all result registers (ints and floats) @@ -560,7 +565,7 @@ void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_siz offset += reg_size; } - assert(offset == frame_size_in_bytes, "consistency check"); + assert(offset == frame_size_in_bytes - (save_vectors ? vecregstosave_num * vs_reg_size : 0), "consistency check"); } // Is vector's size (in bytes) bigger than a size saved by default? @@ -2984,7 +2989,8 @@ void SharedRuntime::generate_deopt_blob() { &first_frame_size_in_bytes, /*generate_oop_map=*/ true, return_pc_adjustment_no_exception, - RegisterSaver::return_pc_is_lr); + RegisterSaver::return_pc_is_lr, + /*save_vectors*/ SuperwordUseVSX); assert(map != nullptr, "OopMap must have been created"); __ li(exec_mode_reg, Deoptimization::Unpack_deopt); @@ -3019,7 +3025,8 @@ void SharedRuntime::generate_deopt_blob() { &first_frame_size_in_bytes, /*generate_oop_map=*/ false, /*return_pc_adjustment_exception=*/ 0, - RegisterSaver::return_pc_is_pre_saved); + RegisterSaver::return_pc_is_pre_saved, + /*save_vectors*/ SuperwordUseVSX); // Deopt during an exception. Save exec mode for unpack_frames. __ li(exec_mode_reg, Deoptimization::Unpack_exception); @@ -3037,7 +3044,8 @@ void SharedRuntime::generate_deopt_blob() { &first_frame_size_in_bytes, /*generate_oop_map=*/ false, /*return_pc_adjustment_reexecute=*/ 0, - RegisterSaver::return_pc_is_pre_saved); + RegisterSaver::return_pc_is_pre_saved, + /*save_vectors*/ SuperwordUseVSX); __ li(exec_mode_reg, Deoptimization::Unpack_reexecute); #endif @@ -3063,7 +3071,7 @@ void SharedRuntime::generate_deopt_blob() { // Restore only the result registers that have been saved // by save_volatile_registers(...). - RegisterSaver::restore_result_registers(masm, first_frame_size_in_bytes); + RegisterSaver::restore_result_registers(masm, first_frame_size_in_bytes, /*save_vectors*/ SuperwordUseVSX); // reload the exec mode from the UnrollBlock (it might have changed) __ lwz(exec_mode_reg, in_bytes(Deoptimization::UnrollBlock::unpack_kind_offset()), unroll_block_reg); diff --git a/src/hotspot/cpu/ppc/vm_version_ppc.cpp b/src/hotspot/cpu/ppc/vm_version_ppc.cpp index e5037482c447..0543885a4752 100644 --- a/src/hotspot/cpu/ppc/vm_version_ppc.cpp +++ b/src/hotspot/cpu/ppc/vm_version_ppc.cpp @@ -26,6 +26,7 @@ #include "precompiled.hpp" #include "asm/assembler.inline.hpp" #include "asm/macroAssembler.inline.hpp" +#include "compiler/compilerDefinitions.inline.hpp" #include "compiler/disassembler.hpp" #include "jvm.h" #include "memory/resourceArea.hpp" @@ -130,7 +131,7 @@ void VM_Version::initialize() { } if (PowerArchitecturePPC64 >= 8) { - if (FLAG_IS_DEFAULT(SuperwordUseVSX)) { + if (FLAG_IS_DEFAULT(SuperwordUseVSX) && CompilerConfig::is_c2_enabled()) { FLAG_SET_ERGO(SuperwordUseVSX, true); } } else { diff --git a/src/hotspot/os/aix/os_aix.cpp b/src/hotspot/os/aix/os_aix.cpp index 71e1ab893084..ec2eda18bd3c 100644 --- a/src/hotspot/os/aix/os_aix.cpp +++ b/src/hotspot/os/aix/os_aix.cpp @@ -177,7 +177,7 @@ static void vmembk_print_on(outputStream* os); //////////////////////////////////////////////////////////////////////////////// // global variables (for a description see os_aix.hpp) -julong os::Aix::_physical_memory = 0; +physical_memory_size_type os::Aix::_physical_memory = 0; pthread_t os::Aix::_main_thread = ((pthread_t)0); @@ -265,28 +265,29 @@ static bool is_close_to_brk(address a) { return false; } -julong os::free_memory() { - return Aix::available_memory(); +bool os::free_memory(physical_memory_size_type& value) { + return Aix::available_memory(value); } -julong os::available_memory() { - return Aix::available_memory(); +bool os::available_memory(physical_memory_size_type& value) { + return Aix::available_memory(value); } -julong os::Aix::available_memory() { +bool os::Aix::available_memory(physical_memory_size_type& value) { // Avoid expensive API call here, as returned value will always be null. if (os::Aix::on_pase()) { return 0x0LL; } os::Aix::meminfo_t mi; if (os::Aix::get_meminfo(&mi)) { - return mi.real_free; + value = static_cast(mi.real_free); + return true; } else { - return ULONG_MAX; + return false; } } -julong os::physical_memory() { +physical_memory_size_type os::physical_memory() { return Aix::physical_memory(); } @@ -357,7 +358,7 @@ void os::Aix::initialize_system_info() { if (!os::Aix::get_meminfo(&mi)) { assert(false, "os::Aix::get_meminfo failed."); } - _physical_memory = (julong) mi.real_total; + _physical_memory = static_cast(mi.real_total); } // Helper function for tracing page sizes. @@ -2402,7 +2403,7 @@ jint os::init_2(void) { } trcVerbose("processor count: %d", os::_processor_count); - trcVerbose("physical memory: %lu", Aix::_physical_memory); + trcVerbose("physical memory: " PHYS_MEM_TYPE_FORMAT, Aix::_physical_memory); // Initially build up the loaded dll map. LoadedLibraries::reload(); diff --git a/src/hotspot/os/aix/os_aix.hpp b/src/hotspot/os/aix/os_aix.hpp index 8cb49b5fe74a..7e47ced50887 100644 --- a/src/hotspot/os/aix/os_aix.hpp +++ b/src/hotspot/os/aix/os_aix.hpp @@ -35,7 +35,7 @@ class os::Aix { private: - static julong _physical_memory; + static physical_memory_size_type _physical_memory; static pthread_t _main_thread; // -1 = uninitialized, 0 = AIX, 1 = OS/400 (PASE) @@ -58,9 +58,9 @@ class os::Aix { // 1 - EXTSHM=ON static int _extshm; - static julong available_memory(); - static julong free_memory(); - static julong physical_memory() { return _physical_memory; } + static bool available_memory(physical_memory_size_type& value); + static bool free_memory(physical_memory_size_type& value); + static physical_memory_size_type physical_memory() { return _physical_memory; } static void initialize_system_info(); // OS recognitions (PASE/AIX, OS level) call this before calling any diff --git a/src/hotspot/os/bsd/os_bsd.cpp b/src/hotspot/os/bsd/os_bsd.cpp index eca9aa9c92ac..0a5e29d1fcb3 100644 --- a/src/hotspot/os/bsd/os_bsd.cpp +++ b/src/hotspot/os/bsd/os_bsd.cpp @@ -120,7 +120,7 @@ //////////////////////////////////////////////////////////////////////////////// // global variables -julong os::Bsd::_physical_memory = 0; +physical_memory_size_type os::Bsd::_physical_memory = 0; #ifdef __APPLE__ mach_timebase_info_data_t os::Bsd::_timebase_info = {0, 0}; @@ -139,17 +139,17 @@ static volatile int processor_id_next = 0; //////////////////////////////////////////////////////////////////////////////// // utility functions -julong os::available_memory() { - return Bsd::available_memory(); +bool os::available_memory(physical_memory_size_type& value) { + return Bsd::available_memory(value); } -julong os::free_memory() { - return Bsd::available_memory(); +bool os::free_memory(physical_memory_size_type& value) { + return Bsd::available_memory(value); } // available here means free -julong os::Bsd::available_memory() { - uint64_t available = physical_memory() >> 2; +bool os::Bsd::available_memory(physical_memory_size_type& value) { + physical_memory_size_type available = physical_memory() >> 2; #ifdef __APPLE__ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT; vm_statistics64_data_t vmstat; @@ -159,9 +159,12 @@ julong os::Bsd::available_memory() { "host_statistics64 failed - check mach_host_self() and count"); if (kerr == KERN_SUCCESS) { available = vmstat.free_count * os::vm_page_size(); + } else { + return false; } #endif - return available; + value = available; + return true; } // for more info see : @@ -180,7 +183,7 @@ void os::Bsd::print_uptime_info(outputStream* st) { } } -julong os::physical_memory() { +physical_memory_size_type os::physical_memory() { return Bsd::physical_memory(); } @@ -254,7 +257,7 @@ void os::Bsd::initialize_system_info() { len = sizeof(mem_val); if (sysctl(mib, 2, &mem_val, &len, nullptr, 0) != -1) { assert(len == sizeof(mem_val), "unexpected data size"); - _physical_memory = mem_val; + _physical_memory = static_cast(mem_val); } else { _physical_memory = 256 * 1024 * 1024; // fallback (XXXBSD?) } @@ -265,7 +268,7 @@ void os::Bsd::initialize_system_info() { // datasize rlimit restricts us anyway. struct rlimit limits; getrlimit(RLIMIT_DATA, &limits); - _physical_memory = MIN2(_physical_memory, (julong)limits.rlim_cur); + _physical_memory = MIN2(_physical_memory, static_cast(limits.rlim_cur)); } #endif } @@ -1411,10 +1414,13 @@ void os::print_memory_info(outputStream* st) { st->print("Memory:"); st->print(" " SIZE_FORMAT "k page", os::vm_page_size()>>10); - st->print(", physical " UINT64_FORMAT "k", - os::physical_memory() >> 10); - st->print("(" UINT64_FORMAT "k free)", - os::available_memory() >> 10); + physical_memory_size_type phys_mem = os::physical_memory(); + st->print(", physical " PHYS_MEM_TYPE_FORMAT "k", + phys_mem >> 10); + physical_memory_size_type avail_mem = 0; + (void)os::available_memory(avail_mem); + st->print("(" PHYS_MEM_TYPE_FORMAT "k free)", + avail_mem >> 10); if((sysctlbyname("vm.swapusage", &swap_usage, &size, nullptr, 0) == 0) || (errno == ENOMEM)) { if (size >= offset_of(xsw_usage, xsu_used)) { diff --git a/src/hotspot/os/bsd/os_bsd.hpp b/src/hotspot/os/bsd/os_bsd.hpp index f79212bc43c0..f8317ed0c8d7 100644 --- a/src/hotspot/os/bsd/os_bsd.hpp +++ b/src/hotspot/os/bsd/os_bsd.hpp @@ -42,12 +42,12 @@ class os::Bsd { protected: - static julong _physical_memory; + static physical_memory_size_type _physical_memory; static pthread_t _main_thread; - static julong available_memory(); - static julong free_memory(); - static julong physical_memory() { return _physical_memory; } + static bool available_memory(physical_memory_size_type& value); + static bool free_memory(physical_memory_size_type& value); + static physical_memory_size_type physical_memory() { return _physical_memory; } static void initialize_system_info(); static void rebuild_cpu_to_node_map(); diff --git a/src/hotspot/os/linux/cgroupSubsystem_linux.cpp b/src/hotspot/os/linux/cgroupSubsystem_linux.cpp index 1186c78b865a..99648021a5b1 100644 --- a/src/hotspot/os/linux/cgroupSubsystem_linux.cpp +++ b/src/hotspot/os/linux/cgroupSubsystem_linux.cpp @@ -62,7 +62,7 @@ CgroupSubsystem* CgroupSubsystemFactory::create() { CgroupV1MemoryController* memory = nullptr; CgroupV1Controller* cpuset = nullptr; CgroupV1CpuController* cpu = nullptr; - CgroupV1Controller* cpuacct = nullptr; + CgroupV1CpuacctController* cpuacct = nullptr; CgroupV1Controller* pids = nullptr; CgroupInfo cg_infos[CG_INFO_LENGTH]; u1 cg_type_flags = INVALID_CGROUPS_GENERIC; @@ -105,9 +105,10 @@ CgroupSubsystem* CgroupSubsystemFactory::create() { CgroupV2CpuController* cpu = new CgroupV2CpuController(CgroupV2Controller(cg_infos[CPU_IDX]._mount_path, cg_infos[CPU_IDX]._cgroup_path, cg_infos[CPU_IDX]._read_only)); + CgroupV2CpuacctController* cpuacct = new CgroupV2CpuacctController(cpu); log_debug(os, container)("Detected cgroups v2 unified hierarchy"); cleanup(cg_infos); - return new CgroupV2Subsystem(memory, cpu, mem_other); + return new CgroupV2Subsystem(memory, cpu, cpuacct, mem_other); } /* @@ -150,7 +151,7 @@ CgroupSubsystem* CgroupSubsystemFactory::create() { cpu = new CgroupV1CpuController(CgroupV1Controller(info._root_mount_path, info._mount_path, info._read_only)); cpu->set_subsystem_path(info._cgroup_path); } else if (strcmp(info._name, "cpuacct") == 0) { - cpuacct = new CgroupV1Controller(info._root_mount_path, info._mount_path, info._read_only); + cpuacct = new CgroupV1CpuacctController(CgroupV1Controller(info._root_mount_path, info._mount_path, info._read_only)); cpuacct->set_subsystem_path(info._cgroup_path); } else if (strcmp(info._name, "pids") == 0) { pids = new CgroupV1Controller(info._root_mount_path, info._mount_path, info._read_only); @@ -669,8 +670,8 @@ jlong CgroupSubsystem::memory_limit_in_bytes() { if (!memory_limit->should_check_metric()) { return memory_limit->value(); } - jlong phys_mem = os::Linux::physical_memory(); - log_trace(os, container)("total physical memory: " JLONG_FORMAT, phys_mem); + julong phys_mem = static_cast(os::Linux::physical_memory()); + log_trace(os, container)("total physical memory: " JULONG_FORMAT, phys_mem); jlong mem_limit = contrl->controller()->read_memory_limit_in_bytes(phys_mem); // Update cached metric to avoid re-reading container settings too often memory_limit->set_value(mem_limit, OSCONTAINER_CACHE_TIMEOUT); @@ -840,16 +841,20 @@ jlong CgroupController::limit_from_str(char* limit_str) { // CgroupSubsystem implementations jlong CgroupSubsystem::memory_and_swap_limit_in_bytes() { - julong phys_mem = os::Linux::physical_memory(); + julong phys_mem = static_cast(os::Linux::physical_memory()); julong host_swap = os::Linux::host_swap(); return memory_controller()->controller()->memory_and_swap_limit_in_bytes(phys_mem, host_swap); } jlong CgroupSubsystem::memory_soft_limit_in_bytes() { - julong phys_mem = os::Linux::physical_memory(); + julong phys_mem = static_cast(os::Linux::physical_memory()); return memory_controller()->controller()->memory_soft_limit_in_bytes(phys_mem); } +jlong CgroupSubsystem::memory_throttle_limit_in_bytes() { + return memory_controller()->controller()->memory_throttle_limit_in_bytes(); +} + jlong CgroupSubsystem::memory_usage_in_bytes() { return memory_controller()->controller()->memory_usage_in_bytes(); } @@ -878,7 +883,11 @@ int CgroupSubsystem::cpu_shares() { return cpu_controller()->controller()->cpu_shares(); } +jlong CgroupSubsystem::cpu_usage_in_micros() { + return cpuacct_controller()->cpu_usage_in_micros(); +} + void CgroupSubsystem::print_version_specific_info(outputStream* st) { - julong phys_mem = os::Linux::physical_memory(); + julong phys_mem = static_cast(os::Linux::physical_memory()); memory_controller()->controller()->print_version_specific_info(st, phys_mem); } diff --git a/src/hotspot/os/linux/cgroupSubsystem_linux.hpp b/src/hotspot/os/linux/cgroupSubsystem_linux.hpp index 6b32408f801c..13db41d1fa6e 100644 --- a/src/hotspot/os/linux/cgroupSubsystem_linux.hpp +++ b/src/hotspot/os/linux/cgroupSubsystem_linux.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -227,6 +227,18 @@ class CgroupCpuController: public CHeapObj { virtual const char* cgroup_path() = 0; }; +// Pure virtual class representing version agnostic CPU accounting controllers +class CgroupCpuacctController: public CHeapObj { + public: + virtual jlong cpu_usage_in_micros() = 0; + virtual bool needs_hierarchy_adjustment() = 0; + virtual bool is_read_only() = 0; + virtual const char* subsystem_path() = 0; + virtual void set_subsystem_path(const char* cgroup_path) = 0; + virtual const char* mount_point() = 0; + virtual const char* cgroup_path() = 0; +}; + // Pure virtual class representing version agnostic memory controllers class CgroupMemoryController: public CHeapObj { public: @@ -234,6 +246,7 @@ class CgroupMemoryController: public CHeapObj { virtual jlong memory_usage_in_bytes() = 0; virtual jlong memory_and_swap_limit_in_bytes(julong host_mem, julong host_swap) = 0; virtual jlong memory_soft_limit_in_bytes(julong upper_bound) = 0; + virtual jlong memory_throttle_limit_in_bytes() = 0; virtual jlong memory_max_usage_in_bytes() = 0; virtual jlong rss_usage_in_bytes() = 0; virtual jlong cache_usage_in_bytes() = 0; @@ -260,14 +273,18 @@ class CgroupSubsystem: public CHeapObj { virtual const char * container_type() = 0; virtual CachingCgroupController* memory_controller() = 0; virtual CachingCgroupController* cpu_controller() = 0; + virtual CgroupCpuacctController* cpuacct_controller() = 0; int cpu_quota(); int cpu_period(); int cpu_shares(); + jlong cpu_usage_in_micros(); + jlong memory_usage_in_bytes(); jlong memory_and_swap_limit_in_bytes(); jlong memory_soft_limit_in_bytes(); + jlong memory_throttle_limit_in_bytes(); jlong memory_max_usage_in_bytes(); jlong rss_usage_in_bytes(); jlong cache_usage_in_bytes(); diff --git a/src/hotspot/os/linux/cgroupUtil_linux.cpp b/src/hotspot/os/linux/cgroupUtil_linux.cpp index b52ef87dcaee..72dda36504d3 100644 --- a/src/hotspot/os/linux/cgroupUtil_linux.cpp +++ b/src/hotspot/os/linux/cgroupUtil_linux.cpp @@ -65,7 +65,7 @@ void CgroupUtil::adjust_controller(CgroupMemoryController* mem) { char* cg_path = os::strdup(orig); char* last_slash; assert(cg_path[0] == '/', "cgroup path must start with '/'"); - julong phys_mem = os::Linux::physical_memory(); + julong phys_mem = static_cast(os::Linux::physical_memory()); char* limit_cg_path = nullptr; jlong limit = mem->read_memory_limit_in_bytes(phys_mem); jlong lowest_limit = limit < 0 ? phys_mem : limit; diff --git a/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp b/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp index 8c8f558116a0..75544ff6059e 100644 --- a/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp +++ b/src/hotspot/os/linux/cgroupV1Subsystem_linux.cpp @@ -243,10 +243,16 @@ jlong CgroupV1MemoryController::memory_soft_limit_in_bytes(julong phys_mem) { } } +jlong CgroupV1MemoryController::memory_throttle_limit_in_bytes() { + // Log this string at trace level so as to make tests happy. + log_trace(os, container)("Memory Throttle Limit is not supported."); + return OSCONTAINER_ERROR; // not supported +} + // Constructor CgroupV1Subsystem::CgroupV1Subsystem(CgroupV1Controller* cpuset, CgroupV1CpuController* cpu, - CgroupV1Controller* cpuacct, + CgroupV1CpuacctController* cpuacct, CgroupV1Controller* pids, CgroupV1MemoryController* memory) : _cpuset(cpuset), @@ -415,6 +421,13 @@ int CgroupV1CpuController::cpu_shares() { return shares_int; } +jlong CgroupV1CpuacctController::cpu_usage_in_micros() { + julong cpu_usage; + CONTAINER_READ_NUMBER_CHECKED(reader(), "/cpuacct.usage", "CPU Usage", cpu_usage); + // Output is in nanoseconds, convert to microseconds. + return (jlong)cpu_usage / 1000; +} + /* pids_max * * Return the maximum number of tasks available to the process diff --git a/src/hotspot/os/linux/cgroupV1Subsystem_linux.hpp b/src/hotspot/os/linux/cgroupV1Subsystem_linux.hpp index 250d0273fc4d..ad1feb38f9e2 100644 --- a/src/hotspot/os/linux/cgroupV1Subsystem_linux.hpp +++ b/src/hotspot/os/linux/cgroupV1Subsystem_linux.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -81,6 +81,7 @@ class CgroupV1MemoryController final : public CgroupMemoryController { jlong memory_usage_in_bytes() override; jlong memory_and_swap_limit_in_bytes(julong host_mem, julong host_swap) override; jlong memory_soft_limit_in_bytes(julong upper_bound) override; + jlong memory_throttle_limit_in_bytes() override; jlong memory_max_usage_in_bytes() override; jlong rss_usage_in_bytes() override; jlong cache_usage_in_bytes() override; @@ -140,12 +141,41 @@ class CgroupV1CpuController final : public CgroupCpuController { } }; +class CgroupV1CpuacctController final : public CgroupCpuacctController { + + private: + CgroupV1Controller _reader; + CgroupV1Controller* reader() { return &_reader; } + public: + jlong cpu_usage_in_micros() override; + void set_subsystem_path(const char *cgroup_path) override { + reader()->set_subsystem_path(cgroup_path); + } + bool is_read_only() override { + return reader()->is_read_only(); + } + const char* subsystem_path() override { + return reader()->subsystem_path(); + } + const char* mount_point() override { + return reader()->mount_point(); + } + bool needs_hierarchy_adjustment() override { + return reader()->needs_hierarchy_adjustment(); + } + const char* cgroup_path() override { return reader()->cgroup_path(); } + + public: + CgroupV1CpuacctController(const CgroupV1Controller& reader) : _reader(reader) { + } +}; + class CgroupV1Subsystem: public CgroupSubsystem { public: CgroupV1Subsystem(CgroupV1Controller* cpuset, CgroupV1CpuController* cpu, - CgroupV1Controller* cpuacct, + CgroupV1CpuacctController* cpuacct, CgroupV1Controller* pids, CgroupV1MemoryController* memory); @@ -165,13 +195,14 @@ class CgroupV1Subsystem: public CgroupSubsystem { } CachingCgroupController* memory_controller() { return _memory; } CachingCgroupController* cpu_controller() { return _cpu; } + CgroupCpuacctController* cpuacct_controller() { return _cpuacct; } private: /* controllers */ CachingCgroupController* _memory = nullptr; CgroupV1Controller* _cpuset = nullptr; CachingCgroupController* _cpu = nullptr; - CgroupV1Controller* _cpuacct = nullptr; + CgroupV1CpuacctController* _cpuacct = nullptr; CgroupV1Controller* _pids = nullptr; }; diff --git a/src/hotspot/os/linux/cgroupV2Subsystem_linux.cpp b/src/hotspot/os/linux/cgroupV2Subsystem_linux.cpp index 4367eba4c43a..395a78d4addc 100644 --- a/src/hotspot/os/linux/cgroupV2Subsystem_linux.cpp +++ b/src/hotspot/os/linux/cgroupV2Subsystem_linux.cpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, 2025, Red Hat Inc. + * 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 @@ -25,6 +26,8 @@ #include "cgroupV2Subsystem_linux.hpp" #include "cgroupUtil_linux.hpp" +#include + // Constructor CgroupV2Controller::CgroupV2Controller(char* mount_path, char *cgroup_path, @@ -60,22 +63,39 @@ int CgroupV2CpuController::cpu_shares() { log_debug(os, container)("CPU Shares is: %d", -1); return -1; } + // cg v2 values must be in range [1-10000] + assert(shares_int >= 1 && shares_int <= 10000, "invariant"); // CPU shares (OCI) value needs to get translated into // a proper Cgroups v2 value. See: - // https://github.com/containers/crun/blob/master/crun.1.md#cpu-controller + // https://github.com/containers/crun/blob/1.24/crun.1.md#cpu-controller // // Use the inverse of (x == OCI value, y == cgroupsv2 value): - // ((262142 * y - 1)/9999) + 2 = x + // y = 10^(log2(x)^2/612 + 125/612 * log2(x) - 7.0/34.0) + // + // By re-arranging it to the standard quadratic form: + // log2(x)^2 + 125 * log2(x) - (126 + 612 * log_10(y)) = 0 + // + // Therefore, log2(x) = (-125 + sqrt( 125^2 - 4 * (-(126 + 612 * log_10(y)))))/2 // - int x = 262142 * shares_int - 1; - double frac = x/9999.0; - x = ((int)frac) + 2; + // As a result we have the inverse (we can discount substraction of the + // square root value since those values result in very small numbers and the + // cpu shares values - OCI - are in range [2,262144]): + // + // x = 2^((-125 + sqrt(16129 + 2448* log10(y)))/2) + // + double log_multiplicand = log10(shares_int); + double discriminant = 16129 + 2448 * log_multiplicand; + double square_root = sqrt(discriminant); + double exponent = (-125 + square_root)/2; + double scaled_val = pow(2, exponent); + int x = (int) scaled_val; log_trace(os, container)("Scaled CPU shares value is: %d", x); // Since the scaled value is not precise, return the closest // multiple of PER_CPU_SHARES for a more conservative mapping if ( x <= PER_CPU_SHARES ) { - // will always map to 1 CPU + // Don't do the multiples of PER_CPU_SHARES mapping since we + // have a value <= PER_CPU_SHARES log_debug(os, container)("CPU Shares is: %d", x); return x; } @@ -114,12 +134,14 @@ int CgroupV2CpuController::cpu_quota() { // Constructor CgroupV2Subsystem::CgroupV2Subsystem(CgroupV2MemoryController * memory, CgroupV2CpuController* cpu, + CgroupV2CpuacctController* cpuacct, CgroupV2Controller unified) : _unified(unified) { CgroupUtil::adjust_controller(memory); CgroupUtil::adjust_controller(cpu); _memory = new CachingCgroupController(memory); _cpu = new CachingCgroupController(cpu); + _cpuacct = cpuacct; } bool CgroupV2Subsystem::is_containerized() { @@ -152,6 +174,17 @@ int CgroupV2CpuController::cpu_period() { return period; } +jlong CgroupV2CpuController::cpu_usage_in_micros() { + julong cpu_usage; + bool is_ok = reader()->read_numerical_key_value("/cpu.stat", "usage_usec", &cpu_usage); + if (!is_ok) { + log_trace(os, container)("CPU Usage failed: %d", OSCONTAINER_ERROR); + return OSCONTAINER_ERROR; + } + log_trace(os, container)("CPU Usage is: " JULONG_FORMAT, cpu_usage); + return (jlong)cpu_usage; +} + /* memory_usage_in_bytes * * Return the amount of used memory used by this cgroup and descendents @@ -173,10 +206,16 @@ jlong CgroupV2MemoryController::memory_soft_limit_in_bytes(julong phys_mem) { return mem_soft_limit; } +jlong CgroupV2MemoryController::memory_throttle_limit_in_bytes() { + jlong mem_throttle_limit; + CONTAINER_READ_NUMBER_CHECKED_MAX(reader(), "/memory.high", "Memory Throttle Limit", mem_throttle_limit); + return mem_throttle_limit; +} + jlong CgroupV2MemoryController::memory_max_usage_in_bytes() { - // Log this string at trace level so as to make tests happy. - log_trace(os, container)("Maximum Memory Usage is not supported."); - return OSCONTAINER_ERROR; // not supported + julong mem_max_usage; + CONTAINER_READ_NUMBER_CHECKED(reader(), "/memory.peak", "Maximum Memory Usage", mem_max_usage); + return mem_max_usage; } jlong CgroupV2MemoryController::rss_usage_in_bytes() { diff --git a/src/hotspot/os/linux/cgroupV2Subsystem_linux.hpp b/src/hotspot/os/linux/cgroupV2Subsystem_linux.hpp index 0a053fa7e45e..2915aea01896 100644 --- a/src/hotspot/os/linux/cgroupV2Subsystem_linux.hpp +++ b/src/hotspot/os/linux/cgroupV2Subsystem_linux.hpp @@ -1,5 +1,6 @@ /* * Copyright (c) 2020, 2024, Red Hat Inc. + * 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 @@ -61,6 +62,34 @@ class CgroupV2CpuController: public CgroupCpuController { int cpu_quota() override; int cpu_period() override; int cpu_shares() override; + jlong cpu_usage_in_micros(); + bool is_read_only() override { + return reader()->is_read_only(); + } + const char* subsystem_path() override { + return reader()->subsystem_path(); + } + bool needs_hierarchy_adjustment() override { + return reader()->needs_hierarchy_adjustment(); + } + void set_subsystem_path(const char* cgroup_path) override { + reader()->set_subsystem_path(cgroup_path); + } + const char* mount_point() override { return reader()->mount_point(); } + const char* cgroup_path() override { return reader()->cgroup_path(); } +}; + +class CgroupV2CpuacctController: public CgroupCpuacctController { + private: + CgroupV2CpuController* _reader; + CgroupV2CpuController* reader() { return _reader; } + public: + CgroupV2CpuacctController(CgroupV2CpuController* reader) : _reader(reader) { + } + // In cgroup v2, cpu usage is a part of the cpu controller. + jlong cpu_usage_in_micros() override { + return reader()->cpu_usage_in_micros(); + } bool is_read_only() override { return reader()->is_read_only(); } @@ -88,6 +117,7 @@ class CgroupV2MemoryController final: public CgroupMemoryController { jlong read_memory_limit_in_bytes(julong upper_bound) override; jlong memory_and_swap_limit_in_bytes(julong host_mem, julong host_swp) override; jlong memory_soft_limit_in_bytes(julong upper_bound) override; + jlong memory_throttle_limit_in_bytes() override; jlong memory_usage_in_bytes() override; jlong memory_max_usage_in_bytes() override; jlong rss_usage_in_bytes() override; @@ -117,11 +147,14 @@ class CgroupV2Subsystem: public CgroupSubsystem { CachingCgroupController* _memory = nullptr; CachingCgroupController* _cpu = nullptr; + CgroupCpuacctController* _cpuacct = nullptr; + CgroupV2Controller* unified() { return &_unified; } public: CgroupV2Subsystem(CgroupV2MemoryController * memory, CgroupV2CpuController* cpu, + CgroupV2CpuacctController* cpuacct, CgroupV2Controller unified); char * cpu_cpuset_cpus() override; @@ -136,6 +169,7 @@ class CgroupV2Subsystem: public CgroupSubsystem { } CachingCgroupController* memory_controller() override { return _memory; } CachingCgroupController* cpu_controller() override { return _cpu; } + CgroupCpuacctController* cpuacct_controller() override { return _cpuacct; }; }; #endif // CGROUP_V2_SUBSYSTEM_LINUX_HPP diff --git a/src/hotspot/os/linux/osContainer_linux.cpp b/src/hotspot/os/linux/osContainer_linux.cpp index 536869c785d9..8b91486122ca 100644 --- a/src/hotspot/os/linux/osContainer_linux.cpp +++ b/src/hotspot/os/linux/osContainer_linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, 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 @@ -117,6 +117,11 @@ jlong OSContainer::memory_soft_limit_in_bytes() { return cgroup_subsystem->memory_soft_limit_in_bytes(); } +jlong OSContainer::memory_throttle_limit_in_bytes() { + assert(cgroup_subsystem != nullptr, "cgroup subsystem not available"); + return cgroup_subsystem->memory_throttle_limit_in_bytes(); +} + jlong OSContainer::memory_usage_in_bytes() { assert(cgroup_subsystem != nullptr, "cgroup subsystem not available"); return cgroup_subsystem->memory_usage_in_bytes(); @@ -172,6 +177,11 @@ int OSContainer::cpu_shares() { return cgroup_subsystem->cpu_shares(); } +jlong OSContainer::cpu_usage_in_micros() { + assert(cgroup_subsystem != nullptr, "cgroup subsystem not available"); + return cgroup_subsystem->cpu_usage_in_micros(); +} + jlong OSContainer::pids_max() { assert(cgroup_subsystem != nullptr, "cgroup subsystem not available"); return cgroup_subsystem->pids_max(); diff --git a/src/hotspot/os/linux/osContainer_linux.hpp b/src/hotspot/os/linux/osContainer_linux.hpp index bb03ba3b005a..56bd80cb8f96 100644 --- a/src/hotspot/os/linux/osContainer_linux.hpp +++ b/src/hotspot/os/linux/osContainer_linux.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, 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 @@ -53,6 +53,7 @@ class OSContainer: AllStatic { static jlong memory_limit_in_bytes(); static jlong memory_and_swap_limit_in_bytes(); static jlong memory_soft_limit_in_bytes(); + static jlong memory_throttle_limit_in_bytes(); static jlong memory_usage_in_bytes(); static jlong memory_max_usage_in_bytes(); static jlong rss_usage_in_bytes(); @@ -68,6 +69,8 @@ class OSContainer: AllStatic { static int cpu_shares(); + static jlong cpu_usage_in_micros(); + static jlong pids_max(); static jlong pids_current(); }; diff --git a/src/hotspot/os/linux/os_linux.cpp b/src/hotspot/os/linux/os_linux.cpp index daec53fa1328..68761a77679f 100644 --- a/src/hotspot/os/linux/os_linux.cpp +++ b/src/hotspot/os/linux/os_linux.cpp @@ -161,7 +161,7 @@ enum CoredumpFilterBit { //////////////////////////////////////////////////////////////////////////////// // global variables -julong os::Linux::_physical_memory = 0; +physical_memory_size_type os::Linux::_physical_memory = 0; address os::Linux::_initial_thread_stack_bottom = nullptr; uintptr_t os::Linux::_initial_thread_stack_size = 0; @@ -236,15 +236,16 @@ julong os::Linux::available_memory_in_container() { return avail_mem; } -julong os::available_memory() { - return Linux::available_memory(); +bool os::available_memory(physical_memory_size_type& value) { + return Linux::available_memory(value); } -julong os::Linux::available_memory() { +bool os::Linux::available_memory(physical_memory_size_type& value) { julong avail_mem = available_memory_in_container(); if (avail_mem != static_cast(-1L)) { log_trace(os)("available container memory: " JULONG_FORMAT, avail_mem); - return avail_mem; + value = static_cast(avail_mem); + return true; } FILE *fp = os::fopen("/proc/meminfo", "r"); @@ -259,43 +260,52 @@ julong os::Linux::available_memory() { fclose(fp); } if (avail_mem == static_cast(-1L)) { - avail_mem = free_memory(); + physical_memory_size_type free_mem = 0; + if (!free_memory(free_mem)) { + return false; + } + avail_mem = static_cast(free_mem); } log_trace(os)("available memory: " JULONG_FORMAT, avail_mem); - return avail_mem; + value = static_cast(avail_mem); + return true; } -julong os::free_memory() { - return Linux::free_memory(); +bool os::free_memory(physical_memory_size_type& value) { + return Linux::free_memory(value); } -julong os::Linux::free_memory() { +bool os::Linux::free_memory(physical_memory_size_type& value) { // values in struct sysinfo are "unsigned long" struct sysinfo si; julong free_mem = available_memory_in_container(); if (free_mem != static_cast(-1L)) { log_trace(os)("free container memory: " JULONG_FORMAT, free_mem); - return free_mem; + value = static_cast(free_mem); + return true; } - sysinfo(&si); + int ret = sysinfo(&si); + if (ret != 0) { + return false; + } free_mem = (julong)si.freeram * si.mem_unit; log_trace(os)("free memory: " JULONG_FORMAT, free_mem); - return free_mem; + value = static_cast(free_mem); + return true; } -julong os::physical_memory() { - jlong phys_mem = 0; +physical_memory_size_type os::physical_memory() { if (OSContainer::is_containerized()) { jlong mem_limit; if ((mem_limit = OSContainer::memory_limit_in_bytes()) > 0) { log_trace(os)("total container memory: " JLONG_FORMAT, mem_limit); - return mem_limit; + return static_cast(mem_limit); } } - phys_mem = Linux::physical_memory(); - log_trace(os)("total system memory: " JLONG_FORMAT, phys_mem); + physical_memory_size_type phys_mem = Linux::physical_memory(); + log_trace(os)("total system memory: " PHYS_MEM_TYPE_FORMAT, phys_mem); return phys_mem; } @@ -452,7 +462,7 @@ void os::Linux::initialize_system_info() { fclose(fp); } } - _physical_memory = (julong)sysconf(_SC_PHYS_PAGES) * (julong)sysconf(_SC_PAGESIZE); + _physical_memory = static_cast(sysconf(_SC_PHYS_PAGES)) * static_cast(sysconf(_SC_PAGESIZE)); assert(processor_count() > 0, "linux error"); } @@ -2375,9 +2385,18 @@ bool os::Linux::print_container_info(outputStream* st) { st->print_cr("%s", i == OSCONTAINER_ERROR ? "not supported" : "no shares"); } + jlong j = OSContainer::cpu_usage_in_micros(); + st->print("cpu_usage_in_micros: "); + if (j >= 0) { + st->print_cr(JLONG_FORMAT, j); + } else { + st->print_cr("%s", j == OSCONTAINER_ERROR ? "not supported" : "no usage"); + } + OSContainer::print_container_helper(st, OSContainer::memory_limit_in_bytes(), "memory_limit_in_bytes"); OSContainer::print_container_helper(st, OSContainer::memory_and_swap_limit_in_bytes(), "memory_and_swap_limit_in_bytes"); OSContainer::print_container_helper(st, OSContainer::memory_soft_limit_in_bytes(), "memory_soft_limit_in_bytes"); + OSContainer::print_container_helper(st, OSContainer::memory_throttle_limit_in_bytes(), "memory_throttle_limit_in_bytes"); OSContainer::print_container_helper(st, OSContainer::memory_usage_in_bytes(), "memory_usage_in_bytes"); OSContainer::print_container_helper(st, OSContainer::memory_max_usage_in_bytes(), "memory_max_usage_in_bytes"); OSContainer::print_container_helper(st, OSContainer::rss_usage_in_bytes(), "rss_usage_in_bytes"); @@ -2385,7 +2404,7 @@ bool os::Linux::print_container_info(outputStream* st) { OSContainer::print_version_specific_info(st); - jlong j = OSContainer::pids_max(); + j = OSContainer::pids_max(); st->print("maximum number of tasks: "); if (j > 0) { st->print_cr(JLONG_FORMAT, j); @@ -2432,11 +2451,13 @@ void os::print_memory_info(outputStream* st) { // values in struct sysinfo are "unsigned long" struct sysinfo si; sysinfo(&si); - - st->print(", physical " UINT64_FORMAT "k", - os::physical_memory() >> 10); - st->print("(" UINT64_FORMAT "k free)", - os::available_memory() >> 10); + physical_memory_size_type phys_mem = physical_memory(); + st->print(", physical " PHYS_MEM_TYPE_FORMAT "k", + phys_mem >> 10); + physical_memory_size_type avail_mem = 0; + (void)os::available_memory(avail_mem); + st->print("(" PHYS_MEM_TYPE_FORMAT "k free)", + avail_mem >> 10); st->print(", swap " UINT64_FORMAT "k", ((jlong)si.totalswap * si.mem_unit) >> 10); st->print("(" UINT64_FORMAT "k free)", @@ -5388,7 +5409,7 @@ int os::get_core_path(char* buffer, size_t bufferSize) { if (core_pattern[0] == '|') { written = jio_snprintf(buffer, bufferSize, - "\"%s\" (or dumping to %s/core.%d)", + "\"%s\" (alternatively, falling back to %s/core.%d)", &core_pattern[1], p, current_process_id()); } else if (pid_pos != nullptr) { *pid_pos = '\0'; diff --git a/src/hotspot/os/linux/os_linux.hpp b/src/hotspot/os/linux/os_linux.hpp index 49f2777d1396..ed6c52aade44 100644 --- a/src/hotspot/os/linux/os_linux.hpp +++ b/src/hotspot/os/linux/os_linux.hpp @@ -51,11 +51,11 @@ class os::Linux { protected: - static julong _physical_memory; + static physical_memory_size_type _physical_memory; static pthread_t _main_thread; - static julong available_memory(); - static julong free_memory(); + static bool available_memory(physical_memory_size_type& value); + static bool free_memory(physical_memory_size_type& value); static void initialize_system_info(); @@ -127,7 +127,7 @@ class os::Linux { static address initial_thread_stack_bottom(void) { return _initial_thread_stack_bottom; } static uintptr_t initial_thread_stack_size(void) { return _initial_thread_stack_size; } - static julong physical_memory() { return _physical_memory; } + static physical_memory_size_type physical_memory() { return _physical_memory; } static julong host_swap(); static intptr_t* ucontext_get_sp(const ucontext_t* uc); diff --git a/src/hotspot/os/posix/os_posix.cpp b/src/hotspot/os/posix/os_posix.cpp index 7f95560a19e1..7d139712002c 100644 --- a/src/hotspot/os/posix/os_posix.cpp +++ b/src/hotspot/os/posix/os_posix.cpp @@ -105,49 +105,63 @@ static int clock_tics_per_sec = 100; size_t os::_os_min_stack_allowed = PTHREAD_STACK_MIN; // Check core dump limit and report possible place where core can be found -void os::check_dump_limit(char* buffer, size_t bufferSize) { +void os::check_core_dump_prerequisites(char* buffer, size_t bufferSize, bool check_only) { + stringStream buf(buffer, bufferSize); if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) { - jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line"); - VMError::record_coredump_status(buffer, false); - return; - } - - int n; - struct rlimit rlim; - bool success; - - char core_path[PATH_MAX]; - n = get_core_path(core_path, PATH_MAX); - - if (n <= 0) { - jio_snprintf(buffer, bufferSize, "core.%d (may not exist)", current_process_id()); - success = true; + buf.print("CreateCoredumpOnCrash is disabled from command line"); + VMError::record_coredump_status(buf.freeze(), false); + } else { + struct rlimit rlim; + bool success = true; + bool warn = true; + char core_path[PATH_MAX]; + if (get_core_path(core_path, PATH_MAX) <= 0) { + // In the warning message, let the user know. + if (check_only) { + buf.print("the core path couldn't be determined. It commonly defaults to "); + } + buf.print("core.%d%s", current_process_id(), check_only ? "" : " (may not exist)"); #ifdef LINUX - } else if (core_path[0] == '"') { // redirect to user process - jio_snprintf(buffer, bufferSize, "Core dumps may be processed with %s", core_path); - success = true; + } else if (core_path[0] == '"') { // redirect to user process + if (check_only) { + buf.print("core dumps may be further processed by the following: "); + } else { + buf.print("Determined by the following: "); + } + buf.print("%s", core_path); #endif - } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) { - jio_snprintf(buffer, bufferSize, "%s (may not exist)", core_path); - success = true; - } else { - switch(rlim.rlim_cur) { - case RLIM_INFINITY: - jio_snprintf(buffer, bufferSize, "%s", core_path); - success = true; - break; - case 0: - jio_snprintf(buffer, bufferSize, "Core dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again"); - success = false; - break; - default: - jio_snprintf(buffer, bufferSize, "%s (max size " UINT64_FORMAT " k). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", core_path, uint64_t(rlim.rlim_cur) / K); - success = true; - break; + } else if (getrlimit(RLIMIT_CORE, &rlim) != 0) { + if (check_only) { + buf.print("the rlimit couldn't be determined. If resource limits permit, the core dump will be located at "); + } + buf.print("%s%s", core_path, check_only ? "" : " (may not exist)"); + } else { + switch(rlim.rlim_cur) { + case RLIM_INFINITY: + buf.print("%s", core_path); + warn = false; + break; + case 0: + buf.print("%s dumps have been disabled. To enable core dumping, try \"ulimit -c unlimited\" before starting Java again", check_only ? "core" : "Core"); + success = false; + break; + default: + if (check_only) { + buf.print("core dumps are constrained "); + } else { + buf.print( "%s ", core_path); + } + buf.print( "(max size " UINT64_FORMAT " k). To ensure a full core dump, try \"ulimit -c unlimited\" before starting Java again", uint64_t(rlim.rlim_cur) / K); + break; + } + } + const char* result = buf.freeze(); + if (!check_only) { + VMError::record_coredump_status(result, success); + } else if (warn) { + warning("CreateCoredumpOnCrash specified, but %s", result); } } - - VMError::record_coredump_status(buffer, success); } int os::get_native_stack(address* stack, int frames, int toSkip) { diff --git a/src/hotspot/os/posix/perfMemory_posix.cpp b/src/hotspot/os/posix/perfMemory_posix.cpp index 7c39c5af466d..790db31348c3 100644 --- a/src/hotspot/os/posix/perfMemory_posix.cpp +++ b/src/hotspot/os/posix/perfMemory_posix.cpp @@ -112,6 +112,10 @@ static void save_memory_to_file(char* addr, size_t size) { result = ::close(fd); if (result == OS_ERR) { warning("Could not close %s: %s\n", destfile, os::strerror(errno)); + } else { + if (!successful_write) { + remove(destfile); + } } } FREE_C_HEAP_ARRAY(char, destfile); @@ -954,6 +958,7 @@ static int create_sharedmem_file(const char* dirname, const char* filename, size warning("Insufficient space for shared memory file:\n %s\nTry using the -Djava.io.tmpdir= option to select an alternate temp location.\n", filename); } result = OS_ERR; + remove(filename); break; } } diff --git a/src/hotspot/os/windows/os_windows.cpp b/src/hotspot/os/windows/os_windows.cpp index 2107b8365d07..a1ee6bc51d64 100644 --- a/src/hotspot/os/windows/os_windows.cpp +++ b/src/hotspot/os/windows/os_windows.cpp @@ -832,25 +832,30 @@ jlong os::elapsed_frequency() { } -julong os::available_memory() { - return win32::available_memory(); +bool os::available_memory(physical_memory_size_type& value) { + return win32::available_memory(value); } -julong os::free_memory() { - return win32::available_memory(); +bool os::free_memory(physical_memory_size_type& value) { + return win32::available_memory(value); } -julong os::win32::available_memory() { +bool os::win32::available_memory(physical_memory_size_type& value) { // Use GlobalMemoryStatusEx() because GlobalMemoryStatus() may return incorrect // value if total memory is larger than 4GB MEMORYSTATUSEX ms; ms.dwLength = sizeof(ms); - GlobalMemoryStatusEx(&ms); - - return (julong)ms.ullAvailPhys; + BOOL res = GlobalMemoryStatusEx(&ms); + if (res == TRUE) { + value = static_cast(ms.ullAvailPhys); + return true; + } else { + assert(false, "GlobalMemoryStatusEx failed in os::win32::available_memory(): %lu", ::GetLastError()); + return false; + } } -julong os::physical_memory() { +physical_memory_size_type os::physical_memory() { return win32::physical_memory(); } @@ -1269,38 +1274,50 @@ void os::shutdown() { static HANDLE dumpFile = nullptr; -// Check if dump file can be created. -void os::check_dump_limit(char* buffer, size_t buffsz) { - bool status = true; +// Check if core dump is active and if a core dump file can be created +void os::check_core_dump_prerequisites(char* buffer, size_t bufferSize, bool check_only) { if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && !CreateCoredumpOnCrash) { - jio_snprintf(buffer, buffsz, "CreateCoredumpOnCrash is disabled from command line"); - status = false; - } - + jio_snprintf(buffer, bufferSize, "CreateCoredumpOnCrash is disabled from command line"); + VMError::record_coredump_status(buffer, false); + } else { + bool success = true; + bool warn = true; #ifndef ASSERT - if (!os::win32::is_windows_server() && FLAG_IS_DEFAULT(CreateCoredumpOnCrash)) { - jio_snprintf(buffer, buffsz, "Minidumps are not enabled by default on client versions of Windows"); - status = false; - } + if (!os::win32::is_windows_server() && FLAG_IS_DEFAULT(CreateCoredumpOnCrash)) { + jio_snprintf(buffer, bufferSize, "Minidumps are not enabled by default on client versions of Windows"); + success = false; + warn = true; + } #endif - if (status) { - const char* cwd = get_current_directory(nullptr, 0); - int pid = current_process_id(); - if (cwd != nullptr) { - jio_snprintf(buffer, buffsz, "%s\\hs_err_pid%u.mdmp", cwd, pid); - } else { - jio_snprintf(buffer, buffsz, ".\\hs_err_pid%u.mdmp", pid); + if (success) { + if (!check_only) { + const char* cwd = get_current_directory(nullptr, 0); + int pid = current_process_id(); + if (cwd != nullptr) { + jio_snprintf(buffer, bufferSize, "%s\\hs_err_pid%u.mdmp", cwd, pid); + } else { + jio_snprintf(buffer, bufferSize, ".\\hs_err_pid%u.mdmp", pid); + } + + if (dumpFile == nullptr && + (dumpFile = CreateFile(buffer, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)) + == INVALID_HANDLE_VALUE) { + jio_snprintf(buffer, bufferSize, "Failed to create minidump file (0x%x).", GetLastError()); + success = false; + } + } else { + // For now on Windows, there are no more checks that we can do + warn = false; + } } - if (dumpFile == nullptr && - (dumpFile = CreateFile(buffer, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)) - == INVALID_HANDLE_VALUE) { - jio_snprintf(buffer, buffsz, "Failed to create minidump file (0x%x).", GetLastError()); - status = false; + if (!check_only) { + VMError::record_coredump_status(buffer, success); + } else if (warn) { + warning("CreateCoredumpOnCrash specified, but %s", buffer); } } - VMError::record_coredump_status(buffer, status); } void os::abort(bool dump_core, void* siginfo, const void* context) { @@ -4062,25 +4079,25 @@ int os::current_process_id() { return (_initial_pid ? _initial_pid : _getpid()); } -int os::win32::_processor_type = 0; +int os::win32::_processor_type = 0; // Processor level is not available on non-NT systems, use vm_version instead -int os::win32::_processor_level = 0; -julong os::win32::_physical_memory = 0; +int os::win32::_processor_level = 0; +physical_memory_size_type os::win32::_physical_memory = 0; -bool os::win32::_is_windows_server = false; +bool os::win32::_is_windows_server = false; // 6573254 // Currently, the bug is observed across all the supported Windows releases, // including the latest one (as of this writing - Windows Server 2012 R2) -bool os::win32::_has_exit_bug = true; +bool os::win32::_has_exit_bug = true; -int os::win32::_major_version = 0; -int os::win32::_minor_version = 0; -int os::win32::_build_number = 0; -int os::win32::_build_minor = 0; +int os::win32::_major_version = 0; +int os::win32::_minor_version = 0; +int os::win32::_build_number = 0; +int os::win32::_build_minor = 0; -bool os::win32::_processor_group_warning_displayed = false; -bool os::win32::_job_object_processor_group_warning_displayed = false; +bool os::win32::_processor_group_warning_displayed = false; +bool os::win32::_job_object_processor_group_warning_displayed = false; void getWindowsInstallationType(char* buffer, int bufferSize) { HKEY hKey; @@ -4295,8 +4312,11 @@ void os::win32::initialize_system_info() { // also returns dwAvailPhys (free physical memory bytes), dwTotalVirtual, dwAvailVirtual, // dwMemoryLoad (% of memory in use) - GlobalMemoryStatusEx(&ms); - _physical_memory = ms.ullTotalPhys; + BOOL res = GlobalMemoryStatusEx(&ms); + if (res != TRUE) { + assert(false, "GlobalMemoryStatusEx failed in os::win32::initialize_system_info(): %lu", ::GetLastError()); + } + _physical_memory = static_cast(ms.ullTotalPhys); if (FLAG_IS_DEFAULT(MaxRAM)) { // Adjust MaxRAM according to the maximum virtual address space available. diff --git a/src/hotspot/os/windows/os_windows.hpp b/src/hotspot/os/windows/os_windows.hpp index c4e5483ce8e3..abbccbf234cb 100644 --- a/src/hotspot/os/windows/os_windows.hpp +++ b/src/hotspot/os/windows/os_windows.hpp @@ -38,18 +38,18 @@ class os::win32 { friend class os; protected: - static int _processor_type; - static int _processor_level; - static julong _physical_memory; - static bool _is_windows_server; - static bool _has_exit_bug; - static bool _processor_group_warning_displayed; - static bool _job_object_processor_group_warning_displayed; - - static int _major_version; - static int _minor_version; - static int _build_number; - static int _build_minor; + static int _processor_type; + static int _processor_level; + static physical_memory_size_type _physical_memory; + static bool _is_windows_server; + static bool _has_exit_bug; + static bool _processor_group_warning_displayed; + static bool _job_object_processor_group_warning_displayed; + + static int _major_version; + static int _minor_version; + static int _build_number; + static int _build_minor; static void print_windows_version(outputStream* st); static void print_uptime_info(outputStream* st); @@ -102,9 +102,9 @@ class os::win32 { static int processor_level() { return _processor_level; } - static julong available_memory(); - static julong free_memory(); - static julong physical_memory() { return _physical_memory; } + static bool available_memory(physical_memory_size_type& value); + static bool free_memory(physical_memory_size_type& value); + static physical_memory_size_type physical_memory() { return _physical_memory; } // load dll from Windows system directory or Windows directory static HINSTANCE load_Windows_dll(const char* name, char *ebuf, int ebuflen); diff --git a/src/hotspot/share/compiler/compileBroker.cpp b/src/hotspot/share/compiler/compileBroker.cpp index b6b681472506..63378b244775 100644 --- a/src/hotspot/share/compiler/compileBroker.cpp +++ b/src/hotspot/share/compiler/compileBroker.cpp @@ -1033,7 +1033,9 @@ void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) { if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return; // Now, we do the more expensive operations. - julong free_memory = os::free_memory(); + physical_memory_size_type free_memory = 0; + // Return value ignored - defaulting to 0 on failure. + (void)os::free_memory(free_memory); // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All). size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled), available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled); diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp index 80d6493963fa..db7b849993d0 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.cpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.cpp @@ -30,6 +30,7 @@ #include "code/icBuffer.hpp" #include "compiler/oopMap.hpp" #include "gc/g1/g1Allocator.inline.hpp" +#include "gc/g1/g1Analytics.hpp" #include "gc/g1/g1Arguments.hpp" #include "gc/g1/g1BarrierSet.hpp" #include "gc/g1/g1BatchedTask.hpp" @@ -492,6 +493,13 @@ HeapWord* G1CollectedHeap::attempt_allocation_slow(uint node_index, size_t word_ gclocker_retry_count += 1; } + // Has the gc overhead limit been reached in the meantime? If so, this mutator + // should receive null even when unsuccessfully scheduling a collection as well + // for global consistency. + if (gc_overhead_limit_exceeded()) { + return nullptr; + } + // We can reach here if we were unsuccessful in scheduling a // collection (because another thread beat us to it) or if we were // stalled due to the GC locker. In either can we should retry the @@ -760,7 +768,12 @@ HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) { GCLocker::stall_until_clear(); gclocker_retry_count += 1; } - + // Has the gc overhead limit been reached in the meantime? If so, this mutator + // should receive null even when unsuccessfully scheduling a collection as well + // for global consistency. + if (gc_overhead_limit_exceeded()) { + return nullptr; + } // We can reach here if we were unsuccessful in scheduling a // collection (because another thread beat us to it) or if we were @@ -981,27 +994,64 @@ void G1CollectedHeap::resize_heap_if_necessary() { } } +void G1CollectedHeap::update_gc_overhead_counter() { + assert(SafepointSynchronize::is_at_safepoint(), "precondition"); + + if (!UseGCOverheadLimit) { + return; + } + + bool gc_time_over_limit = (_policy->analytics()->long_term_pause_time_ratio() * 100) >= GCTimeLimit; + double free_space_percent = percent_of(num_free_or_available_regions() * HeapRegion::GrainBytes, max_capacity()); + bool free_space_below_limit = free_space_percent < GCHeapFreeLimit; + + log_debug(gc)("GC Overhead Limit: GC Time %f Free Space %f Counter %zu", + (_policy->analytics()->long_term_pause_time_ratio() * 100), + free_space_percent, + _gc_overhead_counter); + + if (gc_time_over_limit && free_space_below_limit) { + _gc_overhead_counter++; + } else { + _gc_overhead_counter = 0; + } +} + +bool G1CollectedHeap::gc_overhead_limit_exceeded() { + return _gc_overhead_counter >= GCOverheadLimitThreshold; +} + HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size, bool do_gc, bool maximal_compaction, bool expect_null_mutator_alloc_region, bool* gc_succeeded) { *gc_succeeded = true; - // Let's attempt the allocation first. - HeapWord* result = - attempt_allocation_at_safepoint(word_size, - expect_null_mutator_alloc_region); - if (result != nullptr) { - return result; - } + // Skip allocation if GC overhead limit has been exceeded to let the mutator run + // into an OOME. It can either exit "gracefully" or try to free up memory asap. + // For the latter situation, keep running GCs. If the mutator frees up enough + // memory quickly enough, the overhead(s) will go below the threshold(s) again + // and the VM may continue running. + // If we did not continue garbage collections, the (gc overhead) limit may decrease + // enough by itself to not count as exceeding the limit any more, in the worst + // case bouncing back-and-forth all the time. + if (!gc_overhead_limit_exceeded()) { + // Let's attempt the allocation first. + HeapWord* result = + attempt_allocation_at_safepoint(word_size, + expect_null_mutator_alloc_region); + if (result != nullptr) { + return result; + } - // In a G1 heap, we're supposed to keep allocation from failing by - // incremental pauses. Therefore, at least for now, we'll favor - // expansion over collection. (This might change in the future if we can - // do something smarter than full collection to satisfy a failed alloc.) - result = expand_and_allocate(word_size); - if (result != nullptr) { - return result; + // In a G1 heap, we're supposed to keep allocation from failing by + // incremental pauses. Therefore, at least for now, we'll favor + // expansion over collection. (This might change in the future if we can + // do something smarter than full collection to satisfy a failed alloc.) + result = expand_and_allocate(word_size); + if (result != nullptr) { + return result; + } } if (do_gc) { @@ -1025,6 +1075,10 @@ HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size, bool* succeeded) { assert_at_safepoint_on_vm_thread(); + // Update GC overhead limits after the initial garbage collection leading to this + // allocation attempt. + update_gc_overhead_counter(); + // Attempts to allocate followed by Full GC. HeapWord* result = satisfy_failed_allocation_helper(word_size, @@ -1062,6 +1116,10 @@ HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size, assert(!soft_ref_policy()->should_clear_all_soft_refs(), "Flag should have been handled and cleared prior to this point"); + if (gc_overhead_limit_exceeded()) { + log_info(gc)("GC Overhead Limit exceeded too often (%zu).", GCOverheadLimitThreshold); + } + // What else? We might try synchronous finalization later. If the total // space available is large enough for the allocation, then a more // complete compaction phase than we've tried so far might be @@ -1230,6 +1288,7 @@ class HumongousRegionSetChecker : public HeapRegionSetChecker { G1CollectedHeap::G1CollectedHeap() : CollectedHeap(), + _gc_overhead_counter(0), _service_thread(nullptr), _periodic_gc_task(nullptr), _free_arena_memory_task(nullptr), diff --git a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp index bd521c347bf7..de0de0339ec5 100644 --- a/src/hotspot/share/gc/g1/g1CollectedHeap.hpp +++ b/src/hotspot/share/gc/g1/g1CollectedHeap.hpp @@ -169,6 +169,17 @@ class G1CollectedHeap : public CollectedHeap { friend class G1CheckRegionAttrTableClosure; private: + // GC Overhead Limit functionality related members. + // + // The goal is to return null for allocations prematurely (before really going + // OOME) in case both GC CPU usage (>= GCTimeLimit) and not much available free + // memory (<= GCHeapFreeLimit) so that applications can exit gracefully or try + // to keep running by easing off memory. + uintx _gc_overhead_counter; // The number of consecutive garbage collections we were over the limits. + + void update_gc_overhead_counter(); + bool gc_overhead_limit_exceeded(); + G1ServiceThread* _service_thread; G1ServiceTask* _periodic_gc_task; G1MonotonicArenaFreeMemoryTask* _free_arena_memory_task; diff --git a/src/hotspot/share/gc/shared/gcInitLogger.cpp b/src/hotspot/share/gc/shared/gcInitLogger.cpp index 1dfc27c53337..5956122323d4 100644 --- a/src/hotspot/share/gc/shared/gcInitLogger.cpp +++ b/src/hotspot/share/gc/shared/gcInitLogger.cpp @@ -63,8 +63,8 @@ void GCInitLogger::print_cpu() { } void GCInitLogger::print_memory() { - julong memory = os::physical_memory(); - log_info_p(gc, init)("Memory: " JULONG_FORMAT "%s", + physical_memory_size_type memory = os::physical_memory(); + log_info_p(gc, init)("Memory: " PHYS_MEM_TYPE_FORMAT "%s", byte_size_in_proper_unit(memory), proper_unit_for_byte_size(memory)); } diff --git a/src/hotspot/share/gc/shared/gc_globals.hpp b/src/hotspot/share/gc/shared/gc_globals.hpp index 5d7202685401..98cd6137e985 100644 --- a/src/hotspot/share/gc/shared/gc_globals.hpp +++ b/src/hotspot/share/gc/shared/gc_globals.hpp @@ -477,7 +477,7 @@ "Estimate of footprint other than Java Heap") \ range(0, max_uintx) \ \ - product(bool, UseGCOverheadLimit, true, \ + product(bool, UseGCOverheadLimit, falseInDebug, \ "Use policy to limit of proportion of time spent in GC " \ "before an OutOfMemory error is thrown") \ \ diff --git a/src/hotspot/share/gc/x/xLargePages.cpp b/src/hotspot/share/gc/x/xLargePages.cpp index 13da763c6a39..0afb4ac6d702 100644 --- a/src/hotspot/share/gc/x/xLargePages.cpp +++ b/src/hotspot/share/gc/x/xLargePages.cpp @@ -31,7 +31,8 @@ XLargePages::State XLargePages::_state; void XLargePages::initialize() { pd_initialize(); - log_info_p(gc, init)("Memory: " JULONG_FORMAT "M", os::physical_memory() / M); + const size_t memory = os::physical_memory(); + log_info_p(gc, init)("Memory: " PROPERFMT, PROPERFMTARGS(memory)); log_info_p(gc, init)("Large Page Support: %s", to_string()); } diff --git a/src/hotspot/share/gc/z/zLargePages.cpp b/src/hotspot/share/gc/z/zLargePages.cpp index 88656d153811..9a35e246f4b6 100644 --- a/src/hotspot/share/gc/z/zLargePages.cpp +++ b/src/hotspot/share/gc/z/zLargePages.cpp @@ -31,7 +31,8 @@ ZLargePages::State ZLargePages::_state; void ZLargePages::initialize() { pd_initialize(); - log_info_p(gc, init)("Memory: " JULONG_FORMAT "M", os::physical_memory() / M); + const size_t memory = static_cast(os::physical_memory()); + log_info_p(gc, init)("Memory: " PROPERFMT, PROPERFMTARGS(memory)); log_info_p(gc, init)("Large Page Support: %s", to_string()); } diff --git a/src/hotspot/share/jfr/jni/jfrJniMethod.cpp b/src/hotspot/share/jfr/jni/jfrJniMethod.cpp index 7157c346db01..e78bd11fb647 100644 --- a/src/hotspot/share/jfr/jni/jfrJniMethod.cpp +++ b/src/hotspot/share/jfr/jni/jfrJniMethod.cpp @@ -402,9 +402,9 @@ JVM_ENTRY_NO_ENV(jlong, jfr_host_total_memory(JNIEnv* env, jobject jvm)) #ifdef LINUX // We want the host memory, not the container limit. // os::physical_memory() would return the container limit. - return os::Linux::physical_memory(); + return static_cast(os::Linux::physical_memory()); #else - return os::physical_memory(); + return static_cast(os::physical_memory()); #endif JVM_END diff --git a/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.cpp b/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.cpp index 4ba2e3329f81..d2d3fec79e38 100644 --- a/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.cpp +++ b/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.cpp @@ -35,6 +35,7 @@ #include "memory/resourceArea.hpp" #include "oops/access.inline.hpp" #include "oops/oop.inline.hpp" +#include "runtime/os.hpp" #include "utilities/align.hpp" UnifiedOopRef DFSClosure::_reference_stack[max_dfs_depth]; @@ -68,9 +69,27 @@ void DFSClosure::find_leaks_from_root_set(EdgeStore* edge_store, rs.process(); } +static address calculate_headroom_limit() { + static constexpr size_t required_headroom = K * 64; + const Thread* const t = Thread::current_or_null(); + return t->stack_end() + required_headroom; +} + DFSClosure::DFSClosure(EdgeStore* edge_store, JFRBitSet* mark_bits, const Edge* start_edge) :_edge_store(edge_store), _mark_bits(mark_bits), _start_edge(start_edge), - _max_depth(max_dfs_depth), _depth(0), _ignore_root_set(false) { + _max_depth(max_dfs_depth), _depth(0), _ignore_root_set(false), + _headroom_limit(calculate_headroom_limit()) { +} + +bool DFSClosure::have_headroom() const { + const address sp = (address) os::current_stack_pointer(); +#ifdef ASSERT + const Thread* const t = Thread::current_or_null(); + assert(t->is_VM_thread(), "invariant"); + assert(t->is_in_full_stack(_headroom_limit), "invariant"); + assert(t->is_in_full_stack(sp), "invariant"); +#endif + return sp > _headroom_limit; } void DFSClosure::closure_impl(UnifiedOopRef reference, const oop pointee) { @@ -98,7 +117,7 @@ void DFSClosure::closure_impl(UnifiedOopRef reference, const oop pointee) { } } assert(_max_depth >= 1, "invariant"); - if (_depth < _max_depth - 1) { + if (_depth < _max_depth - 1 && have_headroom()) { _depth++; pointee->oop_iterate(this); assert(_depth > 0, "invariant"); diff --git a/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.hpp b/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.hpp index be0cd2a5d7eb..a22b5137380f 100644 --- a/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.hpp +++ b/src/hotspot/share/jfr/leakprofiler/chains/dfsClosure.hpp @@ -46,12 +46,15 @@ class DFSClosure : public BasicOopIterateClosure { size_t _max_depth; size_t _depth; bool _ignore_root_set; + const address _headroom_limit; DFSClosure(EdgeStore* edge_store, JFRBitSet* mark_bits, const Edge* start_edge); void add_chain(); void closure_impl(UnifiedOopRef reference, const oop pointee); + bool have_headroom() const; + public: virtual ReferenceIterationMode reference_iteration_mode() { return DO_FIELDS_EXCEPT_REFERENT; } diff --git a/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.cpp b/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.cpp index 311c54becd8e..465491cd1d5a 100644 --- a/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.cpp +++ b/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.cpp @@ -236,12 +236,25 @@ void ObjectSampler::add(HeapWord* obj, size_t allocated, traceid thread_id, bool // quick reject, will not fit return; } - sample = _list->reuse(_priority_queue->pop()); + ObjectSample* popped = _priority_queue->pop(); + size_t popped_span = popped->span(); + ObjectSample* previous = popped->prev(); + sample = _list->reuse(popped); + assert(sample != nullptr, "invariant"); + if (previous != nullptr) { + push_span(previous, popped_span); + sample->set_span(span); + } else { + // The removed sample was the youngest sample in the list, which means the new sample is now the youngest + // sample. It should cover the spans of both. + sample->set_span(span + popped_span); + } } else { sample = _list->get(); + assert(sample != nullptr, "invariant"); + sample->set_span(span); } - assert(sample != nullptr, "invariant"); sample->set_thread_id(thread_id); if (virtual_thread) { sample->set_thread_is_virtual(); @@ -255,7 +268,6 @@ void ObjectSampler::add(HeapWord* obj, size_t allocated, traceid thread_id, bool sample->set_stack_trace_hash(stacktrace_hash); } - sample->set_span(allocated); sample->set_object(cast_to_oop(obj)); sample->set_allocated(allocated); sample->set_allocation_time(JfrTicks::now()); @@ -282,14 +294,18 @@ void ObjectSampler::remove_dead(ObjectSample* sample) { ObjectSample* const previous = sample->prev(); // push span onto previous if (previous != nullptr) { - _priority_queue->remove(previous); - previous->add_span(sample->span()); - _priority_queue->push(previous); + push_span(previous, sample->span()); } _priority_queue->remove(sample); _list->release(sample); } +void ObjectSampler::push_span(ObjectSample* sample, size_t span) { + _priority_queue->remove(sample); + sample->add_span(span); + _priority_queue->push(sample); +} + ObjectSample* ObjectSampler::last() const { return _list->last(); } diff --git a/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.hpp b/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.hpp index 3789227b6008..6ae1b0a06833 100644 --- a/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.hpp +++ b/src/hotspot/share/jfr/leakprofiler/sampling/objectSampler.hpp @@ -64,6 +64,7 @@ class ObjectSampler : public CHeapObj { void add(HeapWord* object, size_t size, traceid thread_id, bool virtual_thread, const JfrBlobHandle& bh, JavaThread* thread); void scavenge(); void remove_dead(ObjectSample* sample); + void push_span(ObjectSample* sample, size_t span); const ObjectSample* item_at(int index) const; ObjectSample* item_at(int index); diff --git a/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp b/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp index ff52b4104fdb..80a160ab84ba 100644 --- a/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp +++ b/src/hotspot/share/jfr/periodic/jfrPeriodic.cpp @@ -515,10 +515,13 @@ TRACE_REQUEST_FUNC(ThreadAllocationStatistics) { * the total memory reported is the amount of memory configured for the guest OS by the hypervisor. */ TRACE_REQUEST_FUNC(PhysicalMemory) { - u8 totalPhysicalMemory = os::physical_memory(); + physical_memory_size_type totalPhysicalMemory = os::physical_memory(); EventPhysicalMemory event; event.set_totalSize(totalPhysicalMemory); - event.set_usedSize(totalPhysicalMemory - os::available_memory()); + physical_memory_size_type avail_mem = 0; + // Return value ignored - defaulting to 0 on failure. + (void)os::available_memory(avail_mem); + event.set_usedSize(totalPhysicalMemory - avail_mem); event.commit(); } diff --git a/src/hotspot/share/jfr/recorder/jfrRecorder.cpp b/src/hotspot/share/jfr/recorder/jfrRecorder.cpp index 6f2f9a5857d8..7f49c06bd58a 100644 --- a/src/hotspot/share/jfr/recorder/jfrRecorder.cpp +++ b/src/hotspot/share/jfr/recorder/jfrRecorder.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -227,7 +227,7 @@ bool JfrRecorder::on_create_vm_2() { } bool JfrRecorder::on_create_vm_3() { - assert(JvmtiEnvBase::get_phase() == JVMTI_PHASE_LIVE, "invalid init sequence"); + JVMTI_ONLY( assert(JvmtiEnvBase::get_phase() == JVMTI_PHASE_LIVE, "invalid init sequence, phase is %d", (int)JvmtiEnvBase::get_phase()); ) return Arguments::is_dumping_archive() || launch_command_line_recordings(JavaThread::current()); } diff --git a/src/hotspot/share/prims/jvmtiAgentList.cpp b/src/hotspot/share/prims/jvmtiAgentList.cpp index 2a0f71728888..2857927ac31a 100644 --- a/src/hotspot/share/prims/jvmtiAgentList.cpp +++ b/src/hotspot/share/prims/jvmtiAgentList.cpp @@ -200,6 +200,11 @@ void JvmtiAgentList::load_xrun_agents() { // Invokes Agent_OnAttach for agents loaded dynamically during runtime. void JvmtiAgentList::load_agent(const char* agent_name, bool is_absolute_path, const char* options, outputStream* st) { + if (JvmtiEnvBase::get_phase() != JVMTI_PHASE_LIVE) { + st->print_cr("Dynamic agent loading is only permitted in the live phase"); + return; + } + JvmtiAgent* const agent = new JvmtiAgent(agent_name, options, is_absolute_path, /* dynamic agent */ true); if (agent->load(st)) { add(agent); diff --git a/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp b/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp index 566406433b7f..ccebb272fa50 100644 --- a/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp +++ b/src/hotspot/share/prims/jvmtiClassFileReconstituter.cpp @@ -992,6 +992,11 @@ void JvmtiClassFileReconstituter::write_u8(u8 x) { void JvmtiClassFileReconstituter::copy_bytecodes(const methodHandle& mh, unsigned char* bytecodes) { + // We must copy bytecodes only from linked classes. + // Being linked guarantees we are not getting bytecodes at + // the same time the linking process is rewriting them. + guarantee(mh->method_holder()->is_linked(), "Bytecodes must be copied from a linked class"); + // use a BytecodeStream to iterate over the bytecodes. JVM/fast bytecodes // and the breakpoint bytecode are converted to their original bytecodes. diff --git a/src/hotspot/share/prims/jvmtiEnv.cpp b/src/hotspot/share/prims/jvmtiEnv.cpp index e3f64b59325a..ed3eeeb36c8b 100644 --- a/src/hotspot/share/prims/jvmtiEnv.cpp +++ b/src/hotspot/share/prims/jvmtiEnv.cpp @@ -452,6 +452,18 @@ JvmtiEnv::RetransformClasses(jint class_count, const jclass* classes) { InstanceKlass* ik = InstanceKlass::cast(klass); if (ik->get_cached_class_file_bytes() == nullptr) { + // Link the class to avoid races with the rewriter. This will call the verifier also + // on the class. Linking is also done in VM_RedefineClasses below, but we need + // to keep that for other VM_RedefineClasses callers. + JavaThread* THREAD = current_thread; + ik->link_class(THREAD); + if (HAS_PENDING_EXCEPTION) { + // Retransform/JVMTI swallows error messages. Using this class will rerun the verifier in a context + // that propagates the VerifyError, if thrown. + CLEAR_PENDING_EXCEPTION; + return JVMTI_ERROR_INVALID_CLASS; + } + // Not cached, we need to reconstitute the class file from the // VM representation. We don't attach the reconstituted class // bytes to the InstanceKlass here because they have not been @@ -3600,7 +3612,8 @@ jvmtiError JvmtiEnv::GetBytecodes(Method* method, jint* bytecode_count_ptr, unsigned char** bytecodes_ptr) { NULL_CHECK(method, JVMTI_ERROR_INVALID_METHODID); - methodHandle mh(Thread::current(), method); + JavaThread* current_thread = JavaThread::current(); + methodHandle mh(current_thread, method); jint size = (jint)mh->code_size(); jvmtiError err = allocate(size, bytecodes_ptr); if (err != JVMTI_ERROR_NONE) { @@ -3609,6 +3622,13 @@ JvmtiEnv::GetBytecodes(Method* method, jint* bytecode_count_ptr, unsigned char** (*bytecode_count_ptr) = size; // get byte codes + // Make sure the class is verified and rewritten first. + JavaThread* THREAD = current_thread; + mh->method_holder()->link_class(THREAD); + if (HAS_PENDING_EXCEPTION) { + CLEAR_PENDING_EXCEPTION; + return JVMTI_ERROR_INVALID_CLASS; + } JvmtiClassFileReconstituter::copy_bytecodes(mh, *bytecodes_ptr); return JVMTI_ERROR_NONE; diff --git a/src/hotspot/share/prims/jvmtiRedefineClasses.cpp b/src/hotspot/share/prims/jvmtiRedefineClasses.cpp index 000c1207e70e..009f3972fe13 100644 --- a/src/hotspot/share/prims/jvmtiRedefineClasses.cpp +++ b/src/hotspot/share/prims/jvmtiRedefineClasses.cpp @@ -1375,10 +1375,12 @@ jvmtiError VM_RedefineClasses::load_new_class_versions() { // constant pools HandleMark hm(current); InstanceKlass* the_class = get_ik(_class_defs[i].klass); - + physical_memory_size_type avail_mem = 0; + // Return value ignored - defaulting to 0 on failure. + (void)os::available_memory(avail_mem); log_debug(redefine, class, load) - ("loading name=%s kind=%d (avail_mem=" UINT64_FORMAT "K)", - the_class->external_name(), _class_load_kind, os::available_memory() >> 10); + ("loading name=%s kind=%d (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)", + the_class->external_name(), _class_load_kind, avail_mem >> 10); ClassFileStream st((u1*)_class_defs[i].class_bytes, _class_defs[i].class_byte_count, @@ -1543,9 +1545,10 @@ jvmtiError VM_RedefineClasses::load_new_class_versions() { return JVMTI_ERROR_INTERNAL; } } - + // Return value ignored - defaulting to 0 on failure. + (void)os::available_memory(avail_mem); log_debug(redefine, class, load) - ("loaded name=%s (avail_mem=" UINT64_FORMAT "K)", the_class->external_name(), os::available_memory() >> 10); + ("loaded name=%s (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)", the_class->external_name(), avail_mem >> 10); } return JVMTI_ERROR_NONE; @@ -4453,9 +4456,12 @@ void VM_RedefineClasses::redefine_single_class(Thread* current, jclass the_jclas ResourceMark rm(current); // increment the classRedefinedCount field in the_class and in any // direct and indirect subclasses of the_class + physical_memory_size_type avail_mem = 0; + // Return value ignored - defaulting to 0 on failure. + (void)os::available_memory(avail_mem); log_info(redefine, class, load) - ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)", - the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10); + ("redefined name=%s, count=%d (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)", + the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), avail_mem >> 10); Events::log_redefinition(current, "redefined class name=%s, count=%d", the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror())); diff --git a/src/hotspot/share/prims/whitebox.cpp b/src/hotspot/share/prims/whitebox.cpp index c1dbb482f5fb..3288f5f27d61 100644 --- a/src/hotspot/share/prims/whitebox.cpp +++ b/src/hotspot/share/prims/whitebox.cpp @@ -2408,8 +2408,8 @@ WB_END // Physical memory of the host machine (including containers) WB_ENTRY(jlong, WB_HostPhysicalMemory(JNIEnv* env, jobject o)) - LINUX_ONLY(return os::Linux::physical_memory();) - return os::physical_memory(); + LINUX_ONLY(return static_cast(os::Linux::physical_memory());) + return static_cast(os::physical_memory()); WB_END // Physical swap of the host machine (including containers), Linux only. diff --git a/src/hotspot/share/runtime/arguments.cpp b/src/hotspot/share/runtime/arguments.cpp index ece795dd9de8..0076b9f0bf55 100644 --- a/src/hotspot/share/runtime/arguments.cpp +++ b/src/hotspot/share/runtime/arguments.cpp @@ -1552,13 +1552,13 @@ void Arguments::set_heap_size() { !FLAG_IS_DEFAULT(MaxRAM)); if (override_coop_limit) { if (FLAG_IS_DEFAULT(MaxRAM)) { - phys_mem = os::physical_memory(); + phys_mem = static_cast(os::physical_memory()); FLAG_SET_ERGO(MaxRAM, (uint64_t)phys_mem); } else { phys_mem = (julong)MaxRAM; } } else { - phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(os::physical_memory(), (julong)MaxRAM) + phys_mem = FLAG_IS_DEFAULT(MaxRAM) ? MIN2(static_cast(os::physical_memory()), (julong)MaxRAM) : (julong)MaxRAM; } @@ -1694,7 +1694,8 @@ jint Arguments::set_aggressive_heap_flags() { // Thus, we need to make sure we're using a julong for intermediate // calculations. julong initHeapSize; - julong total_memory = os::physical_memory(); + physical_memory_size_type phys_mem = os::physical_memory(); + julong total_memory = static_cast(phys_mem); if (total_memory < (julong) 256 * M) { jio_fprintf(defaultStream::error_stream(), diff --git a/src/hotspot/share/runtime/os.cpp b/src/hotspot/share/runtime/os.cpp index fd44971fe63b..77f6ef463bf3 100644 --- a/src/hotspot/share/runtime/os.cpp +++ b/src/hotspot/share/runtime/os.cpp @@ -1174,12 +1174,13 @@ void os::print_summary_info(outputStream* st, char* buf, size_t buflen) { #endif // PRODUCT get_summary_cpu_info(buf, buflen); st->print("%s, ", buf); - size_t mem = physical_memory()/G; + physical_memory_size_type phys_mem = physical_memory(); + physical_memory_size_type mem = phys_mem/G; if (mem == 0) { // for low memory systems - mem = physical_memory()/M; - st->print("%d cores, " SIZE_FORMAT "M, ", processor_count(), mem); + mem = phys_mem/M; + st->print("%d cores, " PHYS_MEM_TYPE_FORMAT "M, ", processor_count(), mem); } else { - st->print("%d cores, " SIZE_FORMAT "G, ", processor_count(), mem); + st->print("%d cores, " PHYS_MEM_TYPE_FORMAT "G, ", processor_count(), mem); } get_summary_os_info(buf, buflen); st->print_raw(buf); @@ -1900,17 +1901,17 @@ bool os::is_server_class_machine() { return true; } // Then actually look at the machine - bool result = false; - const unsigned int server_processors = 2; - const julong server_memory = 2UL * G; + bool result = false; + const unsigned int server_processors = 2; + const physical_memory_size_type server_memory = 2UL * G; // We seem not to get our full complement of memory. // We allow some part (1/8?) of the memory to be "missing", // based on the sizes of DIMMs, and maybe graphics cards. - const julong missing_memory = 256UL * M; - + const physical_memory_size_type missing_memory = 256UL * M; + physical_memory_size_type phys_mem = os::physical_memory(); /* Is this a server class machine? */ if ((os::active_processor_count() >= (int)server_processors) && - (os::physical_memory() >= (server_memory - missing_memory))) { + (phys_mem >= server_memory - missing_memory)) { const unsigned int logical_processors = VM_Version::logical_processors_per_package(); if (logical_processors > 1) { diff --git a/src/hotspot/share/runtime/os.hpp b/src/hotspot/share/runtime/os.hpp index 13629829d9e2..8186d23b4726 100644 --- a/src/hotspot/share/runtime/os.hpp +++ b/src/hotspot/share/runtime/os.hpp @@ -320,10 +320,10 @@ class os: AllStatic { // For example, on Linux, "available" memory (`MemAvailable` in `/proc/meminfo`) is greater // than "free" memory (`MemFree` in `/proc/meminfo`) because Linux can free memory // aggressively (e.g. clear caches) so that it becomes available. - static julong available_memory(); - static julong free_memory(); + [[nodiscard]] static bool available_memory(physical_memory_size_type& value); + [[nodiscard]] static bool free_memory(physical_memory_size_type& value); - static julong physical_memory(); + static physical_memory_size_type physical_memory(); static bool has_allocatable_memory_limit(size_t* limit); static bool is_server_class_machine(); @@ -925,7 +925,7 @@ class os: AllStatic { // provided buffer as a scratch buffer. The status message which will be written // into the error log either is file location or a short error message, depending // on the checking result. - static void check_dump_limit(char* buffer, size_t bufferSize); + static void check_core_dump_prerequisites(char* buffer, size_t bufferSize, bool check_only = false); // Get the default path to the core file // Returns the length of the string diff --git a/src/hotspot/share/runtime/thread.cpp b/src/hotspot/share/runtime/thread.cpp index ce4c3b9cc14d..b0c43d146245 100644 --- a/src/hotspot/share/runtime/thread.cpp +++ b/src/hotspot/share/runtime/thread.cpp @@ -36,6 +36,8 @@ #include "memory/resourceArea.hpp" #include "oops/oop.inline.hpp" #include "runtime/atomic.hpp" +#include "runtime/globals.hpp" +#include "runtime/globals_extension.hpp" #include "runtime/handles.inline.hpp" #include "runtime/javaThread.inline.hpp" #include "runtime/nonJavaThread.hpp" diff --git a/src/hotspot/share/runtime/threadSMR.cpp b/src/hotspot/share/runtime/threadSMR.cpp index 1469c7a42aa6..a15bb1710618 100644 --- a/src/hotspot/share/runtime/threadSMR.cpp +++ b/src/hotspot/share/runtime/threadSMR.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -727,7 +727,8 @@ JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const { } } } - } else if (!thread->is_exiting()) { + } else if (includes(thread) && !thread->is_exiting()) { + // The thread is protected by this list and has not yet exited return thread; } return nullptr; @@ -866,7 +867,7 @@ void ThreadsSMRSupport::add_thread(JavaThread *thread){ ThreadsList *old_list = xchg_java_thread_list(new_list); free_list(old_list); - if (ThreadIdTable::is_initialized()) { + if (ThreadIdTable::is_initialized_acquire()) { jlong tid = SharedRuntime::get_java_tid(thread); ThreadIdTable::add_thread(tid, thread); } diff --git a/src/hotspot/share/runtime/threads.cpp b/src/hotspot/share/runtime/threads.cpp index 4ee798ef167c..90514b737bcc 100644 --- a/src/hotspot/share/runtime/threads.cpp +++ b/src/hotspot/share/runtime/threads.cpp @@ -63,6 +63,7 @@ #include "runtime/flags/jvmFlagLimit.hpp" #include "runtime/handles.inline.hpp" #include "runtime/globals.hpp" +#include "runtime/globals_extension.hpp" #include "runtime/interfaceSupport.inline.hpp" #include "runtime/java.hpp" #include "runtime/javaCalls.hpp" @@ -682,6 +683,11 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { log_info(os)("Initialized VM with process ID %d", os::current_process_id()); + if (!FLAG_IS_DEFAULT(CreateCoredumpOnCrash) && CreateCoredumpOnCrash) { + char buffer[2*JVM_MAXPATHLEN]; + os::check_core_dump_prerequisites(buffer, sizeof(buffer), true); + } + // Signal Dispatcher needs to be started before VMInit event is posted os::initialize_jdk_signal_support(CHECK_JNI_ERR); @@ -1038,7 +1044,7 @@ void Threads::remove(JavaThread* p, bool is_daemon) { MutexLocker throttle_ml(UseThreadsLockThrottleLock ? ThreadsLockThrottle_lock : nullptr); MonitorLocker ml(Threads_lock); - if (ThreadIdTable::is_initialized()) { + if (ThreadIdTable::is_initialized_acquire()) { // This cleanup must be done before the current thread's GC barrier // is detached since we need to touch the threadObj oop. jlong tid = SharedRuntime::get_java_tid(p); diff --git a/src/hotspot/share/services/management.cpp b/src/hotspot/share/services/management.cpp index a9c50a8bf06d..5de75840f3d3 100644 --- a/src/hotspot/share/services/management.cpp +++ b/src/hotspot/share/services/management.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -978,7 +978,7 @@ static jlong get_long_attribute(jmmLongAttribute att) { return ClassLoadingService::class_method_data_size(); case JMM_OS_MEM_TOTAL_PHYSICAL_BYTES: - return os::physical_memory(); + return static_cast(os::physical_memory()); default: return -1; @@ -1130,6 +1130,7 @@ JVM_ENTRY(jint, jmm_GetThreadInfo(JNIEnv *env, jlongArray ids, jint maxDepth, jo // create dummy snapshot dump_result.add_thread_snapshot(); } else { + assert(dump_result.t_list()->includes(jt), "Must be protected"); dump_result.add_thread_snapshot(jt); } } diff --git a/src/hotspot/share/services/threadIdTable.cpp b/src/hotspot/share/services/threadIdTable.cpp index 168b2e085adf..3355fc26eaaf 100644 --- a/src/hotspot/share/services/threadIdTable.cpp +++ b/src/hotspot/share/services/threadIdTable.cpp @@ -1,6 +1,6 @@ /* -* Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. +* Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ #include "precompiled.hpp" #include "classfile/javaClasses.inline.hpp" -#include "runtime/atomic.hpp" +#include "runtime/handles.hpp" #include "runtime/interfaceSupport.inline.hpp" #include "runtime/javaThread.inline.hpp" #include "runtime/threadSMR.hpp" @@ -83,24 +83,25 @@ class ThreadIdTableConfig : public AllStatic { // Lazily creates the table and populates it with the given // thread list void ThreadIdTable::lazy_initialize(const ThreadsList *threads) { - if (!_is_initialized) { + if (!Atomic::load_acquire(&_is_initialized)) { { // There is no obvious benefit in allowing the thread table // to be concurrently populated during initialization. MutexLocker ml(ThreadIdTableCreate_lock); - if (_is_initialized) { + if (Atomic::load(&_is_initialized)) { return; } create_table(threads->length()); - _is_initialized = true; + Atomic::release_store(&_is_initialized, true); } + for (uint i = 0; i < threads->length(); i++) { JavaThread* thread = threads->thread_at(i); - oop tobj = thread->threadObj(); + Handle tobj = Handle(JavaThread::current(), thread->threadObj()); if (tobj != nullptr) { - jlong java_tid = java_lang_Thread::thread_id(tobj); MutexLocker ml(Threads_lock); if (!thread->is_exiting()) { + jlong java_tid = java_lang_Thread::thread_id(tobj()); // Must be inside the lock to ensure that we don't add a thread to the table // that has just passed the removal point in Threads::remove(). add_thread(java_tid, thread); @@ -213,7 +214,7 @@ class ThreadGet : public StackObj { }; void ThreadIdTable::do_concurrent_work(JavaThread* jt) { - assert(_is_initialized, "Thread table is not initialized"); + assert(Atomic::load(&_is_initialized), "Thread table is not initialized"); _has_work = false; double load_factor = get_load_factor(); log_debug(thread, table)("Concurrent work, load factor: %g", load_factor); @@ -223,7 +224,8 @@ void ThreadIdTable::do_concurrent_work(JavaThread* jt) { } JavaThread* ThreadIdTable::add_thread(jlong tid, JavaThread* java_thread) { - assert(_is_initialized, "Thread table is not initialized"); + assert(Threads_lock->owned_by_self(), "Must hold Threads_lock"); + assert(Atomic::load(&_is_initialized), "Thread table is not initialized"); Thread* thread = Thread::current(); ThreadIdTableLookup lookup(tid); ThreadGet tg; @@ -242,7 +244,7 @@ JavaThread* ThreadIdTable::add_thread(jlong tid, JavaThread* java_thread) { } JavaThread* ThreadIdTable::find_thread_by_tid(jlong tid) { - assert(_is_initialized, "Thread table is not initialized"); + assert(Atomic::load(&_is_initialized), "Thread table is not initialized"); Thread* thread = Thread::current(); ThreadIdTableLookup lookup(tid); ThreadGet tg; @@ -251,7 +253,8 @@ JavaThread* ThreadIdTable::find_thread_by_tid(jlong tid) { } bool ThreadIdTable::remove_thread(jlong tid) { - assert(_is_initialized, "Thread table is not initialized"); + assert(Threads_lock->owned_by_self(), "Must hold Threads_lock"); + assert(Atomic::load(&_is_initialized), "Thread table is not initialized"); Thread* thread = Thread::current(); ThreadIdTableLookup lookup(tid); return _local_table->remove(thread, lookup); diff --git a/src/hotspot/share/services/threadIdTable.hpp b/src/hotspot/share/services/threadIdTable.hpp index 12772aed88c0..a292d04452a2 100644 --- a/src/hotspot/share/services/threadIdTable.hpp +++ b/src/hotspot/share/services/threadIdTable.hpp @@ -1,6 +1,6 @@ /* -* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. +* Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ #define SHARE_SERVICES_THREADIDTABLE_HPP #include "memory/allStatic.hpp" +#include "runtime/atomic.hpp" class JavaThread; class ThreadsList; @@ -41,7 +42,9 @@ class ThreadIdTable : public AllStatic { public: // Initialization static void lazy_initialize(const ThreadsList* threads); - static bool is_initialized() { return _is_initialized; } + static bool is_initialized_acquire() { + return Atomic::load_acquire(&_is_initialized); + } // Lookup and list management static JavaThread* find_thread_by_tid(jlong tid); diff --git a/src/hotspot/share/utilities/globalDefinitions.hpp b/src/hotspot/share/utilities/globalDefinitions.hpp index 9d4cae2a08d4..2711a4e30079 100644 --- a/src/hotspot/share/utilities/globalDefinitions.hpp +++ b/src/hotspot/share/utilities/globalDefinitions.hpp @@ -131,6 +131,7 @@ class oopDesc; #define UINT64_FORMAT_X "0x%" PRIx64 #define UINT64_FORMAT_X_0 "0x%016" PRIx64 #define UINT64_FORMAT_W(width) "%" #width PRIu64 +#define PHYS_MEM_TYPE_FORMAT "%" PRIu64 // Format integers which change size between 32- and 64-bit. #define SSIZE_FORMAT "%" PRIdPTR @@ -426,6 +427,11 @@ inline size_t byte_size_in_exact_unit(size_t s) { #define HEAP_CHANGE_FORMAT_ARGS(_name_, _prev_used_, _prev_capacity_, _used_, _capacity_) \ (_name_), (_prev_used_) / K, (_prev_capacity_) / K, (_used_) / K, (_capacity_) / K +// This typedef is to address the issue of running a 32-bit VM. In this case the amount +// of physical memory may not fit in size_t, so we have to have a larger type. Once 32-bit +// is deprecated, one can use size_t. +typedef uint64_t physical_memory_size_type; + //---------------------------------------------------------------------------------------------------- // VM type definitions diff --git a/src/hotspot/share/utilities/vmError.cpp b/src/hotspot/share/utilities/vmError.cpp index 5604c7c9d568..65a52a0f3c77 100644 --- a/src/hotspot/share/utilities/vmError.cpp +++ b/src/hotspot/share/utilities/vmError.cpp @@ -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. * Copyright (c) 2017, 2020 SAP SE. All rights reserved. * Copyright (c) 2023, Red Hat, Inc. and/or its affiliates. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -1704,7 +1704,7 @@ void VMError::report_and_die(int id, const char* message, const char* detail_fmt ShowMessageBoxOnError = false; } - os::check_dump_limit(buffer, sizeof(buffer)); + os::check_core_dump_prerequisites(buffer, sizeof(buffer)); // reset signal handlers or exception filter; make sure recursive crashes // are handled properly. diff --git a/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java b/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java index ddb4d8e27183..3bdd7dc2a64e 100644 --- a/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java +++ b/src/java.base/linux/classes/jdk/internal/platform/cgroupv2/CgroupV2Subsystem.java @@ -154,22 +154,39 @@ private long getFromCpuMax(int tokenIdx) { @Override public long getCpuShares() { long sharesRaw = getLongVal("cpu.weight"); - if (sharesRaw == 100 || sharesRaw <= 0) { + // cg v2 value must be in range [1,10000] + if (sharesRaw == 100 || sharesRaw <= 0 || sharesRaw > 10000) { return CgroupSubsystem.LONG_RETVAL_UNLIMITED; } int shares = (int)sharesRaw; // CPU shares (OCI) value needs to get translated into // a proper Cgroups v2 value. See: - // https://github.com/containers/crun/blob/master/crun.1.md#cpu-controller + // https://github.com/containers/crun/blob/1.24/crun.1.md#cpu-controller // // Use the inverse of (x == OCI value, y == cgroupsv2 value): - // ((262142 * y - 1)/9999) + 2 = x + // y = 10^(log2(x)^2/612 + 125/612 * log2(x) - 7.0/34.0) // - int x = 262142 * shares - 1; - double frac = x/9999.0; - x = ((int)frac) + 2; + // By re-arranging it to the standard quadratic form: + // log2(x)^2 + 125 * log2(x) - (126 + 612 * log_10(y)) = 0 + // + // Therefore, log2(x) = (-125 + sqrt( 125^2 - 4 * (-(126 + 612 * log_10(y)))))/2 + // + // As a result we have the inverse (we can discount substraction of the + // square root value since those values result in very small numbers and the + // cpu shares values - OCI - are in range [2-262144]) + // + // x = 2^((-125 + sqrt(16129 + 2448* log10(y)))/2) + // + double logMultiplicand = Math.log10(shares); + double discriminant = 16129 + 2448 * logMultiplicand; + double squareRoot = Math.sqrt(discriminant); + double exponent = (-125 + squareRoot)/2; + double scaledValue = Math.pow(2, exponent); + + int x = (int)scaledValue; if ( x <= PER_CPU_SHARES ) { - return PER_CPU_SHARES; // mimic cgroups v1 + // Return the back-mapped value. + return x; } int f = x/PER_CPU_SHARES; int lower_multiple = f * PER_CPU_SHARES; diff --git a/src/java.base/share/classes/java/net/InetAddress.java b/src/java.base/share/classes/java/net/InetAddress.java index fcc2e2700269..9fd5f4e59c9c 100644 --- a/src/java.base/share/classes/java/net/InetAddress.java +++ b/src/java.base/share/classes/java/net/InetAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -194,8 +194,8 @@ * caching. Likewise, a system admin can configure a different * negative caching TTL value when needed or extend the usage of the stale data. * - *

Three Java security properties control the TTL values used for - * positive and negative host name resolution caching: + *

Three Java {@linkplain java.security.Security security} properties control + * the TTL values used for positive and negative host name resolution caching: * *

*
networkaddress.cache.ttl
diff --git a/src/java.base/share/classes/java/net/doc-files/net-properties.html b/src/java.base/share/classes/java/net/doc-files/net-properties.html index fc401e90b6b0..24f7a12a07fd 100644 --- a/src/java.base/share/classes/java/net/doc-files/net-properties.html +++ b/src/java.base/share/classes/java/net/doc-files/net-properties.html @@ -1,6 +1,6 @@ - - ACA - info@composers.com - http://www.composers.com/ -
- 170 West 74th St. - NY - NY - 10023 -
- 212-362-8900 - 212-874-8605 - - &familytree; -
- - diff --git a/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/out/doctypeGF.out b/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/out/doctypeGF.out deleted file mode 100644 index d4a9d98475f3..000000000000 --- a/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/out/doctypeGF.out +++ /dev/null @@ -1,21 +0,0 @@ - - - - Publishers of the Music of New York Women Composers - The Publishers - - ACA - info@composers.com - http://www.composers.com/ -
- 170 West 74th St. - NY - NY - 10023 -
- 212-362-8900 - 212-874-8605 - - -
-
diff --git a/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/publish2.xml b/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/publish2.xml deleted file mode 100644 index 789983f79f31..000000000000 --- a/test/jaxp/javax/xml/jaxp/functional/javax/xml/transform/xmlfiles/publish2.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - Publishers of the Music of New York Women Composers - The Publishers - - ACA - info@composers.com - http://www.composers.com/ -
- 170 West 74th St. - NY - NY - 10023 -
- 212-362-8900 - 212-874-8605 - - &familytree; -
-
- diff --git a/test/jaxp/javax/xml/jaxp/functional/org/xml/sax/xmlfiles/out/DTDHandlerGF.out b/test/jaxp/javax/xml/jaxp/functional/org/xml/sax/xmlfiles/out/DTDHandlerGF.out deleted file mode 100644 index f4b4241dd397..000000000000 --- a/test/jaxp/javax/xml/jaxp/functional/org/xml/sax/xmlfiles/out/DTDHandlerGF.out +++ /dev/null @@ -1,2 +0,0 @@ -In unparsedEntityDecl... name:logo publicId:null systemId:http://sc11152338.us.oracle.com:8080/xmlsqe/jaxp/web/testfiles/JAXPREP/images/tool.gif notationName:gif -In notationDecl... name:gif publicId:null systemId:http://sardinia/ diff --git a/test/jaxp/javax/xml/jaxp/unittest/transform/JDK8207760.java b/test/jaxp/javax/xml/jaxp/unittest/transform/JDK8207760.java index 1726aacdfb5b..c3c2f35d0f2e 100644 --- a/test/jaxp/javax/xml/jaxp/unittest/transform/JDK8207760.java +++ b/test/jaxp/javax/xml/jaxp/unittest/transform/JDK8207760.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -43,10 +43,10 @@ /* * @test + * @bug 8207760 8349699 + * @summary Verifies that a surrogate pair at the edge of a buffer is properly handled * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest * @run testng/othervm transform.JDK8207760 - * @summary Verifies that a surrogate pair at the edge of a buffer is properly handled - * @bug 8207760 */ @Listeners({jaxp.library.FilePolicy.class}) public class JDK8207760 { @@ -96,6 +96,14 @@ public class JDK8207760 { "\n" + ""; + final String xsl8349699 = """ + + + + + + """; + @DataProvider(name = "xsls") public Object[][] getDataBug8207760_cdata() { return new Object[][]{ @@ -104,6 +112,117 @@ public Object[][] getDataBug8207760_cdata() { }; } + /* + * Data for verifying the patch for JDK8349699 + * @see testBug8349699 + */ + @DataProvider(name = "surrogatePair") + public Object[][] getDataFor8349699() { + return new Object[][]{ + // a surrogate pair in an XML element placed anywhere in a string + {getXML(1024, 1024, "\uD835\uDF00"), getString(1024, 1024, "\uD835\uDF00")}, + {getXML(1023, 1023, "\uD835\uDF00"), getString(1023, 1023, "\uD835\uDF00")}, + {getXML(1023,0, "\uD835\uDF00"), getString(1023,0, "\uD835\uDF00")}, + {getXML(1023,120, "\uD835\uDF00"), getString(1023,120, "\uD835\uDF00")}, + // this is the original test as demonstrated in the bug report + {getXML(1017,1017, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00"), + getString(1017,1017, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00")}, + {getXML(1017,0, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00"), + getString(1017,0, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00")}, + {getXML(1017,120, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00"), + getString(1017,120, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uDF00\uD835\uDF00")}, + }; + } + + /* + * Data for verifying the patch for JDK8349699 + * @see testBug8349699N + */ + @DataProvider(name = "invalidSurrogatePair") + public Object[][] getDataFor8349699N() { + return new Object[][]{ + // invalid pair: high/high + {getXML(1024, 1024, "\uD835\uD835")}, + {getXML(1023, 1023, "\uD835\uD835")}, + {getXML(1023,0, "\uD835\uD835")}, + {getXML(1023,120, "\uD835\uD835")}, + // invalid pair: low/low + {getXML(1024, 1024, "\uDF00\uDF00")}, + {getXML(1023, 1023, "\uDF00\uDF00")}, + {getXML(1023,0, "\uDF00\uDF00")}, + {getXML(1023,120, "\uDF00\uDF00")}, + // invalid pair in the original test string + {getXML(1017,1017, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uD835\uD835\uDF00")}, + {getXML(1017,0, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uD835\uD835\uDF00")}, + {getXML(1017,120, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uD835\uD835\uD835\uDF00")}, + {getXML(1017,1017, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uDF00\uDF00\uD835\uDF00")}, + {getXML(1017,0, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uDF00\uDF00\uD835\uDF00")}, + {getXML(1017,120, "\uD835\uDF03\uD835\uDF00\uD835\uDF00\uDF00\uDF00\uD835\uDF00")}, + }; + } + + /* + * @bug 8349699 + * Verifies that a surrogate pair at the edge of a buffer is properly handled + * when serializing into a Character section. + */ + @Test(dataProvider = "surrogatePair") + public final void testBug8349699(String xml, String expected) throws Exception { + Transformer t = createTransformerFromInputstream( + new ByteArrayInputStream(xsl8349699.getBytes(StandardCharsets.UTF_8))); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(new StringReader(xml)), new StreamResult(sw)); + Assert.assertEquals(sw.toString(), expected); + } + + /* + * @bug 8349699 + * Verifies that invalid surrogate pairs are caught. + */ + @Test(dataProvider = "invalidSurrogatePair") + public final void testBug8349699N(String xml) throws Exception { + Assert.assertThrows(TransformerException.class, () -> { + Transformer t = createTransformerFromInputstream( + new ByteArrayInputStream(xsl8349699.getBytes(StandardCharsets.UTF_8))); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(new StringReader(xml)), new StreamResult(sw)); + }); + } + + /** + * Returns an XML with the input string inserted in a text of length 'len' at + * the position 'pos'. + * @param len the length of the text to be placed in the XML + * @param pos the position at which the input string will be inserted into the text + * @param input the input string + * @return an XML + */ + private String getXML(int len, int pos, String input) { + StringBuilder sb = new StringBuilder(""); + sb.append(getString(len, pos, input)); + sb.append(""); + return sb.toString(); + } + + /** + * Returns a text string with the input string inserted at the specified position. + * @param len the length of the text to be returned + * @param pos the position at which the input string will be inserted into the text + * @param input the input string + * @return a text string + */ + private String getString(int len, int pos, String input) { + StringBuilder sb = new StringBuilder(); + if (pos == 0) { + sb.append(input).append("x".repeat(len)); + } else if (pos == len) { + sb.append("x".repeat(len)).append(input); + } else { + sb.append("x".repeat(pos)).append(input).append("x".repeat(len - pos)); + } + return sb.toString(); + } + /* * @bug 8207760 * Verifies that a surrogate pair at the edge of a buffer is properly handled diff --git a/test/jaxp/javax/xml/jaxp/unittest/validation/CR6740048.java b/test/jaxp/javax/xml/jaxp/unittest/validation/CR6740048.java index 6ecbba3014d8..58e78f97fabd 100644 --- a/test/jaxp/javax/xml/jaxp/unittest/validation/CR6740048.java +++ b/test/jaxp/javax/xml/jaxp/unittest/validation/CR6740048.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -62,11 +62,9 @@ public final void testReusingDocumentBuilder() { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); - if (xsd != null) { - docBuilderFactory.setValidating(true); - docBuilderFactory.setAttribute(SCHEMA_LANGUAGE_URL, XML_SCHEMA_URL); - docBuilderFactory.setAttribute(SCHEMA_SOURCE_URL, xsd); - } + docBuilderFactory.setValidating(true); + docBuilderFactory.setAttribute(SCHEMA_LANGUAGE_URL, XML_SCHEMA_URL); + docBuilderFactory.setAttribute(SCHEMA_SOURCE_URL, xsd); final DocumentBuilder documentBuilder = docBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(new ErrorHandler() { diff --git a/test/jdk/ProblemList.txt b/test/jdk/ProblemList.txt index c97f6c21c3e5..a72f9aecf8fe 100644 --- a/test/jdk/ProblemList.txt +++ b/test/jdk/ProblemList.txt @@ -119,6 +119,7 @@ java/awt/Focus/FocusOwnerFrameOnClick/FocusOwnerFrameOnClick.java 8081489 generi java/awt/Focus/IconifiedFrameFocusChangeTest/IconifiedFrameFocusChangeTest.java 6849364 generic-all java/awt/Focus/AutoRequestFocusTest/AutoRequestFocusToFrontTest.java 6848406 generic-all java/awt/Focus/AutoRequestFocusTest/AutoRequestFocusSetVisibleTest.java 6848407 generic-all +java/awt/Frame/MaximizedToMaximized/MaximizedToMaximized.java 8340374 macosx-all java/awt/Frame/MaximizedUndecorated/MaximizedUndecorated.java 8022302 generic-all java/awt/Frame/RestoreToOppositeScreen/RestoreToOppositeScreen.java 8286840 linux-all java/awt/Frame/InitialIconifiedTest.java 7144049,8203920 macosx-all,linux-all @@ -126,8 +127,9 @@ java/awt/Frame/FocusTest.java 8341480 macosx-all java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java 8160558 windows-all java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion.java 8060176 windows-all,macosx-all java/awt/event/MouseWheelEvent/InfiniteRecursion/InfiniteRecursion_1.java 8060176 windows-all,macosx-all +java/awt/dnd/FileListBetweenJVMsTest/FileListBetweenJVMsTest.java 8353673 macosx-all java/awt/dnd/URIListBetweenJVMsTest/URIListBetweenJVMsTest.java 8171510 macosx-all -java/awt/dnd/MissingDragExitEventTest/MissingDragExitEventTest.java 8288839 windows-x64 +java/awt/dnd/MissingDragExitEventTest/MissingDragExitEventTest.java 8288839 windows-x64,macosx-all java/awt/dnd/DragExitBeforeDropTest.java 8242805 macosx-all java/awt/dnd/DragThresholdTest.java 8076299 macosx-all java/awt/dnd/CustomDragCursorTest.java 8242805 macosx-all @@ -246,18 +248,19 @@ sun/awt/datatransfer/SuplementaryCharactersTransferTest.java 8011371 generic-all sun/awt/shell/ShellFolderMemoryLeak.java 8197794 windows-all sun/java2d/DirectX/OverriddenInsetsTest/OverriddenInsetsTest.java 8196102 generic-all sun/java2d/DirectX/RenderingToCachedGraphicsTest/RenderingToCachedGraphicsTest.java 8196180 windows-all,macosx-all +sun/java2d/OpenGL/MultiWindowFillTest.java 8378506 macosx-all +sun/java2d/OpenGL/OpaqueDest.java#id1 8367574 macosx-all +sun/java2d/OpenGL/ScaleParamsOOB.java#id0 8377908 linux-all sun/java2d/SunGraphics2D/EmptyClipRenderingTest.java 8144029 macosx-all,linux-all sun/java2d/SunGraphics2D/DrawImageBilinear.java 8297175 linux-all sun/java2d/SunGraphics2D/PolyVertTest.java 6986565 generic-all sun/java2d/SunGraphics2D/SimplePrimQuality.java 6992007 generic-all sun/java2d/SunGraphics2D/SourceClippingBlitTest/SourceClippingBlitTest.java 8196185 generic-all -sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh 8221451 linux-all java/awt/FullScreen/DisplayChangeVITest/DisplayChangeVITest.java 8169469,8273617 windows-all,macosx-aarch64 java/awt/FullScreen/UninitializedDisplayModeChangeTest/UninitializedDisplayModeChangeTest.java 8273617 macosx-all java/awt/print/PrinterJob/PSQuestionMark.java 7003378 generic-all java/awt/print/PrinterJob/GlyphPositions.java 7003378 generic-all -java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java 8366852 generic-all java/awt/Component/GetScreenLocTest/GetScreenLocTest.java 4753654 generic-all java/awt/Component/SetEnabledPerformance/SetEnabledPerformance.java 8165863 macosx-all java/awt/Clipboard/PasteNullToTextComponentsTest.java 8234140 macosx-all,windows-all @@ -268,6 +271,7 @@ java/awt/Clipboard/ClipboardSecurity.java 8054809 macosx-all java/awt/Clipboard/GetAltContentsTest/SystemClipboardTest.java 8234140 macosx-all java/awt/Clipboard/ImageTransferTest.java 8030710 generic-all java/awt/Clipboard/NoDataConversionFailureTest.java 8234140 macosx-all +java/awt/Dialog/ModalExcludedTest.java 7125054 macosx-all java/awt/Frame/MiscUndecorated/RepaintTest.java 8266244 macosx-aarch64 java/awt/Modal/FileDialog/FileDialogAppModal1Test.java 7186009 macosx-all java/awt/Modal/FileDialog/FileDialogAppModal2Test.java 7186009 macosx-all @@ -407,7 +411,6 @@ 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,8302787 macosx-all,windows-all java/awt/Mouse/RemovedComponentMouseListener/RemovedComponentMouseListener.java 8157170 macosx-all -java/awt/Modal/ToFront/DialogToFrontModeless1Test.java 8213530 linux-all java/awt/Modal/ToFront/DialogToFrontNonModalTest.java 8221899 linux-all java/awt/Modal/ToBack/ToBackAppModal1Test.java 8196441 linux-all,macosx-all java/awt/Modal/ToBack/ToBackAppModal2Test.java 8196441 linux-all,macosx-all @@ -451,7 +454,6 @@ java/awt/Focus/NonFocusableBlockedOwnerTest/NonFocusableBlockedOwnerTest.java 71 java/awt/Focus/TranserFocusToWindow/TranserFocusToWindow.java 6848810 macosx-all,linux-all java/awt/FileDialog/ModalFocus/FileDialogModalFocusTest.java 8194751 linux-all java/awt/image/VolatileImage/BitmaskVolatileImage.java 8133102 linux-all -java/awt/SplashScreen/MultiResolutionSplash/unix/UnixMultiResolutionSplashTest.java 8203004 linux-all java/awt/ScrollPane/ScrollPaneEventType.java 8296516 macosx-all java/awt/Robot/AcceptExtraMouseButtons/AcceptExtraMouseButtons.java 7107528 linux-all,macosx-all java/awt/Mouse/MouseDragEvent/MouseDraggedTest.java 8080676 linux-all @@ -485,13 +487,10 @@ java/awt/MenuBar/TestNoScreenMenuBar.java 8265987 macosx-all java/awt/Graphics2D/DrawString/DrawRotatedStringUsingRotatedFont.java 8266283 generic-all java/awt/Graphics2D/DrawString/RotTransText.java 8316878 linux-all -java/awt/Graphics2D/CopyAreaOOB.java 8343106 macosx-aarch64 java/awt/KeyboardFocusmanager/TypeAhead/ButtonActionKeyTest/ButtonActionKeyTest.java 8257529 windows-x64 java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeForModalDialogTest/ConsumeForModalDialogTest.java 8302787 windows-all java/awt/KeyboardFocusmanager/TypeAhead/MenuItemActivatedTest/MenuItemActivatedTest.java 8302787 windows-all -java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java 8321303 linux-all -java/awt/Window/GetScreenLocation/GetScreenLocationTest.java 8225787 linux-x64 java/awt/Dialog/MakeWindowAlwaysOnTop/MakeWindowAlwaysOnTop.java 8266243 macosx-aarch64 java/awt/Dialog/ChoiceModalDialogTest.java 8161475 macosx-all java/awt/Dialog/FileDialogUserFilterTest.java 8001142 generic-all @@ -611,7 +610,6 @@ java/rmi/transport/rapidExportUnexport/RapidExportUnexport.java 7146541 linux-al java/rmi/registry/readTest/CodebaseTest.java 8173324 windows-all java/rmi/registry/multipleRegistries/MultipleRegistries.java 8268182 macosx-all - java/rmi/Naming/DefaultRegistryPort.java 8005619 windows-all java/rmi/Naming/legalRegistryNames/LegalRegistryNames.java 8005619 windows-all @@ -685,7 +683,6 @@ javax/swing/AbstractButton/6711682/bug6711682.java 8060765 windows-all,macosx-al javax/swing/JFileChooser/6396844/TwentyThousandTest.java 8198003 generic-all javax/swing/JFileChooser/8194044/FileSystemRootTest.java 8327236 windows-all javax/swing/JPopupMenu/6800513/bug6800513.java 7184956 macosx-all -javax/swing/JTabbedPane/4624207/bug4624207.java 8064922 macosx-all javax/swing/SwingUtilities/TestBadBreak/TestBadBreak.java 8160720 generic-all javax/swing/JFileChooser/bug6798062.java 8146446 windows-all javax/swing/JPopupMenu/4870644/bug4870644.java 8194130 macosx-all,linux-all @@ -800,19 +797,19 @@ jdk/jfr/api/consumer/recordingstream/TestOnEvent.java 8255404 linux-x6 javax/swing/JFileChooser/6698013/bug6698013.java 8024419 macosx-all javax/swing/JColorChooser/8065098/bug8065098.java 8065647 macosx-all javax/swing/JTabbedPane/bug4499556.java 8267500 macosx-all -javax/swing/JTabbedPane/bug4666224.java 8144124 macosx-all javax/swing/SwingUtilities/TestTextPosInPrint.java 8227025 windows-all +javax/swing/JInternalFrame/bug4134077.java 8184985 windows-all java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_1.java 7131438,8022539 generic-all java/awt/event/MouseEvent/SpuriousExitEnter/SpuriousExitEnter_2.java 7131438,8022539 generic-all java/awt/Modal/WsDisabledStyle/CloseBlocker/CloseBlocker.java 7187741 linux-all,macosx-all java/awt/xembed/server/TestXEmbedServerJava.java 8001150,8004031 generic-all -java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java 8068378 generic-all java/awt/image/VolatileImage/VolatileImageConfigurationTest.java 8171069 macosx-all,linux-all java/awt/Modal/InvisibleParentTest/InvisibleParentTest.java 8172245 linux-all java/awt/Frame/FrameStateTest/FrameStateTest.java 8203920 macosx-all,linux-all java/awt/print/PrinterJob/ScaledText/ScaledText.java 8231226 macosx-all java/awt/print/PrinterJob/PrintTextTest.java 8148334 generic-all +java/awt/font/GlyphVector/TestGlyphVectorLayout.java 8354987 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 --git a/test/jdk/TEST.groups b/test/jdk/TEST.groups index 7720d4e8c007..dae237be3ed3 100644 --- a/test/jdk/TEST.groups +++ b/test/jdk/TEST.groups @@ -553,6 +553,7 @@ jdk_jfr_sanity = \ jdk/jfr/event/gc/collection/TestGCWithFasttime.java \ jdk/jfr/event/gc/configuration/TestGCConfigurationEvent.java \ jdk/jfr/event/metadata/TestDefaultConfigurations.java \ + jdk/jfr/event/oldobject/TestDFSWithSmallStack.java \ jdk/jfr/startupargs/TestDumpOnExit.java \ jdk/jfr/api/consumer/recordingstream/TestBasics.java diff --git a/test/jdk/com/sun/java/swing/SwingUtilities3/ApplyInsetsTest.java b/test/jdk/com/sun/java/swing/SwingUtilities3/ApplyInsetsTest.java new file mode 100644 index 000000000000..047eaff66d4a --- /dev/null +++ b/test/jdk/com/sun/java/swing/SwingUtilities3/ApplyInsetsTest.java @@ -0,0 +1,65 @@ +/* + * 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.Insets; +import java.awt.Rectangle; + +import com.sun.java.swing.SwingUtilities3; + +/* + * @test + * @bug 8365379 + * @summary Verify SwingUtilities3 insets return correct result + * independent of initial values + * @modules java.desktop/com.sun.java.swing + * @run main ApplyInsetsTest + */ + +public class ApplyInsetsTest { + public static void main(String[] args) { + Rectangle rect = new Rectangle(10, 20, 60, 60); + Insets insets = new Insets(5, 10, 15, 20); + Rectangle expected = + new Rectangle(rect.x + insets.left, + rect.y + insets.top, + rect.width - (insets.left + insets.right), + rect.height - (insets.top + insets.bottom)); + + SwingUtilities3.applyInsets(rect, insets); + if (!rect.equals(expected)) { + throw new RuntimeException("Test failed: expected " + expected + + " but got " + rect); + } + + // Right to left test + rect.setRect(10, 20, 60, 60); + expected.x = rect.x + insets.right; + SwingUtilities3.applyInsets(rect, insets, false); + if (!rect.equals(expected)) { + throw new RuntimeException("Right to left test failed: expected " + + expected + " but got " + rect); + } + + System.out.println("Test passed."); + } +} diff --git a/test/jdk/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java b/test/jdk/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java index cb90f374d847..7824b030d418 100644 --- a/test/jdk/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java +++ b/test/jdk/com/sun/java/swing/plaf/gtk/4928019/bug4928019.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 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 @@ -26,25 +26,25 @@ * @bug 4928019 * @key headful * @summary Makes sure all the basic classes can be created with GTK. - * @author Scott Violet + * @requires (os.family != "windows" & os.family != "mac") + * @library /test/lib + * @build jtreg.SkippedException + * @run main bug4928019 */ import javax.swing.*; import javax.swing.plaf.basic.*; +import jtreg.SkippedException; + public class bug4928019 { public static void main(String[] args) throws Throwable { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); - } catch (UnsupportedLookAndFeelException ex) { - System.err.println("GTKLookAndFeel is not supported on this platform." + - " Test is considered passed."); - return; - } catch (ClassNotFoundException ex) { - System.err.println("GTKLookAndFeel class is not found." + - " Test is considered passed."); - return; + } catch (Exception e) { + throw new SkippedException("GTKLookAndFeel isn't supported", e); } + new JButton() { public void updateUI() { setUI(new BasicButtonUI()); diff --git a/test/jdk/com/sun/java/swing/plaf/gtk/Test6635110.java b/test/jdk/com/sun/java/swing/plaf/gtk/Test6635110.java index ddf8363e2ee4..eb3e1e7ca62b 100644 --- a/test/jdk/com/sun/java/swing/plaf/gtk/Test6635110.java +++ b/test/jdk/com/sun/java/swing/plaf/gtk/Test6635110.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2010, 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 @@ -21,18 +21,28 @@ * questions. */ -/* @test - @bug 6635110 - @key headful - @summary GTK icons should not throw NPE when called by non-GTK UI - @author Peter Zhelezniakov - @run main Test6635110 +/* + * @test + * @bug 6635110 + * @key headful + * @summary GTK icons should not throw NPE when called by non-GTK UI + * @requires (os.family != "windows" & os.family != "mac") + * @library /test/lib + * @build jtreg.SkippedException + * @run main Test6635110 */ -import javax.swing.*; -import java.awt.*; +import java.awt.Component; import java.awt.image.BufferedImage; -import javax.swing.plaf.basic.*; + +import javax.swing.JMenu; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.basic.BasicMenuUI; +import javax.swing.plaf.basic.BasicToolBarUI; + +import jtreg.SkippedException; public class Test6635110 implements Runnable { @@ -53,7 +63,7 @@ public class Test6635110 implements Runnable { paint(tb); } - void paint(Component c) { + private void paint(Component c) { c.setSize(WIDTH, HEIGHT); c.paint(IMAGE.getGraphics()); } @@ -62,9 +72,9 @@ public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { - System.out.println("GTKLookAndFeel cannot be set, skipping this test"); - return; + throw new SkippedException("GTKLookAndFeel isn't supported", e); } + SwingUtilities.invokeAndWait(new Test6635110()); } } diff --git a/test/jdk/com/sun/java/swing/plaf/gtk/Test6963870.java b/test/jdk/com/sun/java/swing/plaf/gtk/Test6963870.java index 962a2d1a0aff..ea072419a594 100644 --- a/test/jdk/com/sun/java/swing/plaf/gtk/Test6963870.java +++ b/test/jdk/com/sun/java/swing/plaf/gtk/Test6963870.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,23 +21,28 @@ * questions. */ -/* @test - @bug 6963870 - @key headful - @summary Tests that GTKPainter.ListTableFocusBorder.getBorderInsets() - doesn't return null - @author Peter Zhelezniakov - @run main Test6963870 -*/ +/* + * @test + * @bug 6963870 + * @key headful + * @summary Tests that GTKPainter.ListTableFocusBorder.getBorderInsets() + * doesn't return null + * @requires (os.family != "windows" & os.family != "mac") + * @library /test/lib + * @build jtreg.SkippedException + * @run main Test6963870 + */ import java.awt.Insets; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; +import jtreg.SkippedException; + public class Test6963870 implements Runnable { - final static String[] UI_NAMES = { + static final String[] UI_NAMES = { "List.focusCellHighlightBorder", "List.focusSelectedCellHighlightBorder", "List.noFocusBorder", @@ -45,6 +50,7 @@ public class Test6963870 implements Runnable { "Table.focusSelectedCellHighlightBorder", }; + @Override public void run() { for (String uiName: UI_NAMES) { test(uiName); @@ -63,11 +69,9 @@ public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { - System.out.println("GTKLookAndFeel cannot be set, skipping this test"); - return; + throw new SkippedException("GTKLookAndFeel isn't supported", e); } SwingUtilities.invokeAndWait(new Test6963870()); } } - diff --git a/test/jdk/com/sun/java/swing/plaf/windows/MenuItem/MenuItemAcceleratorColor.java b/test/jdk/com/sun/java/swing/plaf/windows/MenuItem/MenuItemAcceleratorColor.java new file mode 100644 index 000000000000..f098be4fdbd6 --- /dev/null +++ b/test/jdk/com/sun/java/swing/plaf/windows/MenuItem/MenuItemAcceleratorColor.java @@ -0,0 +1,193 @@ +/* + * 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.BorderLayout; +import java.awt.Color; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + +import javax.swing.Box; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.KeyStroke; +import javax.swing.UIManager; + +import static javax.swing.BorderFactory.createEmptyBorder; + +/* + * @test id=windows + * @bug 8348760 8365375 8365389 8365625 + * @requires (os.family == "windows") + * @summary Verify that Windows Look & Feel allows changing + * accelerator colors + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MenuItemAcceleratorColor + */ + +/* + * @test id=classic + * @bug 8348760 8365375 8365389 8365625 + * @requires (os.family == "windows") + * @summary Verify that Windows Classic Look & Feel allows changing + * accelerator colors + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MenuItemAcceleratorColor classic + */ +public final class MenuItemAcceleratorColor { + private static final String INSTRUCTIONS = + "Click the Menu to open it.\n" + + "\n" + + "Verify that the first and the last menu items render " + + "their accelerators using the default colors, the color " + + "should match that of the menu item itself in regular and " + + "selected states.\n" + + "\n" + + "Verify that the second menu item renders its accelerator " + + "with green and that the color changes to red when selected.\n" + + "\n" + + "Verify that the third menu item renders its accelerator " + + "with magenta and yellow correspondingly.\n" + + "\n" + + "Verify that only the fifth menu item renders its accelerator " + + "with blue; both the fourth and sixth should render their " + + "accelerator with a shade of gray.\n" + + "\n" + + "If the above conditions are satisfied, press the Pass button; " + + "otherwise, press the Fail button."; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel((args.length > 0 && "classic".equals(args[0])) + ? "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel" + : "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows(20) + .columns(60) + .testUI(MenuItemAcceleratorColor::createUI) + .build() + .awaitAndCheck(); + } + + private static Box createInfoPanel() { + Box box = Box.createVerticalBox(); + box.add(new JLabel("Look and Feel: " + + UIManager.getLookAndFeel() + .getName())); + box.add(new JLabel("Java version: " + + System.getProperty("java.runtime.version"))); + return box; + } + + private static JFrame createUI() { + JPanel content = new JPanel(new BorderLayout()); + content.setBorder(createEmptyBorder(8, 8, 8, 8)); + content.add(createInfoPanel(), + BorderLayout.SOUTH); + + JFrame frame = new JFrame("Accelerator colors in Windows L&F"); + frame.setJMenuBar(createMenuBar()); + frame.add(content, BorderLayout.CENTER); + frame.setSize(350, 370); + return frame; + } + + private static JMenuBar createMenuBar() { + JMenuItem first = new JMenuItem("First menu item"); + first.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, + InputEvent.CTRL_DOWN_MASK)); + + // Modify colors for accelerator rendering + Color acceleratorForeground = UIManager.getColor("MenuItem.acceleratorForeground"); + Color acceleratorSelectionForeground = UIManager.getColor("MenuItem.acceleratorSelectionForeground"); + UIManager.put("MenuItem.acceleratorForeground", Color.GREEN); + UIManager.put("MenuItem.acceleratorSelectionForeground", Color.RED); + + JMenuItem second = new JMenuItem("Second menu item"); + second.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, + InputEvent.SHIFT_DOWN_MASK + | InputEvent.CTRL_DOWN_MASK)); + + UIManager.put("MenuItem.acceleratorForeground", Color.MAGENTA); + UIManager.put("MenuItem.acceleratorSelectionForeground", Color.YELLOW); + JMenuItem third = new JMenuItem("Third menu item"); + third.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, + InputEvent.ALT_DOWN_MASK)); + + // Restore colors + UIManager.put("MenuItem.acceleratorForeground", acceleratorForeground); + UIManager.put("MenuItem.acceleratorSelectionForeground", acceleratorSelectionForeground); + + + // Disabled foreground + JMenuItem fourth = new JMenuItem("Fourth menu item"); + fourth.setEnabled(false); + fourth.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, + InputEvent.CTRL_DOWN_MASK)); + + Color disabledForeground = UIManager.getColor("MenuItem.disabledForeground"); + UIManager.put("MenuItem.disabledForeground", Color.BLUE); + + JMenuItem fifth = new JMenuItem("Fifth menu item"); + fifth.setEnabled(false); + fifth.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, + InputEvent.CTRL_DOWN_MASK + | InputEvent.SHIFT_DOWN_MASK)); + + // Restore disabled foreground + UIManager.put("MenuItem.disabledForeground", disabledForeground); + + JMenuItem sixth = new JMenuItem("Sixth menu item"); + sixth.setEnabled(false); + sixth.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, + InputEvent.CTRL_DOWN_MASK + | InputEvent.ALT_DOWN_MASK)); + + + JMenuItem quit = new JMenuItem("Quit"); + quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, + InputEvent.CTRL_DOWN_MASK)); + + JMenu menu = new JMenu("Menu"); + menu.add(first); + menu.add(second); + menu.add(third); + menu.addSeparator(); + menu.add(fourth); + menu.add(fifth); + menu.add(sixth); + menu.addSeparator(); + menu.add(quit); + + JMenuBar menuBar = new JMenuBar(); + menuBar.add(menu); + + return menuBar; + } +} diff --git a/test/jdk/com/sun/net/httpserver/SANTest.java b/test/jdk/com/sun/net/httpserver/SANTest.java index dc7f5e7bdd53..948ebdce30b6 100644 --- a/test/jdk/com/sun/net/httpserver/SANTest.java +++ b/test/jdk/com/sun/net/httpserver/SANTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -61,7 +61,7 @@ */ public class SANTest implements HttpServerAdapters { - static SSLContext ctx; + private static SSLContext ctx; static HttpServer getHttpsServer(InetSocketAddress addr, Executor exec, SSLContext ctx) throws Exception { HttpsServer server = HttpsServer.create(addr, 0); @@ -99,6 +99,8 @@ static HttpTestServer initServer(boolean h2, InetAddress addr, SSLContext ctx, } public static void main (String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); + // Http/1.1 servers HttpTestServer h1s1 = null; HttpTestServer h1s2 = null; @@ -110,7 +112,6 @@ public static void main (String[] args) throws Exception { ExecutorService executor=null; try { System.out.print ("SANTest: "); - ctx = new SimpleSSLContext().get(); executor = Executors.newCachedThreadPool(); InetAddress l1 = InetAddress.getByName("::1"); diff --git a/test/jdk/com/sun/net/httpserver/SelCacheTest.java b/test/jdk/com/sun/net/httpserver/SelCacheTest.java index 5104e88244e9..1417c3d8582e 100644 --- a/test/jdk/com/sun/net/httpserver/SelCacheTest.java +++ b/test/jdk/com/sun/net/httpserver/SelCacheTest.java @@ -62,9 +62,10 @@ public class SelCacheTest extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + SelCacheTest.class.getSimpleName() + '-'; - static SSLContext ctx; + private static SSLContext ctx; public static void main(String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); HttpServer s1 = null; HttpsServer s2 = null; ExecutorService executor=null; @@ -87,7 +88,6 @@ public static void main(String[] args) throws Exception { executor = Executors.newCachedThreadPool(); s1.setExecutor(executor); s2.setExecutor(executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator(ctx)); s1.start(); s2.start(); diff --git a/test/jdk/com/sun/net/httpserver/ServerStopTerminationTest.java b/test/jdk/com/sun/net/httpserver/ServerStopTerminationTest.java index 815611607258..e8f365b715b1 100644 --- a/test/jdk/com/sun/net/httpserver/ServerStopTerminationTest.java +++ b/test/jdk/com/sun/net/httpserver/ServerStopTerminationTest.java @@ -124,13 +124,16 @@ public void shouldAwaitActiveExchange() throws InterruptedException { // Complete the exchange one second into the future final Duration exchangeDuration = Duration.ofSeconds(1); + // taking start time before entering completeExchange to account for possible + // delays in reaching server.stop(). + final long startTime = System.nanoTime(); completeExchange(exchangeDuration); log("Complete Exchange triggered"); // Time the shutdown sequence - final Duration delayDuration = Duration.ofSeconds(Utils.adjustTimeout(5)); + final Duration delayDuration = Duration.ofSeconds(Utils.adjustTimeout(20)); log("Shutdown triggered with the delay of " + delayDuration.getSeconds()); - final long elapsed = timeShutdown(delayDuration); + final long elapsed = timeShutdown(delayDuration, startTime); log("Shutdown complete"); // The shutdown should take at least as long as the exchange duration @@ -151,31 +154,20 @@ public void shouldAwaitActiveExchange() throws InterruptedException { * @throws InterruptedException if an unexpected interruption occurs */ @Test - public void shouldCompeteAfterDelay() throws InterruptedException { + public void shouldCompleteAfterDelay() throws InterruptedException { // Initiate an exchange startExchange(); // Wait for the server to receive the exchange start.await(); log("Exchange started"); - // Complete the exchange 10 second into the future. - // Runs in parallel, so won't block the server stop - final Duration exchangeDuration = Duration.ofSeconds(Utils.adjustTimeout(10)); - completeExchange(exchangeDuration); - log("Complete Exchange triggered"); - - // Time the shutdown sequence final Duration delayDuration = Duration.ofSeconds(1); log("Shutdown triggered with the delay of " + delayDuration.getSeconds()); final long elapsed = timeShutdown(delayDuration); log("Shutdown complete"); - - - // The shutdown should not await the exchange to complete - if (elapsed >= exchangeDuration.toNanos()) { - fail("HttpServer.stop terminated too late"); - } + complete.countDown(); + log("Exchange completed"); // The shutdown delay should have expired if (elapsed < delayDuration.toNanos()) { @@ -277,7 +269,14 @@ public void shouldAllowRepeatedStop() { */ private long timeShutdown(Duration delayDuration) { final long startTime = System.nanoTime(); + return timeShutdown(delayDuration, startTime); + } + /** + * This allows passing a custom start time + */ + private long timeShutdown(Duration delayDuration, + long startTime) { server.stop((int) delayDuration.toSeconds()); return System.nanoTime() - startTime; } diff --git a/test/jdk/com/sun/net/httpserver/Test1.java b/test/jdk/com/sun/net/httpserver/Test1.java index 32bab4d91784..522e43a0b46b 100644 --- a/test/jdk/com/sun/net/httpserver/Test1.java +++ b/test/jdk/com/sun/net/httpserver/Test1.java @@ -69,9 +69,11 @@ public class Test1 extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + Test1.class.getSimpleName() + '-'; - static SSLContext ctx; + private static SSLContext ctx; public static void main (String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); + HttpServer s1 = null; HttpsServer s2 = null; ExecutorService executor=null; @@ -94,7 +96,6 @@ public static void main (String[] args) throws Exception { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/test/jdk/com/sun/net/httpserver/Test12.java b/test/jdk/com/sun/net/httpserver/Test12.java index 2a0ee1fc0a44..102b607f2129 100644 --- a/test/jdk/com/sun/net/httpserver/Test12.java +++ b/test/jdk/com/sun/net/httpserver/Test12.java @@ -56,9 +56,11 @@ public class Test12 extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + Test12.class.getSimpleName() + '-'; - static SSLContext ctx; + private static SSLContext ctx; public static void main (String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); + HttpServer s1 = null; HttpsServer s2 = null; Path smallFilePath = createTempFileOfSize(TEMP_FILE_PREFIX, null, 23); @@ -77,7 +79,6 @@ public static void main (String[] args) throws Exception { HttpContext c2 = s2.createContext ("/", h); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/test/jdk/com/sun/net/httpserver/Test13.java b/test/jdk/com/sun/net/httpserver/Test13.java index ead3ff95acd6..f7ade590f2cd 100644 --- a/test/jdk/com/sun/net/httpserver/Test13.java +++ b/test/jdk/com/sun/net/httpserver/Test13.java @@ -59,13 +59,15 @@ public class Test13 extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + Test13.class.getSimpleName() + '-'; - static SSLContext ctx; + private static SSLContext ctx; final static int NUM = 32; // was 32 static boolean fail = false; public static void main (String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); + HttpServer s1 = null; HttpsServer s2 = null; ExecutorService executor=null; @@ -87,7 +89,6 @@ public static void main (String[] args) throws Exception { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); diff --git a/test/jdk/com/sun/net/httpserver/Test6a.java b/test/jdk/com/sun/net/httpserver/Test6a.java index bbe107f5e2fd..21a4aebdc75a 100644 --- a/test/jdk/com/sun/net/httpserver/Test6a.java +++ b/test/jdk/com/sun/net/httpserver/Test6a.java @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 6270015 * @library /test/lib @@ -54,7 +54,7 @@ public static void main (String[] args) throws Exception { HttpsServer server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); ExecutorService executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext().get(); + SSLContext ssl = SimpleSSLContext.findSSLContext(); server.setExecutor (executor); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.start (); diff --git a/test/jdk/com/sun/net/httpserver/Test7a.java b/test/jdk/com/sun/net/httpserver/Test7a.java index 5ff01ade9a03..58d40bd8ddee 100644 --- a/test/jdk/com/sun/net/httpserver/Test7a.java +++ b/test/jdk/com/sun/net/httpserver/Test7a.java @@ -58,7 +58,7 @@ public static void main (String[] args) throws Exception { HttpsServer server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); ExecutorService executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext().get(); + SSLContext ssl = SimpleSSLContext.findSSLContext(); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.setExecutor (executor); server.start (); diff --git a/test/jdk/com/sun/net/httpserver/Test8a.java b/test/jdk/com/sun/net/httpserver/Test8a.java index 6c642f7c22aa..67f9c93172ab 100644 --- a/test/jdk/com/sun/net/httpserver/Test8a.java +++ b/test/jdk/com/sun/net/httpserver/Test8a.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2023, 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 @@ -61,7 +61,7 @@ public static void main (String[] args) throws Exception { server = HttpsServer.create (addr, 0); HttpContext ctx = server.createContext ("/test", handler); executor = Executors.newCachedThreadPool(); - SSLContext ssl = new SimpleSSLContext().get(); + SSLContext ssl = SimpleSSLContext.findSSLContext(); server.setHttpsConfigurator(new HttpsConfigurator (ssl)); server.setExecutor (executor); server.start (); diff --git a/test/jdk/com/sun/net/httpserver/Test9.java b/test/jdk/com/sun/net/httpserver/Test9.java index 6f7b1d4f5bc3..92489d88dd69 100644 --- a/test/jdk/com/sun/net/httpserver/Test9.java +++ b/test/jdk/com/sun/net/httpserver/Test9.java @@ -58,15 +58,19 @@ public class Test9 extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + Test9.class.getSimpleName() + '-'; - static SSLContext ctx; - static boolean error = false; + private static SSLContext ctx; + static volatile boolean error = false; public static void main (String[] args) throws Exception { + ctx = SimpleSSLContext.findSSLContext(); + HttpServer s1 = null; HttpsServer s2 = null; ExecutorService executor=null; Path smallFilePath = createTempFileOfSize(TEMP_FILE_PREFIX, null, 23); Path largeFilePath = createTempFileOfSize(TEMP_FILE_PREFIX, null, 2730088); + smallFilePath.toFile().deleteOnExit(); + largeFilePath.toFile().deleteOnExit(); try { System.out.print ("Test9: "); InetAddress loopback = InetAddress.getLoopbackAddress(); @@ -81,7 +85,6 @@ public static void main (String[] args) throws Exception { executor = Executors.newCachedThreadPool(); s1.setExecutor (executor); s2.setExecutor (executor); - ctx = new SimpleSSLContext().get(); s2.setHttpsConfigurator(new HttpsConfigurator (ctx)); s1.start(); s2.start(); @@ -122,20 +125,16 @@ public static void main (String[] args) throws Exception { s2.stop(0); if (executor != null) executor.shutdown (); - Files.delete(smallFilePath); - Files.delete(largeFilePath); } } - static int foo = 1; - static ClientThread test (boolean fixedLen, String protocol, int port, Path filePath) throws Exception { ClientThread t = new ClientThread (fixedLen, protocol, port, filePath); t.start(); return t; } - static Object fileLock = new Object(); + static final Object fileLock = new Object(); static class ClientThread extends Thread { @@ -203,9 +202,8 @@ public boolean verify (String s, SSLSession s1) { error = true; } assertFileContentsEqual(filePath, temp.toPath()); - temp.delete(); } catch (Exception e) { - e.printStackTrace(); + System.err.println("Error occurred: " + e); error = true; } } diff --git a/test/jdk/com/sun/net/httpserver/Test9a.java b/test/jdk/com/sun/net/httpserver/Test9a.java index 85acfd265187..290acd343570 100644 --- a/test/jdk/com/sun/net/httpserver/Test9a.java +++ b/test/jdk/com/sun/net/httpserver/Test9a.java @@ -56,11 +56,14 @@ public class Test9a extends Test { private static final String TEMP_FILE_PREFIX = HttpServer.class.getPackageName() + '-' + Test9a.class.getSimpleName() + '-'; - static SSLContext serverCtx; - static volatile SSLContext clientCtx = null; + private static SSLContext serverCtx; + private static SSLContext clientCtx; static volatile boolean error = false; public static void main (String[] args) throws Exception { + serverCtx = SimpleSSLContext.findSSLContext(); + clientCtx = SimpleSSLContext.findSSLContext(); + HttpsServer server = null; ExecutorService executor=null; Path smallFilePath = createTempFileOfSize(TEMP_FILE_PREFIX, null, 23); @@ -76,8 +79,6 @@ public static void main (String[] args) throws Exception { HttpContext c1 = server.createContext ("/", h); executor = Executors.newCachedThreadPool(); server.setExecutor (executor); - serverCtx = new SimpleSSLContext().get(); - clientCtx = new SimpleSSLContext().get(); server.setHttpsConfigurator(new HttpsConfigurator (serverCtx)); server.start(); diff --git a/test/jdk/com/sun/net/httpserver/bugs/HandlerConnectionClose.java b/test/jdk/com/sun/net/httpserver/bugs/HandlerConnectionClose.java index 89839e462c51..0d44d9677892 100644 --- a/test/jdk/com/sun/net/httpserver/bugs/HandlerConnectionClose.java +++ b/test/jdk/com/sun/net/httpserver/bugs/HandlerConnectionClose.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -63,7 +63,7 @@ public class HandlerConnectionClose { static final int ONEK = 1024; static final long POST_SIZE = ONEK * 1L; - SSLContext sslContext; + private static SSLContext sslContext; Logger logger; void test(String[] args) throws Exception { @@ -77,7 +77,6 @@ void test(String[] args) throws Exception { } finally { httpServer.stop(0); } - sslContext = new SimpleSSLContext().get(); HttpServer httpsServer = startHttpServer("https"); try { testHttpURLConnection(httpsServer, "https","/close/legacy/https/chunked"); @@ -425,6 +424,7 @@ public void handle(HttpExchange t) throws IOException { void check(boolean cond, String failMessage) {if (cond) pass(); else fail(failMessage);} void debug(String message) {if(debug) { System.out.println(message); } } public static void main(String[] args) throws Throwable { + sslContext = SimpleSSLContext.findSSLContext(); Class k = new Object(){}.getClass().getEnclosingClass(); try {k.getMethod("instanceMain",String[].class) .invoke( k.newInstance(), (Object) args);} diff --git a/test/jdk/com/sun/net/httpserver/simpleserver/CustomFileSystemTest.java b/test/jdk/com/sun/net/httpserver/simpleserver/CustomFileSystemTest.java index d6ec3eb06955..0a46ac1ea8a5 100644 --- a/test/jdk/com/sun/net/httpserver/simpleserver/CustomFileSystemTest.java +++ b/test/jdk/com/sun/net/httpserver/simpleserver/CustomFileSystemTest.java @@ -256,63 +256,65 @@ public void testDirectoryWithIndexGET(String id, @Test public void testNotReadableFileGET() throws Exception { - if (!Platform.isWindows()) { // not applicable on Windows - var expectedBody = openHTML + """ -

File not found

-

/aFile.txt

- """ + closeHTML; - var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); - var root = createDirectoryInCustomFs("testNotReadableFileGET"); - var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE); - - file.toFile().setReadable(false, false); - assert !Files.isReadable(file); - - var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); - server.start(); - try { - var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); - var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build(); - var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 404); - assertEquals(response.headers().firstValue("content-length").get(), expectedLength); - assertEquals(response.body(), expectedBody); - } finally { - server.stop(0); - file.toFile().setReadable(true, false); - } + if (Platform.isWindows()) { + throw new SkipException("Not applicable on Windows"); + } + var expectedBody = openHTML + """ +

File not found

+

/aFile.txt

+ """ + closeHTML; + var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); + var root = createDirectoryInCustomFs("testNotReadableFileGET"); + var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE); + + file.toFile().setReadable(false, false); + assert !Files.isReadable(file); + + var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); + server.start(); + try { + var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); + var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build(); + var response = client.send(request, BodyHandlers.ofString()); + assertEquals(response.statusCode(), 404); + assertEquals(response.headers().firstValue("content-length").get(), expectedLength); + assertEquals(response.body(), expectedBody); + } finally { + server.stop(0); + file.toFile().setReadable(true, false); } } @Test public void testNotReadableSegmentGET() throws Exception { - if (!Platform.isWindows()) { // not applicable on Windows - var expectedBody = openHTML + """ -

File not found

-

/dir/aFile.txt

- """ + closeHTML; - var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); - var root = createDirectoryInCustomFs("testNotReadableSegmentGET"); - var dir = Files.createDirectory(root.resolve("dir")); - var file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE); - - dir.toFile().setReadable(false, false); - assert !Files.isReadable(dir); - assert Files.isReadable(file); - - var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); - server.start(); - try { - var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); - var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build(); - var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 404); - assertEquals(response.headers().firstValue("content-length").get(), expectedLength); - assertEquals(response.body(), expectedBody); - } finally { - server.stop(0); - dir.toFile().setReadable(true, false); - } + if (Platform.isWindows()) { + throw new SkipException("Not applicable on Windows"); + } + var expectedBody = openHTML + """ +

File not found

+

/dir/aFile.txt

+ """ + closeHTML; + var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); + var root = createDirectoryInCustomFs("testNotReadableSegmentGET"); + var dir = Files.createDirectory(root.resolve("dir")); + var file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE); + + dir.toFile().setReadable(false, false); + assert !Files.isReadable(dir); + assert Files.isReadable(file); + + var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); + server.start(); + try { + var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); + var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build(); + var response = client.send(request, BodyHandlers.ofString()); + assertEquals(response.statusCode(), 404); + assertEquals(response.headers().firstValue("content-length").get(), expectedLength); + assertEquals(response.body(), expectedBody); + } finally { + server.stop(0); + dir.toFile().setReadable(true, false); } } diff --git a/test/jdk/com/sun/net/httpserver/simpleserver/HttpsServerTest.java b/test/jdk/com/sun/net/httpserver/simpleserver/HttpsServerTest.java index 2227c4cd4379..37bba945fc9f 100644 --- a/test/jdk/com/sun/net/httpserver/simpleserver/HttpsServerTest.java +++ b/test/jdk/com/sun/net/httpserver/simpleserver/HttpsServerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -40,7 +40,6 @@ import java.net.http.HttpResponse.BodyHandlers; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; @@ -67,7 +66,14 @@ public class HttpsServerTest { static final boolean ENABLE_LOGGING = true; static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver"); - SSLContext sslContext; + private static SSLContext sslContext; + + static { + try { + sslContext = SimpleSSLContext.findSSLContext(); + } catch (IOException e) {} + SSLContext.setDefault(sslContext); + } @BeforeTest public void setup() throws IOException { @@ -77,8 +83,6 @@ public void setup() throws IOException { ch.setLevel(Level.ALL); LOGGER.addHandler(ch); } - sslContext = new SimpleSSLContext().get(); - SSLContext.setDefault(sslContext); } @Test diff --git a/test/jdk/com/sun/net/httpserver/simpleserver/SimpleFileServerTest.java b/test/jdk/com/sun/net/httpserver/simpleserver/SimpleFileServerTest.java index b31346409250..ab40b3c58ced 100644 --- a/test/jdk/com/sun/net/httpserver/simpleserver/SimpleFileServerTest.java +++ b/test/jdk/com/sun/net/httpserver/simpleserver/SimpleFileServerTest.java @@ -248,63 +248,65 @@ public void testDirectoryWithIndexGET(String id, @Test public void testNotReadableFileGET() throws Exception { - if (!Platform.isWindows()) { // not applicable on Windows - var expectedBody = openHTML + """ -

File not found

-

/aFile.txt

- """ + closeHTML; - var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); - var root = Files.createDirectory(TEST_DIR.resolve("testNotReadableFileGET")); - var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE); - - file.toFile().setReadable(false, false); - assert !Files.isReadable(file); - - var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); - server.start(); - try { - var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); - var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build(); - var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 404); - assertEquals(response.headers().firstValue("content-length").get(), expectedLength); - assertEquals(response.body(), expectedBody); - } finally { - server.stop(0); - file.toFile().setReadable(true, false); - } + if (Platform.isWindows()) { + throw new SkipException("Not applicable on Windows"); + } + var expectedBody = openHTML + """ +

File not found

+

/aFile.txt

+ """ + closeHTML; + var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); + var root = Files.createDirectory(TEST_DIR.resolve("testNotReadableFileGET")); + var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE); + + file.toFile().setReadable(false, false); + assert !Files.isReadable(file); + + var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); + server.start(); + try { + var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); + var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build(); + var response = client.send(request, BodyHandlers.ofString()); + assertEquals(response.statusCode(), 404); + assertEquals(response.headers().firstValue("content-length").get(), expectedLength); + assertEquals(response.body(), expectedBody); + } finally { + server.stop(0); + file.toFile().setReadable(true, false); } } @Test public void testNotReadableSegmentGET() throws Exception { - if (!Platform.isWindows()) { // not applicable on Windows - var expectedBody = openHTML + """ -

File not found

-

/dir/aFile.txt

- """ + closeHTML; - var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); - var root = Files.createDirectory(TEST_DIR.resolve("testNotReadableSegmentGET")); - var dir = Files.createDirectory(root.resolve("dir")); - var file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE); - - dir.toFile().setReadable(false, false); - assert !Files.isReadable(dir); - assert Files.isReadable(file); - - var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); - server.start(); - try { - var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); - var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build(); - var response = client.send(request, BodyHandlers.ofString()); - assertEquals(response.statusCode(), 404); - assertEquals(response.headers().firstValue("content-length").get(), expectedLength); - assertEquals(response.body(), expectedBody); - } finally { - server.stop(0); - dir.toFile().setReadable(true, false); - } + if (Platform.isWindows()) { + throw new SkipException("Not applicable on Windows"); + } + var expectedBody = openHTML + """ +

File not found

+

/dir/aFile.txt

+ """ + closeHTML; + var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length); + var root = Files.createDirectory(TEST_DIR.resolve("testNotReadableSegmentGET")); + var dir = Files.createDirectory(root.resolve("dir")); + var file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE); + + dir.toFile().setReadable(false, false); + assert !Files.isReadable(dir); + assert Files.isReadable(file); + + var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE); + server.start(); + try { + var client = HttpClient.newBuilder().proxy(NO_PROXY).build(); + var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build(); + var response = client.send(request, BodyHandlers.ofString()); + assertEquals(response.statusCode(), 404); + assertEquals(response.headers().firstValue("content-length").get(), expectedLength); + assertEquals(response.body(), expectedBody); + } finally { + server.stop(0); + dir.toFile().setReadable(true, false); } } @@ -627,18 +629,22 @@ public void testIllegalPath() throws Exception { var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO)); assertTrue(iae.getMessage().contains("does not exist")); } - { // not readable - if (!Platform.isWindows()) { // not applicable on Windows - Path p = Files.createDirectory(TEST_DIR.resolve("aDir")); - p.toFile().setReadable(false, false); - assert !Files.isReadable(p); - try { - var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO)); - assertTrue(iae.getMessage().contains("not readable")); - } finally { - p.toFile().setReadable(true, false); - } - } + } + + @Test + public void testNonReadablePath() throws Exception { + if (Platform.isWindows()) { + throw new SkipException("Not applicable on Windows"); + } + var addr = LOOPBACK_ADDR; + Path p = Files.createDirectory(TEST_DIR.resolve("aDir")); + p.toFile().setReadable(false, false); + assert !Files.isReadable(p); + try { + var iae = expectThrows(IAE, () -> SimpleFileServer.createFileServer(addr, p, OutputLevel.INFO)); + assertTrue(iae.getMessage().contains("not readable")); + } finally { + p.toFile().setReadable(true, false); } } diff --git a/test/jdk/com/sun/net/httpserver/simpleserver/jwebserver/MaxRequestTimeTest.java b/test/jdk/com/sun/net/httpserver/simpleserver/jwebserver/MaxRequestTimeTest.java index c972f87dc180..385615ecd3d3 100644 --- a/test/jdk/com/sun/net/httpserver/simpleserver/jwebserver/MaxRequestTimeTest.java +++ b/test/jdk/com/sun/net/httpserver/simpleserver/jwebserver/MaxRequestTimeTest.java @@ -78,18 +78,16 @@ public class MaxRequestTimeTest { static final String LOOPBACK_ADDR = InetAddress.getLoopbackAddress().getHostAddress(); static final AtomicInteger PORT = new AtomicInteger(); - static SSLContext sslContext; + private static SSLContext sslContext; @BeforeTest public void setup() throws IOException { + sslContext = SimpleSSLContext.findSSLContext(); + if (Files.exists(TEST_DIR)) { FileUtils.deleteFileTreeWithRetry(TEST_DIR); } Files.createDirectories(TEST_DIR); - - sslContext = new SimpleSSLContext().get(); - if (sslContext == null) - throw new AssertionError("Unexpected null sslContext"); } @Test diff --git a/test/jdk/com/sun/nio/sctp/SctpChannel/CloseDescriptors.java b/test/jdk/com/sun/nio/sctp/SctpChannel/CloseDescriptors.java index 33b68fafd520..5d62b88f23e2 100644 --- a/test/jdk/com/sun/nio/sctp/SctpChannel/CloseDescriptors.java +++ b/test/jdk/com/sun/nio/sctp/SctpChannel/CloseDescriptors.java @@ -24,6 +24,7 @@ /* * @test * @bug 8238274 + * @key intermittent * @summary Potential leak file descriptor for SCTP * @requires (os.family == "linux") * @library /test/lib diff --git a/test/jdk/java/awt/Checkbox/AppearanceIfLargeFont.java b/test/jdk/java/awt/Checkbox/AppearanceIfLargeFont.java new file mode 100644 index 000000000000..7995b43ed18d --- /dev/null +++ b/test/jdk/java/awt/Checkbox/AppearanceIfLargeFont.java @@ -0,0 +1,84 @@ +/* + * 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. + */ + +import java.awt.Button; +import java.awt.CheckboxMenuItem; +import java.awt.Frame; +import java.awt.PopupMenu; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 6401956 + * @summary The right mark of the CheckboxMenu item is broken + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual AppearanceIfLargeFont + */ + +public class AppearanceIfLargeFont extends Frame { + private static final String INSTRUCTIONS = """ + 1) Make sure that font-size is large. + You could change this using 'Appearance' dialog. + 2) Press button 'Press' + You will see a menu item with check-mark. + 3) If check-mark is correctly painted then the test passed. + Otherwise, test failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("AppearanceIfLargeFont") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(AppearanceIfLargeFont::new) + .build() + .awaitAndCheck(); + } + + public AppearanceIfLargeFont() { + createComponents(); + + setSize(200, 200); + validate(); + } + + void createComponents() { + final Button press = new Button("Press"); + final PopupMenu popup = new PopupMenu(); + press.add(popup); + add(press); + + CheckboxMenuItem item = new CheckboxMenuItem("CheckboxMenuItem", true); + popup.add(item); + + press.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent ae) { + popup.show(press, press.getSize().width, 0); + } + } + ); + } +} diff --git a/test/jdk/java/awt/Checkbox/CheckboxMenuItemEventsTest.java b/test/jdk/java/awt/Checkbox/CheckboxMenuItemEventsTest.java new file mode 100644 index 000000000000..425c24ba7ef4 --- /dev/null +++ b/test/jdk/java/awt/Checkbox/CheckboxMenuItemEventsTest.java @@ -0,0 +1,120 @@ +/* + * 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 + * 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.Button; +import java.awt.CheckboxMenuItem; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.PopupMenu; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +/* + * @test + * @bug 4814163 5005195 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests events fired by CheckboxMenuItem + * @run main/manual CheckboxMenuItemEventsTest +*/ + +public class CheckboxMenuItemEventsTest extends Frame implements ActionListener { + Button trigger; + PopupMenu popup; + TextArea ta; + + class Listener implements ItemListener, ActionListener { + public void itemStateChanged(ItemEvent e) { + ta.append("CORRECT: ItemEvent fired\n"); + } + + public void actionPerformed(ActionEvent e) { + ta.append("ERROR: ActionEvent fired\n"); + } + } + + Listener listener = new Listener(); + + private static final String INSTRUCTIONS = """ + Press button to invoke popup menu + When you press checkbox menu item + Item state should toggle (on/off). + ItemEvent should be displayed in log below. + And ActionEvent should not be displayed + Press PASS if ItemEvents are generated + and ActionEvents are not, FAIL Otherwise. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("CheckboxMenuItemEventsTest") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(CheckboxMenuItemEventsTest::new) + .build() + .awaitAndCheck(); + } + + public CheckboxMenuItemEventsTest() { + CheckboxMenuItem i1 = new CheckboxMenuItem("CheckBoxMenuItem 1"); + CheckboxMenuItem i2 = new CheckboxMenuItem("CheckBoxMenuItem 2"); + Panel p1 = new Panel(); + Panel p2 = new Panel(); + + setLayout(new BorderLayout()); + ta = new TextArea(); + p2.add(ta); + + trigger = new Button("menu"); + trigger.addActionListener(this); + + popup = new PopupMenu(); + + i1.addItemListener(listener); + i1.addActionListener(listener); + popup.add(i1); + i2.addItemListener(listener); + i2.addActionListener(listener); + popup.add(i2); + + trigger.add(popup); + + p1.add(trigger); + + add(p1, BorderLayout.NORTH); + add(p2, BorderLayout.SOUTH); + + pack(); + validate(); + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == (Object) trigger) { + popup.show(trigger, trigger.getSize().width, 0); + } + } +} diff --git a/test/jdk/java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java b/test/jdk/java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java index 6426a3779108..3a94680b7237 100644 --- a/test/jdk/java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java +++ b/test/jdk/java/awt/Choice/ChoiceMouseWheelTest/ChoiceMouseWheelTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2016, 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 @@ -22,58 +22,66 @@ */ /* - @test - @key headful - @bug 7050935 - @summary closed/java/awt/Choice/WheelEventsConsumed/WheelEventsConsumed.html fails on win32 - @library ../../regtesthelpers - @author Oleg Pekhovskiy: area=awt-choice - @build Util - @run main ChoiceMouseWheelTest -*/ + * @test + * @key headful + * @bug 7050935 + * @summary closed/java/awt/Choice/WheelEventsConsumed/WheelEventsConsumed.html fails on win32 + * @library /java/awt/regtesthelpers + * @build Util + * @run main ChoiceMouseWheelTest + */ import test.java.awt.regtesthelpers.Util; -import java.awt.*; -import java.awt.event.*; +import java.awt.Choice; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +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; public class ChoiceMouseWheelTest extends Frame { private volatile boolean itemChanged = false; private volatile boolean wheelMoved = false; private volatile boolean frameExited = false; + private final Choice choice; - public static void main(String[] args) { - new ChoiceMouseWheelTest(); + public static void main(String[] args) throws Exception { + ChoiceMouseWheelTest test = Util.invokeOnEDT(ChoiceMouseWheelTest::new); + try { + test.test(); + } finally { + EventQueue.invokeAndWait(test::dispose); + } } ChoiceMouseWheelTest() { super("ChoiceMouseWheelTest"); setLayout(new FlowLayout()); - Choice choice = new Choice(); - addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { - System.exit(0); + e.getWindow().dispose(); } }); - for(Integer i = 0; i < 50; i++) { - choice.add(i.toString()); + choice = new Choice(); + for(int i = 0; i < 50; i++) { + choice.add(Integer.toString(i)); } - choice.addItemListener(new ItemListener() { - public void itemStateChanged(ItemEvent e) { - itemChanged = true; - } - }); - choice.addMouseWheelListener(new MouseWheelListener() { - public void mouseWheelMoved(MouseWheelEvent e) { - wheelMoved = true; - } - }); + choice.addItemListener(e -> itemChanged = true); + choice.addMouseWheelListener(e -> wheelMoved = true); addMouseListener(new MouseAdapter() { @Override @@ -84,71 +92,79 @@ public void mouseExited(MouseEvent e) { add(choice); setSize(200, 300); + setLocationRelativeTo(null); setVisible(true); toFront(); + } - try { - Robot robot = new Robot(); - robot.setAutoDelay(20); - Util.waitForIdle(robot); + private void test() throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(20); + robot.waitForIdle(); + robot.delay(500); + Rectangle choiceBounds = Util.invokeOnEDT(() -> { Point pt = choice.getLocationOnScreen(); Dimension size = choice.getSize(); - int x = pt.x + size.width / 3; - robot.mouseMove(x, pt.y + size.height / 2); + return new Rectangle(pt, size); + }); + + int x = choiceBounds.x + choiceBounds.width / 3; + robot.mouseMove(x, choiceBounds.y + choiceBounds.height / 2); - // Test mouse wheel over the choice - String name = Toolkit.getDefaultToolkit().getClass().getName(); + // Test mouse wheel over the choice + String name = Toolkit.getDefaultToolkit().getClass().getName(); + boolean isXtoolkit = name.equals("sun.awt.X11.XToolkit"); + boolean isLWCToolkit = name.equals("sun.lwawt.macosx.LWCToolkit"); - // mouse wheel doesn't work for the choice on X11 and Mac, so skip it - if(!name.equals("sun.awt.X11.XToolkit") - && !name.equals("sun.lwawt.macosx.LWCToolkit")) { - robot.mouseWheel(1); - Util.waitForIdle(robot); + // mouse wheel doesn't work for the choice on X11 and Mac, so skip it + if (!isXtoolkit && !isLWCToolkit) { + robot.mouseWheel(1); + robot.waitForIdle(); - if(!wheelMoved || !itemChanged) { - throw new RuntimeException("Mouse Wheel over the choice failed!"); - } + if (!wheelMoved || !itemChanged) { + throw new RuntimeException("Mouse Wheel over the choice failed!"); } + } - // Test mouse wheel over the drop-down list - robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - Util.waitForIdle(robot); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - Util.waitForIdle(robot); + // Test mouse wheel over the drop-down list + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); - int y = getLocationOnScreen().y + getSize().height; - while(!frameExited && y >= 0) { // move to the bottom of drop-down list - robot.mouseMove(x, --y); - Util.waitForIdle(robot); - } + frameExited = false; - if(x < 0) { - throw new RuntimeException("Could not enter drop-down list!"); - } + Rectangle frameBounds = Util.invokeOnEDT(this::getBounds); - y -= choice.getHeight() / 2; - robot.mouseMove(x, y); // move to the last visible item in the drop-down list - Util.waitForIdle(robot); + int y = frameBounds.y + frameBounds.height; + while (!frameExited && y >= frameBounds.y) { // move to the bottom of drop-down list + robot.mouseMove(x, --y); + robot.waitForIdle(); + } - robot.mouseWheel(choice.getItemCount()); // wheel to the last item - Util.waitForIdle(robot); + if (y < frameBounds.y) { + throw new RuntimeException("Could not enter drop-down list!"); + } - // click the last item - itemChanged = false; - robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - Util.waitForIdle(robot); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - Util.waitForIdle(robot); + y -= choiceBounds.height / 2; + robot.mouseMove(x, y); // move to the last visible item in the drop-down list + robot.waitForIdle(); - if(!itemChanged || choice.getSelectedIndex() != choice.getItemCount() - 1) { - throw new RuntimeException("Mouse Wheel scroll position error!"); - } + int scrollDirection = isLWCToolkit ? -1 : 1; + // wheel to the last item + robot.mouseWheel(scrollDirection * choice.getItemCount()); + robot.waitForIdle(); - dispose(); - } catch (AWTException e) { - throw new RuntimeException("AWTException occurred - problem creating robot!"); + // click the last item + itemChanged = false; + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + + if (!itemChanged || choice.getSelectedIndex() != choice.getItemCount() - 1) { + throw new RuntimeException("Mouse Wheel scroll position error!"); } } } - diff --git a/test/jdk/java/awt/Choice/PaintArtefacts.java b/test/jdk/java/awt/Choice/PaintArtefacts.java new file mode 100644 index 000000000000..859525e8c943 --- /dev/null +++ b/test/jdk/java/awt/Choice/PaintArtefacts.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2006, 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 6405689 + * @key headful + * @summary Reg: Painting is not happening properly, + * when Choice scrollbar gets disappeared after selected item + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual PaintArtefacts +*/ + +import java.awt.Button; +import java.awt.Choice; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; + +public class PaintArtefacts { + + static boolean removeItems = true; + private static final String INSTRUCTIONS = """ + The problem is seen on XToolkit only. + Open the choice and press down or up key several times + until the scrollbar gets disappeared. + At that moment you may see a painting artefacts on dropdown menu + If you see them, press Fail. + If you don't see them press Add/Remove switch button and + again open the choice and press Up/Down key several times + until Scrollbar gets appeared back. + If you still don't see any painting artefacts press Pass. + """; + + private static Frame init() { + Frame frame = new Frame("Painting Frame"); + Button b = new Button ("Add/Remove switch"); + final Choice ch = new Choice(); + ch.add("Praveen"); + ch.add("Mohan"); + ch.add("Rakesh"); + ch.add("Menon"); + ch.add("Girish"); + ch.add("Ramachandran"); + ch.add("Elancheran"); + ch.add("Subramanian"); + ch.add("Raju"); + ch.add("Pallath"); + ch.add("Mayank"); + ch.add("Joshi"); + ch.add("Sundar"); + ch.add("Srinivas"); + ch.add("Mandalika"); + ch.add("Suresh"); + ch.add("Chandar"); + ch.select(1); + frame.setLayout(new FlowLayout()); + frame.add(ch); + frame.add(b); + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent ae) { + PassFailJFrame.log(ae.toString()); + PassFailJFrame.log("selected index = " + ch.getSelectedIndex()); + removeItems = !removeItems; + } + }); + ch.addItemListener(new ItemListener() { + public void itemStateChanged(ItemEvent ie) { + PassFailJFrame.log(ie.toString()); + PassFailJFrame.log("selected index = " + ch.getSelectedIndex()); + if (removeItems) { + PassFailJFrame.log("REMOVE : " + ch.getSelectedIndex()); + ch.remove(ch.getSelectedIndex()); + } else { + PassFailJFrame.log("ADD : "+ch.getSelectedIndex() + "/" + "new item"); + ch.add("new item"); + } + } + }); + frame.setSize(200, 200); + + for (int i = 0; i < 5; i++){ + ch.remove(ch.getSelectedIndex()); + } + + return frame; + } + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(PaintArtefacts::init) + .logArea() + .build() + .awaitAndCheck(); + } +} diff --git a/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java b/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java index b7a5cdea0720..220ddbd930c3 100644 --- a/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java +++ b/test/jdk/java/awt/Choice/PopupPosTest/PopupPosTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -95,6 +95,8 @@ public TestFrame() { pt.y + choice.getHeight()*3/4); // testing that ItemEvent doesn't generated on a simple // mouse click when the dropdown appears under mouse : 6425067 + robot.waitForIdle(); + robot.delay(250); stateChanged = false; openChoice(); closeChoice(); diff --git a/test/jdk/java/awt/Choice/SelectBetweenPressRelease.java b/test/jdk/java/awt/Choice/SelectBetweenPressRelease.java new file mode 100644 index 000000000000..21262c67922f --- /dev/null +++ b/test/jdk/java/awt/Choice/SelectBetweenPressRelease.java @@ -0,0 +1,146 @@ +/* + * 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 + * 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 6318746 + * @key headful + * @summary REG: File Selection is failing for every second selection made in the FileDlg drop-down, XToolkit +*/ + +import java.awt.Choice; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +public class SelectBetweenPressRelease { + static Frame frame; + static Choice ch; + static Robot r; + static volatile Point loc; + static volatile int selectedIndex; + + public static void main(final String[] args) throws Exception { + r = new Robot(); + try { + EventQueue.invokeAndWait(() -> init()); + r.waitForIdle(); + r.delay(1000); + test(); + } finally { + EventQueue.invokeAndWait(() -> frame.dispose()); + } + } + + private static void init() { + frame = new Frame("SelectBetweenPressRelease"); + ch = new Choice(); + ch.add("0"); + ch.add("1"); + frame.add(ch); + + frame.setLayout (new FlowLayout ()); + + addListener(); + frame.setSize(200, 200); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + frame.validate(); + } + + + private static void test() throws Exception { + EventQueue.invokeAndWait(() -> ch.select(0)); + + EventQueue.invokeAndWait(() -> { + loc = ch.getLocationOnScreen(); + }); + r.delay(1000); + r.waitForIdle(); + + r.mouseMove(loc.x+ch.getWidth()/2, loc.y+ch.getHeight()/2); + r.delay(10); + r.mousePress(InputEvent.BUTTON1_DOWN_MASK); + r.delay(100); + // This code leads to the bug + EventQueue.invokeAndWait(() -> ch.select(1)); + r.delay(100); + r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + r.delay(1000); + r.waitForIdle(); + + // 'selected' variable wich stored in the peer still equals 0 + // if the bug is reproducible + // so the next ISC to the first item by mouse will be ignored + + // try to hit the first item + if (System.getProperty("os.name").startsWith("Mac")) { + r.mouseMove(loc.x + ch.getWidth() / 2, loc.y + ch.getHeight() / 2); + } else { + r.mouseMove(loc.x + ch.getWidth() / 2, + loc.y + ch.getHeight() * 3 / 2); + } + r.delay(10); + r.mousePress(InputEvent.BUTTON1_DOWN_MASK); + r.delay(100); + r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + r.delay(1000); + r.waitForIdle(); + + EventQueue.invokeAndWait(() -> { + selectedIndex = ch.getSelectedIndex(); + }); + if (selectedIndex != 0){ + throw new RuntimeException("Test failed. ch.getSelectedIndex() = "+selectedIndex); + } + + } + + // just for logging + private static void addListener(){ + frame.addMouseListener( + new MouseAdapter(){ + public void mousePressed(MouseEvent me){ + System.out.println(me); + } + public void mouseReleased(MouseEvent me){ + System.out.println(me); + } + }); + ch.addMouseListener( + new MouseAdapter(){ + public void mousePressed(MouseEvent me){ + System.out.println(me); + } + public void mouseReleased(MouseEvent me){ + System.out.println(me); + } + }); + } + +} diff --git a/test/jdk/java/awt/Container/ActivateOnFocusTest.java b/test/jdk/java/awt/Container/ActivateOnFocusTest.java new file mode 100644 index 000000000000..ee60f985e989 --- /dev/null +++ b/test/jdk/java/awt/Container/ActivateOnFocusTest.java @@ -0,0 +1,141 @@ +/* + * 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 java.awt.Button; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.Graphics; +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.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +/* + * @test + * @bug 4111098 + * @key headful + * @summary Test for no window activation on control requestFocus() + * @run main/timeout=30 ActivateOnFocusTest + */ + +public class ActivateOnFocusTest { + static MyFrame mf1; + static Point p; + + public static void main(String[] args) throws Exception { + try { + EventQueue.invokeAndWait(() -> { + mf1 = new MyFrame(); + mf1.setBounds(100, 100, 300, 300); + mf1.mc1.requestFocusInWindow(); + }); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + EventQueue.invokeAndWait(() -> { + p = mf1.mb.getLocationOnScreen(); + }); + + robot.waitForIdle(); + + robot.mouseMove(p.x + 5, p.y + 5); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(250); + + } finally { + if (mf1 != null) { + EventQueue.invokeAndWait(mf1::dispose); + } + } + } +} + +class MyFrame extends Frame implements ActionListener { + public Button mb; + public MyComponent mc1; + public MyComponent mc2; + + public MyFrame() { + super(); + setTitle("ActivateOnFocusTest"); + setLayout(new FlowLayout()); + mb = new Button("Pull"); + mb.addActionListener(this); + add(mb); + mc1 = new MyComponent(Color.red); + add(mc1); + mc2 = new MyComponent(Color.blue); + add(mc2); + addWindowListener(new WindowAdapter() { + @Override + public void windowActivated(WindowEvent e) { + mc1.requestFocusInWindow(); + } + @Override + public void windowDeactivated(WindowEvent e) { + mc2.requestFocusInWindow(); + } + }); + setVisible(true); + } + + public void actionPerformed(ActionEvent e) { + MyFrame mf2 = new MyFrame(); + mf2.setBounds(200, 200, 300, 300); + mf2.setVisible(true); + mf2.mc1.requestFocusInWindow(); + } +} + +class MyComponent extends Component { + public MyComponent(Color c) { + super(); + setBackground(c); + } + + public void paint(Graphics g) { + Dimension d = getSize(); + g.setColor(getBackground()); + g.fillRect(0, 0, d.width, d.height); + } + + public boolean isFocusTraversable() { + return true; + } + + public Dimension getPreferredSize() { + return new Dimension(50, 50); + } +} diff --git a/test/jdk/java/awt/Container/MouseEnteredTest.java b/test/jdk/java/awt/Container/MouseEnteredTest.java new file mode 100644 index 000000000000..3bd5d3e4778e --- /dev/null +++ b/test/jdk/java/awt/Container/MouseEnteredTest.java @@ -0,0 +1,244 @@ +/* + * 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 java.awt.Component; +import java.awt.EventQueue; +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 java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import javax.swing.ButtonGroup; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JTextArea; +import javax.swing.KeyStroke; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +/* + * @test + * @bug 4159745 + * @key headful + * @summary Mediumweight popup dragging broken + * @run main MouseEnteredTest + */ + +public class MouseEnteredTest extends JFrame implements ActionListener { + static volatile MouseEnteredTest test; + static volatile Point p; + static volatile Point p2; + + static String strMotif = "Motif"; + static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; + static char cMotif = 'o'; + + static String strWindows = "Windows"; + static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; + static char cWindows = 'W'; + + static String strMetal = "Metal"; + static String metalClassName = "javax.swing.plaf.metal.MetalLookAndFeel"; + static char cMetal = 'M'; + + static JMenu m; + static JMenu menu; + + static MouseListener ml = new MouseEnteredTest.MouseEventListener(); + + public MouseEnteredTest() { + setTitle("MouseEnteredTest"); + JPopupMenu.setDefaultLightWeightPopupEnabled(false); + setJMenuBar(getMyMenuBar()); + getContentPane().add("Center", new JTextArea()); + setSize(400, 500); + setLocationRelativeTo(null); + setVisible(true); + } + + public static void main(String[] args) throws Exception { + try { + EventQueue.invokeAndWait(() -> { + test = new MouseEnteredTest(); + }); + + Robot robot = new Robot(); + robot.setAutoWaitForIdle(true); + robot.waitForIdle(); + robot.delay(1000); + + EventQueue.invokeAndWait(() -> { + p = m.getLocationOnScreen(); + p2 = menu.getLocationOnScreen(); + }); + robot.waitForIdle(); + robot.delay(250); + robot.mouseMove(p.x + 5, p.y + 10); + robot.waitForIdle(); + + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + for (int i = p.x; i < p2.x + 10; i = i + 2) { + robot.mouseMove(i, p2.y + 10); + } + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(2000); + + if (m.isPopupMenuVisible()) { + throw new RuntimeException("First menu is showing. Test Failed."); + } + } finally { + if (test != null) { + EventQueue.invokeAndWait(test::dispose); + } + } + } + + public JMenuBar getMyMenuBar() { + JMenuBar menubar; + JMenuItem menuItem; + + menubar = GetLNFMenuBar(); + + menu = menubar.add(new JMenu("Test")); + menu.setName("Test"); + menu.addMouseListener(ml); + menu.setMnemonic('T'); + menuItem = menu.add(new JMenuItem("Menu Item")); + menuItem.addActionListener(this); + menuItem.setMnemonic('M'); + menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.ALT_MASK)); + + JRadioButtonMenuItem mi = new JRadioButtonMenuItem("Radio Button"); + mi.addActionListener(this); + mi.setMnemonic('R'); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK)); + menu.add(mi); + + JCheckBoxMenuItem mi1 = new JCheckBoxMenuItem("Check Box"); + mi1.addActionListener(this); + mi1.setMnemonic('C'); + mi1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK)); + menu.add(mi1); + return menubar; + } + + public void actionPerformed(ActionEvent e) { + String str = e.getActionCommand(); + if (str.equals(metalClassName) || str.equals(windowsClassName) || str.equals(motifClassName)) { + changeLNF(str); + } else { + System.out.println("ActionEvent: " + str); + } + } + + public void changeLNF(String str) { + System.out.println("Changing LNF to " + str); + try { + UIManager.setLookAndFeel(str); + SwingUtilities.updateComponentTreeUI(this); + pack(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public JMenuBar GetLNFMenuBar() { + JMenuBar mbar = new JMenuBar(); + m = new JMenu("Look and Feel"); + m.setName("Look and Feel"); + m.addMouseListener(ml); + m.setMnemonic('L'); + ButtonGroup bg = new ButtonGroup(); + + JRadioButtonMenuItem mi; + + mi = new JRadioButtonMenuItem(strMetal); + mi.addActionListener(this); + mi.setActionCommand(metalClassName); + mi.setMnemonic(cMetal); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK)); + mi.setSelected(true); + bg.add(mi); + m.add(mi); + + mi = new JRadioButtonMenuItem(strWindows); + mi.addActionListener(this); + mi.setActionCommand(windowsClassName); + mi.setMnemonic(cWindows); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK)); + bg.add(mi); + m.add(mi); + + mi = new JRadioButtonMenuItem(strMotif); + mi.addActionListener(this); + mi.setActionCommand(motifClassName); + mi.setMnemonic(cMotif); + mi.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.ALT_MASK)); + bg.add(mi); + m.add(mi); + + mbar.add(m); + return mbar; + } + + static class MouseEventListener implements MouseListener, MouseMotionListener { + public void mouseClicked(MouseEvent e) { + System.out.println("In mouseClicked for " + e.getComponent().getName()); + } + + public void mousePressed(MouseEvent e) { + Component c = e.getComponent(); + System.out.println("In mousePressed for " + c.getName()); + } + + public void mouseReleased(MouseEvent e) { + System.out.println("In mouseReleased for " + e.getComponent().getName()); + } + + public void mouseEntered(MouseEvent e) { + System.out.println("In mouseEntered for " + e.getComponent().getName()); + System.out.println("MouseEvent:" + e.getComponent()); + } + + public void mouseExited(MouseEvent e) { + System.out.println("In mouseExited for " + e.getComponent().getName()); + } + + public void mouseDragged(MouseEvent e) { + System.out.println("In mouseDragged for " + e.getComponent().getName()); + } + + public void mouseMoved(MouseEvent e) { + System.out.println("In mouseMoved for " + e.getComponent().getName()); + } + } +} diff --git a/test/jdk/java/awt/Container/ValidateTest.java b/test/jdk/java/awt/Container/ValidateTest.java new file mode 100644 index 000000000000..935766094cf7 --- /dev/null +++ b/test/jdk/java/awt/Container/ValidateTest.java @@ -0,0 +1,78 @@ +/* + * 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 java.awt.EventQueue; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Panel; + +/* + * @test + * @bug 4136190 + * @requires (os.family == "windows") + * @summary Recursive validation calls would cause major USER resource leakage + * @key headful + * @run main/timeout=30 ValidateTest + */ + +public class ValidateTest { + static Frame frame; + + public static void main(String args[]) throws Exception { + try { + EventQueue.invokeAndWait(() -> { + createGUI(); + }); + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + public static void createGUI() { + frame = new Frame("Test for 4136190 : JVM and win95 resource leakage issues"); + frame.setLayout(new GridLayout(1, 1)); + MyPanel panel = new MyPanel(); + frame.add(panel); + frame.invalidate(); + frame.validate(); + frame.setSize(500, 400); + frame.setVisible(true); + } + + static class MyPanel extends Panel { + int recurseCounter = 0; + + public void validate() { + recurseCounter++; + if (recurseCounter >= 100) { + return; + } + getParent().validate(); + super.validate(); + } + } +} \ No newline at end of file diff --git a/test/jdk/java/awt/Dialog/ClosingParentTest.java b/test/jdk/java/awt/Dialog/ClosingParentTest.java new file mode 100644 index 000000000000..9b2750ab95fa --- /dev/null +++ b/test/jdk/java/awt/Dialog/ClosingParentTest.java @@ -0,0 +1,100 @@ +/* + * 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.Dialog; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowEvent; +import java.awt.event.WindowAdapter; + +/* + * @test + * @bug 4336913 + * @summary On Windows, disable parent window controls while modal dialog is being created. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual ClosingParentTest + */ + +public class ClosingParentTest { + + static String instructions = """ + When the test starts, you will see a Frame with a Button + titled 'Show modal dialog with delay'. Press this button + and before the modal Dialog is shown, try to close the + Frame using X button or system menu for windowing systems + which don't provide X button in Window decorations. The + delay before Dialog showing is 5 seconds. + If in test output you see message about WINDOW_CLOSING + being dispatched, then test fails. If no such message + is printed, the test passes. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("ClosingParentTest") + .instructions(instructions) + .testTimeOut(5) + .rows(10) + .columns(35) + .testUI(ClosingParentTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame frame = new Frame("Main Frame"); + Dialog dialog = new Dialog(frame, true); + + Button button = new Button("Show modal dialog with delay"); + button.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + try { + Thread.currentThread().sleep(5000); + } catch (InterruptedException x) { + x.printStackTrace(); + } + + dialog.setVisible(true); + } + }); + frame.add(button); + frame.pack(); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.out.println("WINDOW_CLOSING dispatched on the frame"); + } + }); + + dialog.setSize(100, 100); + dialog.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + dialog.dispose(); + } + }); + + return frame; + } +} diff --git a/test/jdk/java/awt/Dialog/DefaultIconTest.java b/test/jdk/java/awt/Dialog/DefaultIconTest.java new file mode 100644 index 000000000000..8d2ec8c406f0 --- /dev/null +++ b/test/jdk/java/awt/Dialog/DefaultIconTest.java @@ -0,0 +1,71 @@ +/* + * 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 + * 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; + +/* + * @test + * @bug 4964237 + * @requires (os.family == "windows") + * @summary Win: Changing theme changes java dialogs title icon + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual DefaultIconTest + */ + +public class DefaultIconTest { + static String instructions = """ + This test shows frame and two dialogs + Change windows theme. Resizable dialog should retain default icon + Non-resizable dialog should retain no icon + Press PASS if icons look correct, FAIL otherwise + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("ShownModalDialogSerializationTest Instructions") + .instructions(instructions) + .testTimeOut(5) + .rows(10) + .columns(35) + .testUI(DefaultIconTest::createGUIs) + .build() + .awaitAndCheck(); + } + + public static Frame createGUIs() { + Frame f = new Frame("DefaultIconTest"); + f.setSize(200, 100); + Dialog d1 = new Dialog(f, "Resizable Dialog, should show default icon"); + d1.setSize(200, 100); + d1.setVisible(true); + d1.setLocation(0, 150); + Dialog d2 = new Dialog(f, "Non-resizable dialog, should have no icon"); + d2.setSize(200, 100); + d2.setVisible(true); + d2.setResizable(false); + d2.setLocation(0, 300); + return f; + } +} diff --git a/test/jdk/java/awt/Dialog/DialogDisposeLeak.java b/test/jdk/java/awt/Dialog/DialogDisposeLeak.java new file mode 100644 index 000000000000..9d581519de36 --- /dev/null +++ b/test/jdk/java/awt/Dialog/DialogDisposeLeak.java @@ -0,0 +1,200 @@ +/* + * 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 java.awt.AWTEvent; +import java.awt.Button; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Label; +import java.awt.Toolkit; +import java.awt.event.MouseEvent; +import java.awt.event.FocusEvent; +import java.awt.event.MouseAdapter; + +/* + * @test + * @bug 4193022 + * @summary Test for bug(s): 4193022, disposing dialog leaks memory + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual DialogDisposeLeak + */ + +public class DialogDisposeLeak { + private static final String INSTRUCTIONS = """ + Click on the Dialog... button in the frame that appears. + Now dismiss the dialog by clicking on the label in the dialog. + + Repeat this around 10 times. At some point the label in the frame should change + to indicated that the dialog has been garbage collected and the test passed. + """; + + public static void main(String args[]) throws Exception { + Frame frame = new DisposeFrame(); + PassFailJFrame.builder() + .title("DialogDisposeLeak") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(frame) + .build() + .awaitAndCheck(); + } +} + +class DisposeFrame extends Frame { + Label label = new Label("Test not passed yet"); + + DisposeFrame() { + super("DisposeLeak test"); + setLayout(new FlowLayout()); + Button btn = new Button("Dialog..."); + add(btn); + btn.addActionListener(ev -> { + Dialog dlg = new DisposeDialog(DisposeFrame.this); + dlg.setVisible(true); + } + ); + add(label); + pack(); + } + + public void testOK() { + label.setText("Test has passed. Dialog finalized."); + } +} + +class DisposeDialog extends Dialog { + DisposeDialog(Frame frame) { + super(frame, "DisposeDialog", true); + setLocation(frame.getX(), frame.getY()); + + setLayout(new FlowLayout()); + LightweightComp lw = new LightweightComp("Click here to dispose"); + lw.addMouseListener( + new MouseAdapter() { + public void mouseEntered(MouseEvent ev) { + System.out.println("Entered lw"); + } + + public void mouseExited(MouseEvent ev) { + System.out.println("Exited lw"); + } + + public void mouseReleased(MouseEvent ev) { + System.out.println("Released lw"); + DisposeDialog.this.dispose(); + // try to force GC and finalization + for (int n = 0; n < 100; n++) { + byte[] bytes = new byte[1024 * 1024 * 8]; + System.gc(); + } + } + } + ); + add(lw); + pack(); + } + + public void finalize() { + ((DisposeFrame) getParent()).testOK(); + } +} + +// simple lightweight component, focus traversable, highlights upon focus +class LightweightComp extends Component { + FontMetrics fm; + String label; + private static final int FOCUS_GONE = 0; + private static final int FOCUS_TEMP = 1; + private static final int FOCUS_HAVE = 2; + int focusLevel = FOCUS_GONE; + public static int nameCounter = 0; + + public LightweightComp(String lwLabel) { + label = lwLabel; + enableEvents(AWTEvent.FOCUS_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); + setName("lw" + nameCounter++); + } + + public Dimension getPreferredSize() { + if (fm == null) fm = Toolkit.getDefaultToolkit().getFontMetrics(getFont()); + return new Dimension(fm.stringWidth(label) + 2, fm.getHeight() + 2); + } + + public void paint(Graphics g) { + Dimension s = getSize(); + + // erase the background + g.setColor(getBackground()); + g.fillRect(0, 0, s.width, s.height); + + g.setColor(getForeground()); + + // draw the string + g.drawString(label, 2, fm.getHeight()); + + // draw a focus rectangle + if (focusLevel > FOCUS_GONE) { + if (focusLevel == FOCUS_TEMP) { + g.setColor(Color.gray); + } else { + g.setColor(Color.blue); + } + } else { + g.setColor(Color.black); + } + g.drawRect(1, 1, s.width - 2, s.height - 2); + } + + public boolean isFocusTraversable() { + return true; + } + + protected void processFocusEvent(FocusEvent e) { + super.processFocusEvent(e); + if (e.getID() == FocusEvent.FOCUS_GAINED) { + focusLevel = FOCUS_HAVE; + } else { + if (e.isTemporary()) { + focusLevel = FOCUS_TEMP; + } else { + focusLevel = FOCUS_GONE; + } + } + repaint(); + } + + protected void processMouseEvent(MouseEvent e) { + if (e.getID() == MouseEvent.MOUSE_PRESSED) { + requestFocus(); + } + super.processMouseEvent(e); + } +} + diff --git a/test/jdk/java/awt/Dialog/DialogInitialResizability.java b/test/jdk/java/awt/Dialog/DialogInitialResizability.java new file mode 100644 index 000000000000..7ecde39c4add --- /dev/null +++ b/test/jdk/java/awt/Dialog/DialogInitialResizability.java @@ -0,0 +1,96 @@ +/* + * 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 + * 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.Dimension; +import java.awt.Frame; +import java.awt.event.ComponentEvent; +import java.awt.event.ComponentListener; + +/* + * @test + * @bug 4912551 + * @summary Checks that with resizable set to false before show() + * dialog can not be resized. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual DialogInitialResizability + */ + +public class DialogInitialResizability { + static String instructions = """ + When this test is run a dialog will display (setResizable Test). + This dialog should not be resizable. + + Additionally ensure that there are NO componentResized events in the log section. + If the above conditions are true, then Press PASS else FAIL. + """; + + private static final Dimension INITIAL_SIZE = new Dimension(400, 150); + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("DialogInitialResizability") + .instructions(instructions) + .testTimeOut(5) + .rows((int) instructions.lines().count() + 2) + .columns(40) + .testUI(DialogInitialResizability::createGUI) + .logArea() + .build() + .awaitAndCheck(); + } + + public static MyDialog createGUI() { + Frame f = new Frame("invisible dialog owner"); + + MyDialog ld = new MyDialog(f); + ld.setBounds(100, 100, INITIAL_SIZE.width, INITIAL_SIZE.height); + ld.setResizable(false); + + PassFailJFrame.log("Dialog isResizable is set to: " + ld.isResizable()); + PassFailJFrame.log("Dialog Initial Size " + ld.getSize()); + return ld; + } + + private static class MyDialog extends Dialog implements ComponentListener { + public MyDialog(Frame f) { + super(f, "setResizable test", false); + this.addComponentListener(this); + } + + public void componentResized(ComponentEvent e) { + if (!e.getComponent().getSize().equals(INITIAL_SIZE)) { + PassFailJFrame.log("Component Resized. Test Failed!!"); + } + } + + public void componentMoved(ComponentEvent e) { + } + + public void componentShown(ComponentEvent e) { + } + + public void componentHidden(ComponentEvent e) { + } + } +} diff --git a/test/jdk/java/awt/Dialog/FileDialogEmptyTitleTest.java b/test/jdk/java/awt/Dialog/FileDialogEmptyTitleTest.java new file mode 100644 index 000000000000..d288a7c18f65 --- /dev/null +++ b/test/jdk/java/awt/Dialog/FileDialogEmptyTitleTest.java @@ -0,0 +1,59 @@ +/* + * 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 java.awt.FileDialog; +import java.awt.Frame; + +/* + * @test + * @bug 4177831 + * @summary solaris: default FileDialog title is not empty + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FileDialogEmptyTitleTest + */ + +public class FileDialogEmptyTitleTest { + static String instructions = """ + Test passes if title of file dialog is empty, + otherwise test failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("FileDialogEmptyTitleTest") + .instructions(instructions) + .testTimeOut(5) + .rows(10) + .columns(35) + .testUI(FileDialogEmptyTitleTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static FileDialog createGUI() { + Frame frame = new Frame("invisible dialog owner"); + FileDialog fileDialog = new FileDialog(frame); + return fileDialog; + } +} diff --git a/test/jdk/java/awt/Dialog/FileDialogTest.java b/test/jdk/java/awt/Dialog/FileDialogTest.java new file mode 100644 index 000000000000..4ac937d773d8 --- /dev/null +++ b/test/jdk/java/awt/Dialog/FileDialogTest.java @@ -0,0 +1,189 @@ +/* + * 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 java.awt.Button; +import java.awt.Container; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4105025 4153487 4177107 4146229 4119383 4181310 4152317 + * @summary Test: FileDialogTest + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FileDialogTest + */ + +public class FileDialogTest extends Panel implements ActionListener { + Button buttonShow, buttonNullShow, buttonShowHide, buttonShowDispose; + TextField fieldFile; + TextField fieldDir; + TextField fieldTitle; + private static final String INSTRUCTIONS = """ + 1. Set file, directory, and title fields to some real values + Title will not show on macos dialog + 2. Click the "Get File..." button. + 3. Verify that dialog is set to proper file and directory, and that + title is also set. + 4. Select a file and OK the dialog + (or whatever the selection button is). + 5. Verify that the file and directory fields reflect the file chosen. + 6. Now, click the "Get null File with null Directory..." button. + 7. Verify that the file list matches the listed directory. + 8. Cancel or OK the dialog. + 9. Verify that no NullPointerException is thrown. + 10. Now, click the "Show FileDialog, then hide() in 5 s..." button. + 11. Wait for 5 seconds. The FileDialog should then + disappear automatically. + 12. 12-14 are Windows specific. Set file to some invalid value, + like "/<>++". + 13. Click the "Get File..." button. + 14. Verify that FileDialog is shown with empty "file" field. + 15. Run the test on different locales. Verify that filter string + "All Files" is localized. + """; + + public static void main(String args[]) throws Exception { + Frame frame = new Frame("FileDialogTest"); + frame.setLayout(new GridLayout()); + frame.add(new FileDialogTest()); + frame.pack(); + + PassFailJFrame.builder() + .title("FileDialogTest") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(frame) + .build() + .awaitAndCheck(); + } + + public FileDialogTest() { + setLayout(new GridLayout(6, 2)); + + buttonShow = new Button("Get File..."); + add(buttonShow); + buttonNullShow = new Button("Get null File with null Directory..."); + add(buttonNullShow); + buttonShowHide = new Button("Show FileDialog, then hide() in 5 s..."); + add(buttonShowHide); + buttonShowDispose = + new Button("Show FileDialog, then dispose() in 5 s..."); + add(buttonShowDispose); + + add(new Label("")); + add(new Label("")); + + add(new Label("File:")); + fieldFile = new TextField(20); + add(fieldFile); + + add(new Label("Directory:")); + fieldDir = new TextField(20); + add(fieldDir); + + add(new Label("Title:")); + fieldTitle = new TextField(20); + fieldTitle.setText("TestTitle"); + add(fieldTitle); + + buttonShow.addActionListener(this); + buttonNullShow.addActionListener(this); + buttonShowHide.addActionListener(this); + buttonShowDispose.addActionListener(this); + } + + public void actionPerformed(ActionEvent evt) { + if (evt.getSource() == buttonShow) { + FileDialog fd = new FileDialog(getFrame(), fieldTitle.getText()); + fd.setFile(fieldFile.getText()); + fd.setDirectory(fieldDir.getText()); + fd.show(); + System.out.println("back from show"); + fieldFile.setText(fd.getFile()); + fieldDir.setText(fd.getDirectory()); + fd.dispose(); + } else if (evt.getSource() == buttonNullShow) { + FileDialog fd = new FileDialog(getFrame(), fieldTitle.getText()); + fd.setFile(null); + fd.setDirectory(null); + fd.show(); + System.out.println("back from show"); + fieldFile.setText(fd.getFile()); + fieldDir.setText(fd.getDirectory()); + fd.setFile(null); + fd.setDirectory(null); + fd.dispose(); + } else if (evt.getSource() == buttonShowHide) { + final FileDialog fd = new FileDialog(getFrame(), + fieldTitle.getText()); + fd.setFile(fieldFile.getText()); + fd.setDirectory(fieldDir.getText()); + new Thread(new Runnable() { + public void run() { + try { + Thread.currentThread().sleep(5000); + } catch (InterruptedException ex) { + } + fd.hide(); + } + }).start(); + fd.show(); + System.out.println("back from show"); + fd.dispose(); + } else if (evt.getSource() == buttonShowDispose) { + final FileDialog fd = new FileDialog(getFrame(), + fieldTitle.getText()); + fd.setFile(fieldFile.getText()); + fd.setDirectory(fieldDir.getText()); + new Thread(() -> { + try { + Thread.currentThread().sleep(5000); + } catch (InterruptedException ex) { + } + fd.dispose(); + }).start(); + fd.show(); + System.out.println("back from show"); + fd.dispose(); + } + } + + private Frame getFrame() { + Container cont = getParent(); + while (cont != null) { + if (cont instanceof Frame) { + return (Frame) cont; + } + cont = cont.getParent(); + } + return null; + } +} diff --git a/test/jdk/java/awt/Dialog/FileDialogUIUpdate.java b/test/jdk/java/awt/Dialog/FileDialogUIUpdate.java new file mode 100644 index 000000000000..f97d947991b4 --- /dev/null +++ b/test/jdk/java/awt/Dialog/FileDialogUIUpdate.java @@ -0,0 +1,83 @@ +/* + * 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 + * 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.Button; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4859390 + * @requires (os.family == "windows") + * @summary Verify that FileDialog matches the look + of the native windows FileDialog + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual FileDialogUIUpdate + */ + +public class FileDialogUIUpdate extends Frame { + static String instructions = """ + Click the button to show the FileDialog. Then open the Paint + application (usually found in Program Files->Accessories). + Select File->Open from Paint to display a native Open dialog. + Compare the native dialog to the AWT FileDialog. + Specifically, confirm that the Places Bar icons are along the left side (or + not, if the native dialog doesn't have them), and that the + dialogs are both resizable (or not). + If the file dialogs both look the same press Pass. If not, + press Fail. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("FileDialogUIUpdate") + .instructions(instructions) + .testTimeOut(5) + .rows(12) + .columns(35) + .testUI(FileDialogUIUpdate::new) + .build() + .awaitAndCheck(); + } + + public FileDialogUIUpdate() { + final FileDialog fd = new FileDialog(new Frame("FileDialogUIUpdate frame"), + "Open FileDialog"); + Button showButton = new Button("Show FileDialog"); + setLayout(new BorderLayout()); + + fd.setDirectory("c:/"); + showButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + fd.setVisible(true); + } + }); + + add(showButton); + setSize(200, 200); + } +} diff --git a/test/jdk/java/awt/Dialog/MenuAndModalDialogTest.java b/test/jdk/java/awt/Dialog/MenuAndModalDialogTest.java new file mode 100644 index 000000000000..c22116ff8df1 --- /dev/null +++ b/test/jdk/java/awt/Dialog/MenuAndModalDialogTest.java @@ -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.Button; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4070085 + * @summary Java program locks up X server + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual MenuAndModalDialogTest + */ + +public class MenuAndModalDialogTest { + static Frame frame; + static String instructions = """ + 1. Bring up the File Menu and leave it up. + 2. In a few seconds, the modal dialog will appear. + 3. Verify that your system does not lock up when you push the "OK" button. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame pf = PassFailJFrame.builder() + .title("MenuAndModalDialogTest") + .instructions(instructions) + .testTimeOut(5) + .rows(10) + .columns(35) + .testUI(MenuAndModalDialogTest::createFrame) + .build(); + + // Allow time to pop up the menu + try { + Thread.currentThread().sleep(5000); + } catch (InterruptedException exception) { + } + + createDialog(); + pf.awaitAndCheck(); + } + + public static Frame createFrame() { + frame = new Frame("MenuAndModalDialogTest frame"); + + MenuBar menuBar = new MenuBar(); + frame.setMenuBar(menuBar); + + Menu file = new Menu("File"); + menuBar.add(file); + + MenuItem menuItem = new MenuItem("A Menu Entry"); + file.add(menuItem); + + frame.setSize(200, 200); + frame.setLocationRelativeTo(null); + return frame; + } + + public static void createDialog() { + Dialog dialog = new Dialog(frame); + + Button button = new Button("OK"); + dialog.add(button); + button.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + dialog.dispose(); + } + } + ); + + dialog.setSize(200, 200); + dialog.setModal(true); + dialog.setVisible(true); + } +} diff --git a/test/jdk/java/awt/Dialog/ModalExcludedTest.java b/test/jdk/java/awt/Dialog/ModalExcludedTest.java new file mode 100644 index 000000000000..2531c26d3bc3 --- /dev/null +++ b/test/jdk/java/awt/Dialog/ModalExcludedTest.java @@ -0,0 +1,315 @@ +/* + * 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 + * 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.Button; +import java.awt.Dialog; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.JobAttributes; +import java.awt.PageAttributes; +import java.awt.Panel; +import java.awt.PrintJob; +import java.awt.TextArea; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; + +import sun.awt.SunToolkit; + +/* + * @test + * @bug 4813288 4866704 + * @summary Test for "modal exclusion" functionality + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame + * @modules java.desktop/sun.awt + * @run main/manual ModalExcludedTest + */ + +public class ModalExcludedTest { + private static final String INSTRUCTIONS = """ + 1. Press 'Modal dialog w/o modal excluded' button below + A window, a modeless dialog and a modal dialog will appear + Make sure the frame and the modeless dialog are inaccessible, + i.e. receive no mouse and keyboard events. MousePressed and + KeyPressed events are logged in the text area - use it + to watch events + Close all 3 windows + + 2. Press 'Modal dialog w/ modal excluded' button below + Again, 3 windows will appear (frame, dialog, modal dialog), + but the frame and the dialog would be modal excluded, i.e. + behave the same way as there is no modal dialog shown. Verify + this by pressing mouse buttons and typing any keys. The + RootFrame would be modal blocked - verify this too + Close all 3 windows + + 3. Repeat step 2 for file and print dialogs using appropriate + buttons below + + Notes: if there is no printer installed in the system you may not + get any print dialogs + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("ModalExcludedTest") + .instructions(INSTRUCTIONS) + .rows(10) + .columns(35) + .testUI(ModalExcludedTest::createGUIs) + .build() + .awaitAndCheck(); + } + + public static Frame createGUIs() { + final Frame f = new Frame("RootFrame"); + f.setBounds(0, 0, 480, 500); + f.setLayout(new BorderLayout()); + + final TextArea messages = new TextArea(); + + final WindowListener wl = new WindowAdapter() { + public void windowClosing(WindowEvent ev) { + if (ev.getSource() instanceof Window) { + ((Window) ev.getSource()).dispose(); + } + } + }; + final MouseListener ml = new MouseAdapter() { + public void mousePressed(MouseEvent ev) { + messages.append(ev + "\n"); + } + }; + final KeyListener kl = new KeyAdapter() { + public void keyPressed(KeyEvent ev) { + messages.append(ev + "\n"); + } + }; + + if (!SunToolkit.isModalExcludedSupported()) { + throw new jtreg.SkippedException("Modal exclude is not supported on this platform."); + } + + messages.addMouseListener(ml); + messages.addKeyListener(kl); + f.add(messages, BorderLayout.CENTER); + + Panel buttons = new Panel(); + buttons.setLayout(new GridLayout(6, 1)); + + Button b = new Button("Modal dialog w/o modal excluded"); + b.addActionListener(ev -> { + Frame ff = new Frame("Non-modal-excluded frame"); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + ff.setVisible(true); + + Dialog dd = new Dialog(ff, "Non-modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + + Dialog d = new Dialog(f, "Modal dialog", true); + d.setBounds(600, 200, 200, 100); + d.addWindowListener(wl); + d.addMouseListener(ml); + d.addKeyListener(kl); + d.setVisible(true); + }); + buttons.add(b); + + Button c = new Button("Modal dialog w/ modal excluded"); + c.addActionListener(ev -> { + JFrame ff = new JFrame("Modal-excluded frame"); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + JMenuBar mb = new JMenuBar(); + JMenu m = new JMenu("Test menu"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + m.add("Test menu item"); + mb.add(m); + ff.setJMenuBar(mb); + // 1: set visible + ff.setVisible(true); + + Dialog dd = new Dialog(ff, "Modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + + // 2: set modal excluded + SunToolkit.setModalExcluded(ff); + + Dialog d = new Dialog(f, "Modal dialog", true); + d.setBounds(600, 200, 200, 100); + d.addWindowListener(wl); + d.addMouseListener(ml); + d.addKeyListener(kl); + d.setVisible(true); + }); + buttons.add(c); + + Button c1 = new Button("Modal dialog before modal excluded"); + c1.addActionListener(ev -> { + // 1: create dialog + Dialog d = new Dialog(f, "Modal dialog", true); + d.setBounds(600, 200, 200, 100); + d.addWindowListener(wl); + d.addMouseListener(ml); + d.addKeyListener(kl); + + // 2: create frame + Frame ff = new Frame("Modal-excluded frame"); + // 3: set modal excluded + SunToolkit.setModalExcluded(ff); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + // 4: show frame + ff.setVisible(true); + + Dialog dd = new Dialog(ff, "Modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + + // 5: show dialog + d.setVisible(true); + }); + buttons.add(c1); + + Button d = new Button("File dialog w/ modal excluded"); + d.addActionListener(ev -> { + Frame ff = new Frame("Modal-excluded frame"); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + // 1: set modal excluded (peer is not created yet) + SunToolkit.setModalExcluded(ff); + // 2: set visible + ff.setVisible(true); + + Dialog dd = new Dialog(ff, "Modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + SunToolkit.setModalExcluded(dd); + + Dialog d1 = new FileDialog(f, "File dialog"); + d1.setVisible(true); + }); + buttons.add(d); + + Button e = new Button("Native print dialog w/ modal excluded"); + e.addActionListener(ev -> { + Frame ff = new Frame("Modal-excluded frame"); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + ff.setVisible(true); + SunToolkit.setModalExcluded(ff); + + Dialog dd = new Dialog(ff, "Modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + + JobAttributes jobAttributes = new JobAttributes(); + jobAttributes.setDialog(JobAttributes.DialogType.NATIVE); + PageAttributes pageAttributes = new PageAttributes(); + PrintJob job = Toolkit.getDefaultToolkit().getPrintJob(f, "Test", jobAttributes, pageAttributes); + }); + buttons.add(e); + + Button g = new Button("Common print dialog w/ modal excluded"); + g.addActionListener(ev -> { + Frame ff = new Frame("Modal-excluded frame"); + ff.setBounds(400, 0, 200, 100); + ff.addWindowListener(wl); + ff.addMouseListener(ml); + ff.addKeyListener(kl); + ff.setVisible(true); + SunToolkit.setModalExcluded(ff); + ff.dispose(); + // modal excluded must still be alive + ff.setVisible(true); + + Dialog dd = new Dialog(ff, "Modal-excluded dialog", false); + dd.setBounds(500, 100, 200, 100); + dd.addWindowListener(wl); + dd.addMouseListener(ml); + dd.addKeyListener(kl); + dd.setVisible(true); + + JobAttributes jobAttributes = new JobAttributes(); + jobAttributes.setDialog(JobAttributes.DialogType.COMMON); + PageAttributes pageAttributes = new PageAttributes(); + PrintJob job = Toolkit.getDefaultToolkit().getPrintJob(f, "Test", jobAttributes, pageAttributes); + }); + buttons.add(g); + + f.add(buttons, BorderLayout.SOUTH); + return f; + } +} diff --git a/test/jdk/java/awt/Dialog/NestedDialogTest.java b/test/jdk/java/awt/Dialog/NestedDialogTest.java new file mode 100644 index 000000000000..28fb1bc919e6 --- /dev/null +++ b/test/jdk/java/awt/Dialog/NestedDialogTest.java @@ -0,0 +1,312 @@ +/* + * 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 java.awt.Button; +import java.awt.Choice; +import java.awt.Dialog; +import java.awt.FileDialog; +import java.awt.FlowLayout; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.List; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Vector; +import java.util.Enumeration; + +/* + * @test + * @bug 4110094 4178930 4178390 + * @summary Test: Rewrite of Win modal dialogs + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual NestedDialogTest + */ + +public class NestedDialogTest { + private static Vector windows = new Vector(); + static String instructions = """ + To solve various race conditions, windows modal dialogs were rewritten. This + test exercises various modal dialog boundary conditions and checks that + previous fixes to modality are incorporated in the rewrite. + + Check the following: + - No IllegalMonitorStateException is thrown when a dialog closes + + - Open multiple nested dialogs and verify that all other windows + are disabled when modal dialog is active. + + - Check that the proper window is activated when a modal dialog closes. + + - Close nested dialogs out of order (e.g. close dialog1 before dialog2) + and verify that this works and no deadlock occurs. + + - Check that all other windows are disabled when a FileDialog is open. + + - Check that the proper window is activated when a FileDialog closes. + + - Verify that the active window nevers switches to another application + when closing dialogs, even temporarily. + + - Check that choosing Hide always sucessfully hides a dialog. You should + try this multiple times to catch any race conditions. + + - Check that the scrollbar on the Choice component in the dialog works, as opposed + to just using drag-scrolling or the cursor keys + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("NestedDialogTest") + .instructions(instructions) + .testTimeOut(5) + .rows((int) instructions.lines().count() + 2) + .columns(35) + .testUI(NestedDialogTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame frame1 = new NestedDialogTestFrame("frame0"); + Frame frame2 = new NestedDialogTestFrame("frame1"); + frame2.setLocation(100, 100); + return frame1; + } + + public static void addWindow(Window window) { + // System.out.println("Pushing window " + window); + windows.removeElement(window); + windows.addElement(window); + } + + public static void removeWindow(Window window) { + // System.out.println("Popping window " + window); + windows.removeElement(window); + } + + public static Window getWindow(int index) { + return (Window) windows.elementAt(index); + } + + public static Enumeration enumWindows() { + return windows.elements(); + } + + public static int getWindowIndex(Window win) { + return windows.indexOf(win); + } +} + +class NestedDialogTestFrame extends Frame { + NestedDialogTestFrame(String name) { + super(name); + setSize(200, 200); + show(); + + setLayout(new FlowLayout()); + Button btnDlg = new Button("Dialog..."); + add(btnDlg); + Button btnFileDlg = new Button("FileDialog..."); + add(btnFileDlg); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent ev) { + System.exit(0); + } + }); + + btnDlg.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + Dialog d1 = new SimpleDialog(NestedDialogTestFrame.this, null, true); + System.out.println("Returned from showing dialog: " + d1); + } + } + ); + + btnFileDlg.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + FileDialog dlg = new FileDialog(NestedDialogTestFrame.this); + dlg.show(); + } + } + ); + + validate(); + } + + public void show() { + if (!isVisible()) { + NestedDialogTest.addWindow(this); + } + super.show(); + } + + public void dispose() { + NestedDialogTest.removeWindow(this); + super.dispose(); + } +} + +class SimpleDialog extends Dialog { + Button btnNested; + Button btnFileDlg; + Button btnShow; + Button btnHide; + Button btnDispose; + Button btnExit; + List listWins; + Dialog dlgPrev; + + public SimpleDialog(Frame frame, Dialog prev, boolean isModal) { + super(frame, "", isModal); + + dlgPrev = prev; + + addWindowListener(new WindowAdapter() { + public void windowActivated(WindowEvent ev) { + populateListWin(); + } + }); + + setTitle(getName()); + + Panel panelNorth = new Panel(); + panelNorth.setLayout(new GridLayout(1, 1)); + listWins = new List(); + panelNorth.add(listWins); + + Panel panelSouth = new Panel(); + panelSouth.setLayout(new FlowLayout()); + btnNested = new Button("Dialog..."); + panelSouth.add(btnNested); + btnFileDlg = new Button("FileDialog..."); + panelSouth.add(btnFileDlg); + btnShow = new Button("Show"); + panelSouth.add(btnShow); + btnHide = new Button("Hide"); + panelSouth.add(btnHide); + btnDispose = new Button("Dispose"); + panelSouth.add(btnDispose); + + Choice cbox = new Choice(); + cbox.add("Test1"); + cbox.add("Test2"); + cbox.add("Test3"); + cbox.add("Test4"); + cbox.add("Test5"); + cbox.add("Test6"); + cbox.add("Test7"); + cbox.add("Test8"); + cbox.add("Test9"); + cbox.add("Test10"); + cbox.add("Test11"); + panelSouth.add(cbox); + + validate(); + + add("Center", panelNorth); + add("South", panelSouth); + + btnNested.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Dialog dlg = new SimpleDialog((Frame) getParent(), SimpleDialog.this, true); + System.out.println("Returned from showing dialog: " + dlg); + } + }); + + btnFileDlg.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + FileDialog dlg = new FileDialog((Frame) getParent()); + dlg.show(); + } + }); + + btnHide.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Window wnd = getSelectedWindow(); + System.out.println(wnd); + wnd.hide(); + } + }); + + btnShow.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + getSelectedWindow().show(); + } + }); + + btnDispose.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + getSelectedWindow().dispose(); + populateListWin(); + } + }); + + pack(); + setSize(getSize().width, getSize().height * 2); + if (dlgPrev != null) { + Point pt = dlgPrev.getLocation(); + setLocation(pt.x + 30, pt.y + 50); + } + show(); + } + + private Window getSelectedWindow() { + Window window; + int index = listWins.getSelectedIndex(); + + window = NestedDialogTest.getWindow(index); + return window; + } + + private void populateListWin() { + Enumeration enumWindows = NestedDialogTest.enumWindows(); + + listWins.removeAll(); + while (enumWindows.hasMoreElements()) { + Window win = (Window) enumWindows.nextElement(); + listWins.add(win.getName()); + } + listWins.select(NestedDialogTest.getWindowIndex(this)); + } + + public void show() { + if (!isVisible()) { + NestedDialogTest.addWindow(this); + } + super.show(); + } + + public void dispose() { + NestedDialogTest.removeWindow(this); + super.dispose(); + } +} diff --git a/test/jdk/java/awt/Dialog/ShownModalDialogSerializationTest.java b/test/jdk/java/awt/Dialog/ShownModalDialogSerializationTest.java new file mode 100644 index 000000000000..b57dd2cf8f23 --- /dev/null +++ b/test/jdk/java/awt/Dialog/ShownModalDialogSerializationTest.java @@ -0,0 +1,92 @@ +/* + * 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. + */ + +import java.awt.Dialog; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Label; + +import java.awt.TextArea; +import java.io.File; +import java.io.FileOutputStream; +import java.io.ObjectOutputStream; + +/* + * @test + * @bug 4739757 + * @summary REGRESSION: Modal Dialog is not serializable after showing + * @key headful + * @run main ShownModalDialogSerializationTest + */ + +public class ShownModalDialogSerializationTest { + static volatile Frame frame; + static volatile Frame outputFrame; + static volatile Dialog dialog; + + public static void main(String[] args) throws Exception { + + EventQueue.invokeLater(ShownModalDialogSerializationTest::createTestUI); + + while (dialog == null || !dialog.isShowing()) { + Thread.sleep(500); + } + File file = new File("dialog.ser"); + FileOutputStream fos = new FileOutputStream(file); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(dialog); + oos.flush(); + file.delete(); + + EventQueue.invokeAndWait(ShownModalDialogSerializationTest::deleteTestUI); + } + + static void deleteTestUI() { + if (dialog != null) { + dialog.setVisible(false); + dialog.dispose(); + } + if (frame != null) { + frame.setVisible(false); + frame.dispose(); + } + if (outputFrame != null) { + outputFrame.setVisible(false); + outputFrame.dispose(); + } + } + + private static void createTestUI() { + outputFrame = new Frame("ShownModalDialogSerializationTest"); + TextArea output = new TextArea(40, 50); + outputFrame.add(output); + + frame = new Frame("invisible dialog owner"); + dialog = new Dialog(frame, "Dialog for Close", true); + dialog.add(new Label("Close This Dialog")); + outputFrame.setSize(200, 200); + outputFrame.setVisible(true); + dialog.pack(); + dialog.setVisible(true); + } +} diff --git a/test/jdk/java/awt/Dialog/TaskbarIconTest.java b/test/jdk/java/awt/Dialog/TaskbarIconTest.java new file mode 100644 index 000000000000..2ced3853a0c0 --- /dev/null +++ b/test/jdk/java/awt/Dialog/TaskbarIconTest.java @@ -0,0 +1,145 @@ +/* + * 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. + */ + +import java.awt.Button; +import java.awt.Dialog; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.event.WindowListener; +import java.awt.print.PageFormat; +import java.awt.print.PrinterJob; + +/* + * @test + * @bug 6488834 + * @requires (os.family == "windows") + * @summary Tests that native dialogs (file, page, print) appear or + don't appear on the windows taskbar depending of their parent + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TaskbarIconTest +*/ + +public class TaskbarIconTest { + private static WindowListener wl = new WindowAdapter() { + public void windowClosing(WindowEvent we) { + Window w = we.getWindow(); + w.dispose(); + Window owner = w.getOwner(); + if (owner != null) { + owner.dispose(); + } + } + }; + + private static ActionListener al = new ActionListener() { + public void actionPerformed(ActionEvent ae) { + Button b = (Button) ae.getSource(); + + String bLabel = b.getLabel(); + boolean hasParent = (bLabel.indexOf("parentless") < 0); + Frame parent = hasParent ? new Frame("Parent") : null; + + if (bLabel.startsWith("Java")) { + Dialog d = new Dialog(parent, "Java dialog", true); + d.setBounds(0, 0, 160, 120); + d.addWindowListener(wl); + d.setVisible(true); + } else if (bLabel.startsWith("File")) { + FileDialog d = new FileDialog(parent, "File dialog"); + d.setVisible(true); + } else if (bLabel.startsWith("Print")) { + PrinterJob pj = PrinterJob.getPrinterJob(); + pj.printDialog(); + } else if (bLabel.startsWith("Page")) { + PrinterJob pj = PrinterJob.getPrinterJob(); + pj.pageDialog(new PageFormat()); + } + } + }; + + private static final String INSTRUCTIONS = """ + When the test starts a frame 'Main' is shown. It contains + several buttons, pressing each of them shows a dialog. + Some of the dialogs have a parent window, others are + parentless, according to the corresponding button's test. + + Press each button one after another. Make sure that all + parentless dialogs have an icon in the windows taskbar + and all the dialogs with parents don't. Press PASS or + FAIL button depending on the result. + + Note: as all the dialogs shown are modal, you have to close + them before showing the next dialog or PASS or FAIL buttons." + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("WindowInputBlock") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(TaskbarIconTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Button b; + + Frame mainFrame = new Frame("Main"); + mainFrame.setBounds(120, 240, 160, 240); + mainFrame.setLayout(new GridLayout(6, 1)); + + b = new Button("Java dialog, with parent"); + b.addActionListener(al); + mainFrame.add(b); + + b = new Button("Java dialog, parentless"); + b.addActionListener(al); + mainFrame.add(b); + + b = new Button("File dialog, with parent"); + b.addActionListener(al); + mainFrame.add(b); + + b = new Button("File dialog, parentless"); + b.addActionListener(al); + mainFrame.add(b); + + b = new Button("Print dialog, parentless"); + b.addActionListener(al); + mainFrame.add(b); + + b = new Button("Page dialog, parentless"); + b.addActionListener(al); + mainFrame.add(b); + + return mainFrame; + } +} diff --git a/test/jdk/java/awt/Dialog/WindowInputBlock.java b/test/jdk/java/awt/Dialog/WindowInputBlock.java new file mode 100644 index 000000000000..c38e8653ecc8 --- /dev/null +++ b/test/jdk/java/awt/Dialog/WindowInputBlock.java @@ -0,0 +1,134 @@ +/* + * 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 java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +/* + * @test + * @bug 4124096 + * @summary Modal JDialog is not modal on Solaris + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual WindowInputBlock + */ + +public class WindowInputBlock { + private static final String INSTRUCTIONS = """ + When the Window is up, you see a "Show Modal Dialog" button, a + "Test" button and a TextField. + Verify that the "Test" button is clickable, and the TextField can + receive focus. + + Now, click on "Show Modal Dialog" button to bring up a modal dialog + and verify that both "Test" button and TextField are not accessible. + Close the new dialog window. If the test behaved as described, pass + this test. Otherwise, fail this test. + + """; + + public static void main(String[] argv) throws Exception { + JFrame frame = new ModalDialogTest(); + PassFailJFrame.builder() + .title("WindowInputBlock") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(frame) + .build() + .awaitAndCheck(); + } +} + +class ModalDialogTest extends JFrame implements ActionListener { + JDialog dialog = new JDialog(new JFrame(), "Modal Dialog", true); + + public ModalDialogTest() { + setTitle("Modal Dialog Test"); + JPanel controlPanel = new JPanel(); + JPanel infoPanel = new JPanel(); + JButton showButton = new JButton("Show Modal Dialog"); + JButton testButton = new JButton("Test"); + JTextField textField = new JTextField("Test"); + + getContentPane().setLayout(new BorderLayout()); + infoPanel.setLayout(new GridLayout(0, 1)); + + showButton.setOpaque(true); + showButton.setBackground(Color.yellow); + + testButton.setOpaque(true); + testButton.setBackground(Color.pink); + + controlPanel.add(showButton); + controlPanel.add(testButton); + controlPanel.add(textField); + + infoPanel.add(new JLabel("Click the \"Show Modal Dialog\" button " + + "to display a modal JDialog.")); + infoPanel.add(new JLabel("Click the \"Test\" button to verify " + + "dialog modality.")); + + getContentPane().add(BorderLayout.NORTH, controlPanel); + getContentPane().add(BorderLayout.SOUTH, infoPanel); + dialog.setSize(200, 200); + + showButton.addActionListener(this); + testButton.addActionListener(this); + + addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + System.exit(0); + } + + public void windowClosed(WindowEvent e) { + System.exit(0); + } + }); + + pack(); + setSize(450, 120); + } + + public void actionPerformed(ActionEvent evt) { + String command = evt.getActionCommand(); + + if (command == "Show Modal Dialog") { + System.out.println("*** Invoking JDialog.show() ***"); + dialog.setLocation(200, 200); + dialog.setVisible(true); + } else if (command == "Test") { + System.out.println("*** Test ***"); + } + } +} diff --git a/test/jdk/java/awt/Focus/ClearLwQueueBreakTest/ClearLwQueueBreakTest.java b/test/jdk/java/awt/Focus/ClearLwQueueBreakTest/ClearLwQueueBreakTest.java index 5d1012bd22b3..13b8a1de5111 100644 --- a/test/jdk/java/awt/Focus/ClearLwQueueBreakTest/ClearLwQueueBreakTest.java +++ b/test/jdk/java/awt/Focus/ClearLwQueueBreakTest/ClearLwQueueBreakTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, 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 @@ -44,7 +44,7 @@ public class ClearLwQueueBreakTest { JTextField tf1 = new JTextField(" "); JTextField tf2 = new JTextField(" "); JTextField tf3 = new JTextField(" "); - AtomicBoolean typed = new AtomicBoolean(false); + final AtomicBoolean typed = new AtomicBoolean(false); FocusListener listener1; FocusListener listener2; @@ -114,6 +114,7 @@ public void focusGained(FocusEvent e) { f1.setLocationRelativeTo(null); f1.setVisible(true); Util.waitForIdle(robot); + robot.delay(1000); /* * Break the sequence of LW requests in the middle. diff --git a/test/jdk/java/awt/Focus/InitialFocusTest/InitialFocusTest1.java b/test/jdk/java/awt/Focus/InitialFocusTest/InitialFocusTest1.java index 9edbcf8f71c1..602a376655c6 100644 --- a/test/jdk/java/awt/Focus/InitialFocusTest/InitialFocusTest1.java +++ b/test/jdk/java/awt/Focus/InitialFocusTest/InitialFocusTest1.java @@ -22,8 +22,10 @@ */ import java.awt.Button; +import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Frame; +import java.awt.Robot; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; @@ -39,27 +41,36 @@ public class InitialFocusTest1 extends Frame implements FocusListener { Button button1 = new Button("Button1"); Button button2 = new Button("Button2"); private static volatile Object focused; + private static InitialFocusTest1 app; public static void main(final String[] args) throws Exception { - InitialFocusTest1 app = new InitialFocusTest1(); try { - app.setSize(200, 200); - app.setLocationRelativeTo(null); - app.setLayout(new FlowLayout()); + Robot robot = new Robot(); + EventQueue.invokeAndWait(() -> { + app = new InitialFocusTest1(); + app.setLayout(new FlowLayout()); - app.button1.addFocusListener(app); - app.button2.addFocusListener(app); - app.add(app.button1); - app.add(app.button2); - app.setVisible(true); - app.button2.requestFocus(); + app.button1.addFocusListener(app); + app.button2.addFocusListener(app); + app.add(app.button1); + app.add(app.button2); + + app.setSize(200, 200); + app.setLocationRelativeTo(null); + app.setVisible(true); + }); + robot.waitForIdle(); + robot.delay(1000); + EventQueue.invokeAndWait(() -> { + app.button2.requestFocus(); + }); // wait for the very very last focus event - Thread.sleep(10000); + robot.delay(1000); if (app.button2 != focused) { throw new RuntimeException("Wrong focus owner: " + focused); } } finally { - app.dispose(); + EventQueue.invokeAndWait(() -> app.dispose()); } } diff --git a/test/jdk/java/awt/Focus/KeyStrokeTest.java b/test/jdk/java/awt/Focus/KeyStrokeTest.java index 7c462ce8f22d..668bc1216c89 100644 --- a/test/jdk/java/awt/Focus/KeyStrokeTest.java +++ b/test/jdk/java/awt/Focus/KeyStrokeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -29,9 +29,9 @@ * @run main KeyStrokeTest */ -import java.awt.BorderLayout; import java.awt.Button; import java.awt.Dialog; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Robot; import java.awt.TextField; @@ -39,25 +39,53 @@ import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; public class KeyStrokeTest { static boolean keyTyped; static Frame frame; + static Robot robot; + static final CountDownLatch latch = new CountDownLatch(1); public static void main(String[] args) throws Exception { + robot = new Robot(); try { - KeyStrokeTest test = new KeyStrokeTest(); - test.doTest(); - } finally { - if (frame != null) { - frame.dispose(); + EventQueue.invokeAndWait(() -> { + KeyStrokeTest test = new KeyStrokeTest(); + test.initTest(); + }); + robot.waitForIdle(); + robot.delay(1000); + robot.keyPress(KeyEvent.VK_TAB); + robot.keyRelease(KeyEvent.VK_TAB); + + robot.delay(1000); + robot.keyPress(KeyEvent.VK_SPACE); + robot.keyRelease(KeyEvent.VK_SPACE); + + robot.delay(1000); + robot.keyPress(KeyEvent.VK_A); + robot.keyRelease(KeyEvent.VK_A); + try { + latch.await(3, TimeUnit.SECONDS); + } catch (InterruptedException e) {} + if (!keyTyped) { + throw new + RuntimeException("First keystroke after JDialog is closed is lost"); } + System.out.println("Test passed"); + } finally { + EventQueue.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } - private static void doTest() throws Exception { - final Object monitor = new Object(); - frame = new Frame(); + private static void initTest() { + frame = new Frame("KeyStrokeTest"); TextField textField = new TextField() { public void transferFocus() { System.err.println("transferFocus()"); @@ -71,6 +99,7 @@ public void actionPerformed(ActionEvent e) { }); dialog.add(btn); dialog.setSize(200, 200); + dialog.setLocationRelativeTo(null); dialog.setVisible(true); } }; @@ -81,38 +110,12 @@ public void keyTyped(KeyEvent e) { if (e.getKeyChar() == 'a') { keyTyped = true; } - - synchronized (monitor) { - monitor.notifyAll(); - } + latch.countDown(); } }); frame.add(textField); frame.setSize(400, 400); + frame.setLocationRelativeTo(null); frame.setVisible(true); - - Robot robot = new Robot(); - robot.waitForIdle(); - robot.delay(1000); - robot.keyPress(KeyEvent.VK_TAB); - robot.keyRelease(KeyEvent.VK_TAB); - - robot.delay(1000); - robot.keyPress(KeyEvent.VK_SPACE); - robot.keyRelease(KeyEvent.VK_SPACE); - - robot.delay(1000); - synchronized (monitor) { - robot.keyPress(KeyEvent.VK_A); - robot.keyRelease(KeyEvent.VK_A); - monitor.wait(3000); - } - - if (!keyTyped) { - throw new RuntimeException("TEST FAILED"); - } - - System.out.println("Test passed"); } - } diff --git a/test/jdk/java/awt/Frame/DisposeTest.java b/test/jdk/java/awt/Frame/DisposeTest.java index 08c0def638e6..ea1b2428f5c0 100644 --- a/test/jdk/java/awt/Frame/DisposeTest.java +++ b/test/jdk/java/awt/Frame/DisposeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -44,6 +44,7 @@ public class DisposeTest { private static Frame backgroundFrame; private static Frame testedFrame; + private static final int PIXEL_OFFSET = 4; private static final Rectangle backgroundFrameBounds = new Rectangle(100, 100, 200, 200); @@ -74,8 +75,8 @@ 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++) { + for (int x = PIXEL_OFFSET; x < bi.getWidth() - PIXEL_OFFSET; x++) { + for (int y = PIXEL_OFFSET; y < bi.getHeight() - PIXEL_OFFSET; y++) { if (bi.getRGB(x, y) != redPix) { try { ImageIO.write(bi, "png", diff --git a/test/jdk/java/awt/Frame/FrameSetMinimumSizeTest.java b/test/jdk/java/awt/Frame/FrameSetMinimumSizeTest.java index 929a36e773e4..ff95fd514015 100644 --- a/test/jdk/java/awt/Frame/FrameSetMinimumSizeTest.java +++ b/test/jdk/java/awt/Frame/FrameSetMinimumSizeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2024, 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 @@ -24,6 +24,7 @@ import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Frame; +import java.awt.Robot; /* * @test @@ -35,57 +36,65 @@ public class FrameSetMinimumSizeTest { private static Frame f; - private static volatile boolean passed; - + private static Robot robot; public static void main(String[] args) throws Exception { - EventQueue.invokeAndWait(() -> { - try { - createAndShowUI(); - - f.setSize(200, 200); - passed = verifyFrameSize(new Dimension(300, 300)); - isFrameSizeOk(passed); + robot = new Robot(); + try { + EventQueue.invokeAndWait(FrameSetMinimumSizeTest::createAndShowUI); + robot.waitForIdle(); + robot.delay(500); - f.setSize(200, 400); - passed = verifyFrameSize(new Dimension(300, 400)); - isFrameSizeOk(passed); + test( + new Dimension(200, 200), + new Dimension(300, 300) + ); - f.setSize(400, 200); - passed = verifyFrameSize(new Dimension(400, 300)); - isFrameSizeOk(passed); + test( + new Dimension(200, 400), + new Dimension(300, 400) + ); - f.setMinimumSize(null); + test( + new Dimension(400, 200), + new Dimension(400, 300) + ); - f.setSize(200, 200); - passed = verifyFrameSize(new Dimension(200, 200)); - isFrameSizeOk(passed); - } finally { + EventQueue.invokeAndWait(() -> f.setMinimumSize(null)); + test( + new Dimension(200, 200), + new Dimension(200, 200) + ); + } finally { + EventQueue.invokeAndWait(() -> { if (f != null) { f.dispose(); } - } - }); + }); + } + } + + private static void test(Dimension size, Dimension expected) throws Exception { + robot.waitForIdle(); + robot.delay(250); + EventQueue.invokeAndWait(() -> f.setSize(size)); + robot.waitForIdle(); + EventQueue.invokeAndWait(() -> verifyFrameSize(expected)); } private static void createAndShowUI() { f = new Frame("Minimum Size Test"); f.setSize(300, 300); f.setMinimumSize(new Dimension(300, 300)); + f.setLocationRelativeTo(null); f.setVisible(true); } - private static boolean verifyFrameSize(Dimension expected) { - + private static void verifyFrameSize(Dimension expected) { if (f.getSize().width != expected.width || f.getSize().height != expected.height) { - return false; - } - return true; - } - - private static void isFrameSizeOk(boolean passed) { - if (!passed) { - throw new RuntimeException("Frame's setMinimumSize not honoured for the" + - " frame size: " + f.getSize()); + String message = + "Frame's setMinimumSize not honoured for the frame size: %s. Expected %s" + .formatted(f.getSize(), expected); + throw new RuntimeException(message); } } } diff --git a/test/jdk/java/awt/Frame/FrameVisualTest.java b/test/jdk/java/awt/Frame/FrameVisualTest.java index 767eb0a18965..39853822c446 100644 --- a/test/jdk/java/awt/Frame/FrameVisualTest.java +++ b/test/jdk/java/awt/Frame/FrameVisualTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -46,62 +46,71 @@ public class FrameVisualTest { private static GraphicsConfiguration[] gcs; private static volatile Frame[] frames; - private static volatile int index; - private static Frame f; private static Robot robot; + private static volatile int frameNum; private static volatile Point p; private static volatile Dimension d; private static final int TOLERANCE = 5; + private static final int MAX_FRAME_COUNT = 30; public static void main(String[] args) throws Exception { - gcs = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getConfigurations(); + gcs = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice().getConfigurations(); robot = new Robot(); robot.setAutoDelay(100); - try { - EventQueue.invokeAndWait(() -> { - createAndShowUI(); - }); - robot.delay(1000); - System.out.println("frames.length: "+frames.length); - for (index = 0; index < frames.length; index++) { + + // Limit the number of frames tested if needed + if (gcs.length > MAX_FRAME_COUNT) { + frames = new Frame[MAX_FRAME_COUNT]; + } else { + frames = new Frame[gcs.length]; + } + System.out.println(gcs.length + " gcs found. Testing " + + frames.length + " frame(s)."); + + for (frameNum = 0; frameNum < frames.length; frameNum++) { + try { + EventQueue.invokeAndWait(() -> { + frames[frameNum] = new Frame("Frame w/ gc " + + frameNum, gcs[frameNum]); + frames[frameNum].setSize(100, 100); + frames[frameNum].setUndecorated(true); + frames[frameNum].setBackground(Color.WHITE); + frames[frameNum].setVisible(true); + System.out.println("Frame " + frameNum + " created"); + }); + + robot.delay(1000); + EventQueue.invokeAndWait(() -> { - p = frames[index].getLocation(); - d = frames[index].getSize(); + p = frames[frameNum].getLocation(); + d = frames[frameNum].getSize(); }); + Rectangle rect = new Rectangle(p, d); BufferedImage img = robot.createScreenCapture(rect); if (chkImgBackgroundColor(img)) { try { - ImageIO.write(img, "png", new File("Frame_" + index + ".png")); + ImageIO.write(img, "png", + new File("Frame_" + + frameNum + ".png")); } catch (IOException ignored) {} - throw new RuntimeException("Frame visual test failed with non-white background color"); + throw new RuntimeException("Frame visual test " + + "failed with non-white background color"); } - } - } finally { - for (index = 0; index < frames.length; index++) { + } finally { EventQueue.invokeAndWait(() -> { - if (frames[index] != null) { - frames[index].dispose(); + if (frames[frameNum] != null) { + frames[frameNum].dispose(); + System.out.println("Frame " + frameNum + " disposed"); } }); } } } - private static void createAndShowUI() { - frames = new Frame[gcs.length]; - for (int i = 0; i < frames.length; i++) { - frames[i] = new Frame("Frame w/ gc " + i, gcs[i]); - frames[i].setSize(100, 100); - frames[i].setUndecorated(true); - frames[i].setBackground(Color.WHITE); - frames[i].setVisible(true); - } - } - private static boolean chkImgBackgroundColor(BufferedImage img) { - // scan for mid-line and if it is non-white color then return true. for (int x = 1; x < img.getWidth() - 1; ++x) { Color c = new Color(img.getRGB(x, img.getHeight() / 2)); diff --git a/test/jdk/java/awt/Frame/MultiScreenTest.java b/test/jdk/java/awt/Frame/MultiScreenTest.java index 845f601138b7..cbd781f94ddd 100644 --- a/test/jdk/java/awt/Frame/MultiScreenTest.java +++ b/test/jdk/java/awt/Frame/MultiScreenTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -43,6 +43,7 @@ import java.awt.RenderingHints; import java.awt.TextField; +import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -74,7 +75,7 @@ public static void main(String[] args) throws Exception { ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); gs = ge.getScreenDevices(); if (gs.length < 2) { - throw new SkippedException("You have only one monitor in your system - test passed"); + throw new SkippedException("You have only one monitor in your system"); } MultiScreenTest obj = new MultiScreenTest(); String INSTRUCTIONS = @@ -82,38 +83,42 @@ public static void main(String[] args) throws Exception { "You have " + gs.length + " monitors in your system.\n" + "Actively drag the DitherTest frames on the secondary screen and " + "if you see garbage appearing on your primary screen " + - "test failed otherwise it passed.";; + "test failed otherwise it passed."; PassFailJFrame.builder() - .title("MultiScreenTest Instruction") .instructions(INSTRUCTIONS) - .rows((int) INSTRUCTIONS.lines().count() + 2) .columns(40) .testUI(obj::init) + .positionTestUI(MultiScreenTest::positionTestWindows) .build() .awaitAndCheck(); } + private static void positionTestWindows(List windows, PassFailJFrame.InstructionUI instructionUI) { + // Do nothing - the location of each window is set when they're created + } + public List init() { List list = new ArrayList<>(); for (int j = 0; j < gs.length; j++) { GraphicsConfiguration[] gc = gs[j].getConfigurations(); if (gc.length > 0) { - for (int i = 0; i < gc.length / 2; i++) { - JFrame f = new JFrame(gc[i]); //test JFrame( gc ) - GCCanvas c = new GCCanvas(gc[i]);//test canvas( gc ) - Rectangle gcBounds = gc[i].getBounds(); //test getBounds() + for (int i = 0; i < gc.length && i < 10; i++) { + JFrame f = new JFrame(gc[i]); + 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# " + Integer.toString(j) + ", GC#" + Integer.toString(i)); + f.setTitle("Screen# " + j + ", GC#" + i); f.setSize(300, 200); - f.setLocation(400 + xoffs, (i * 150) + yoffs);//test displaying in right location + // test displaying in right location + f.setLocation(400 + xoffs, (i * 150) + yoffs); list.add(f); - Frame ditherfs = new Frame("DitherTest GC#" + Integer.toString(i), gc[i]); - ditherfs.setLayout(new BorderLayout()); //showDitherTest + Frame ditherfs = new Frame("DitherTest GC#" + i, gc[i]); + ditherfs.setLayout(new BorderLayout()); DitherTest ditherTest = new DitherTest(gc[i]); ditherfs.add("Center", ditherTest); ditherfs.setBounds(300, 200, 300, 200); @@ -126,360 +131,368 @@ public List init() { } return list; } -} - -class GCCanvas extends Canvas { - - GraphicsConfiguration gc; - Rectangle bounds; - Graphics g = this.getGraphics(); - Dimension size = getSize(); - - public GCCanvas(GraphicsConfiguration gc) { - super(gc); - this.gc = gc; - bounds = gc.getBounds(); - } - - public void paint( Graphics _g ) { - Graphics2D g = (Graphics2D) _g; - g.drawRect(0, 0, size.width-1, size.height-1); - g.setColor(Color.lightGray); - g.draw3DRect(1, 1, size.width-3, size.height-3, true); + static class GCCanvas extends Canvas { - g.setColor(Color.red); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + GraphicsConfiguration gc; + Rectangle bounds; + Dimension size = getSize(); - g.drawString("HELLO!", 110, 10); + public GCCanvas(GraphicsConfiguration gc) { + super(gc); + this.gc = gc; + bounds = gc.getBounds(); + } - g.setColor(Color.blue); - g.drawString("ScreenSize="+Integer.toString(bounds.width)+"X"+ - Integer.toString(bounds.height), 10, 20); - g.setColor(Color.green); - g.drawString(gc.toString(), 10, 30); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); + @Override + public void paint( Graphics _g ) { - g.setColor(Color.orange); - g.fillRect(40, 20, 50, 50); + Graphics2D g = (Graphics2D) _g; - g.setColor(Color.red); - g.drawRect(100, 20, 30, 30); + g.drawRect(0, 0, size.width-1, size.height-1); + g.setColor(Color.lightGray); + g.draw3DRect(1, 1, size.width-3, size.height-3, true); - g.setColor(Color.gray); - g.drawLine(220, 20, 280, 40); + g.setColor(Color.red); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setColor(Color.cyan); - g.fillArc(150, 30, 30, 30, 0, 200); - } + g.drawString("HELLO!", 110, 10); - public Dimension getPreferredSize(){ - return new Dimension(300, 200); - } -} + g.setColor(Color.blue); + g.drawString("ScreenSize="+Integer.toString(bounds.width)+"X"+ + Integer.toString(bounds.height), 10, 20); + g.setColor(Color.green); + g.drawString(gc.toString(), 10, 30); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); -class DitherCanvas extends Canvas { - Image img; - static String calcString = "Calculating..."; + g.setColor(Color.orange); + g.fillRect(40, 20, 50, 50); - GraphicsConfiguration mGC; + g.setColor(Color.red); + g.drawRect(100, 20, 30, 30); - public DitherCanvas(GraphicsConfiguration gc) { - super(gc); - mGC = gc; - } + g.setColor(Color.gray); + g.drawLine(220, 20, 280, 40); - public GraphicsConfiguration getGraphicsConfig() { - return mGC; - } + g.setColor(Color.cyan); + g.fillArc(150, 30, 30, 30, 0, 200); + } - public void paint(Graphics g) { - int w = getSize().width; - int h = getSize().height; - if (img == null) { - super.paint(g); - g.setColor(Color.black); - FontMetrics fm = g.getFontMetrics(); - int x = (w - fm.stringWidth(calcString)) / 2; - int y = h / 2; - g.drawString(calcString, x, y); - } else { - g.drawImage(img, 0, 0, w, h, this); + @Override + public Dimension getPreferredSize(){ + return new Dimension(300, 200); } } - public void update(Graphics g) { - paint(g); - } + static class DitherCanvas extends Canvas { + Image img; + static String calcString = "Calculating..."; - public Dimension getMinimumSize() { - return new Dimension(20, 20); - } + GraphicsConfiguration mGC; - public Dimension getPreferredSize() { - return new Dimension(200, 200); - } + public DitherCanvas(GraphicsConfiguration gc) { + super(gc); + mGC = gc; + } - public Image getImage() { - return img; - } + public GraphicsConfiguration getGraphicsConfig() { + return mGC; + } - public void setImage(Image img) { - this.img = img; - paint(getGraphics()); - } -} + @Override + public void paint(Graphics g) { + int w = getSize().width; + int h = getSize().height; + if (img == null) { + super.paint(g); + g.setColor(Color.black); + FontMetrics fm = g.getFontMetrics(); + int x = (w - fm.stringWidth(calcString)) / 2; + int y = h / 2; + g.drawString(calcString, x, y); + } else { + g.drawImage(img, 0, 0, w, h, this); + } + } -class DitherTest extends Panel implements Runnable { - 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; - - Thread runner; - - DitherControls XControls; - DitherControls YControls; - DitherCanvas canvas; - - public DitherTest(GraphicsConfiguration gc) { - String xspec, yspec; - int xvals[] = new int[2]; - int yvals[] = new int[2]; - - xspec = "red"; - yspec = "blue"; - int xmethod = colormethod(xspec, xvals); - int ymethod = colormethod(yspec, yvals); - - setLayout(new BorderLayout()); - XControls = new DitherControls(this, xvals[0], xvals[1], - xmethod, false); - YControls = new DitherControls(this, yvals[0], yvals[1], - ymethod, true); - YControls.addRenderButton(); - add("North", XControls); - add("South", YControls); - add("Center", canvas = new DitherCanvas(gc)); - } + @Override + public void update(Graphics g) { + paint(g); + } - public void start() { - runner = new Thread(this); - runner.start(); - } + @Override + public Dimension getMinimumSize() { + return new Dimension(20, 20); + } - int colormethod(String s, int vals[]) { - int method = NOOP; + @Override + public Dimension getPreferredSize() { + return new Dimension(200, 200); + } - if (s == null) { - s = ""; + public Image getImage() { + return img; } - String lower = s.toLowerCase(); - int len = 0; - if (lower.startsWith("red")) { - method = RED; - lower = lower.substring(3); - } else if (lower.startsWith("green")) { - method = GREEN; - lower = lower.substring(5); - } else if (lower.startsWith("blue")) { - method = BLUE; - lower = lower.substring(4); - } else if (lower.startsWith("alpha")) { - method = ALPHA; - lower = lower.substring(4); - } else if (lower.startsWith("saturation")) { - method = SATURATION; - lower = lower.substring(10); + public void setImage(Image img) { + this.img = img; + paint(getGraphics()); } + } - if (method == NOOP) { - vals[0] = 0; - vals[1] = 0; - return method; + static class DitherTest extends Panel implements Runnable { + 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; + + Thread runner; + + DitherControls XControls; + DitherControls YControls; + DitherCanvas canvas; + + public DitherTest(GraphicsConfiguration gc) { + String xspec, yspec; + int xvals[] = new int[2]; + int yvals[] = new int[2]; + + xspec = "red"; + yspec = "blue"; + int xmethod = colormethod(xspec, xvals); + int ymethod = colormethod(yspec, yvals); + + setLayout(new BorderLayout()); + XControls = new DitherControls(this, xvals[0], xvals[1], + xmethod, false); + YControls = new DitherControls(this, yvals[0], yvals[1], + ymethod, true); + YControls.addRenderButton(); + add("North", XControls); + add("South", YControls); + add("Center", canvas = new DitherCanvas(gc)); } - int begval = 0; - int endval = 255; + public void start() { + runner = new Thread(this); + runner.start(); + } - try { - int dash = lower.indexOf('-'); - if (dash < 0) { - begval = endval = Integer.parseInt(lower); - } else { - begval = Integer.parseInt(lower.substring(0, dash)); - endval = Integer.parseInt(lower.substring(dash + 1)); + int colormethod(String s, int vals[]) { + int method = NOOP; + + if (s == null) { + s = ""; } - } catch (Exception e) { - } - if (begval < 0) { - begval = 0; - } - if (endval < 0) { - endval = 0; - } - if (begval > 255) { - begval = 255; - } - if (endval > 255) { - endval = 255; - } + String lower = s.toLowerCase(); + int len = 0; + if (lower.startsWith("red")) { + method = RED; + lower = lower.substring(3); + } else if (lower.startsWith("green")) { + method = GREEN; + lower = lower.substring(5); + } else if (lower.startsWith("blue")) { + method = BLUE; + lower = lower.substring(4); + } else if (lower.startsWith("alpha")) { + method = ALPHA; + lower = lower.substring(4); + } else if (lower.startsWith("saturation")) { + method = SATURATION; + lower = lower.substring(10); + } - vals[0] = begval; - vals[1] = endval; + if (method == NOOP) { + vals[0] = 0; + vals[1] = 0; + return method; + } - return method; - } + int begval = 0; + int endval = 255; - 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; + try { + int dash = lower.indexOf('-'); + if (dash < 0) { + begval = endval = Integer.parseInt(lower); + } else { + begval = Integer.parseInt(lower.substring(0, dash)); + endval = Integer.parseInt(lower.substring(dash + 1)); } - break; + } catch (Exception e) { + } + + if (begval < 0) { + begval = 0; + } + if (endval < 0) { + endval = 0; + } + if (begval > 255) { + begval = 255; + } + if (endval > 255) { + endval = 255; + } + + vals[0] = begval; + vals[1] = endval; + + return method; } - } - public void run() { - canvas.setImage(null); // Wipe previous image - Image img = calculateImage(); - synchronized (this) { - if (img != null && runner == Thread.currentThread()) { - canvas.setImage(img); + 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; } } - } - /** - * Calculates and returns the image. Halts the calculation and returns - * null if stopped during the calculation. - */ - Image calculateImage() { - Thread me = Thread.currentThread(); - - int width = canvas.getSize().width; - int height = canvas.getSize().height; - int xvals[] = new int[2]; - int yvals[] = new int[2]; - int xmethod = XControls.getParams(xvals); - int ymethod = YControls.getParams(yvals); - 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); + @Override + public void run() { + canvas.setImage(null); // Wipe previous image + Image img = calculateImage(); + synchronized (this) { + if (img != null && runner == Thread.currentThread()) { + canvas.setImage(img); } - pixels[index++] = ((c[3] << 24) | - (c[0] << 16) | - (c[1] << 8) | - (c[2] << 0)); - - } - // Poll once per row to see if we've been told to stop. - if (runner != me) { - return null; } } - return createImage(new MemoryImageSource(width, height, - ColorModel.getRGBdefault(), pixels, 0, width)); - } + /** + * Calculates and returns the image. Halts the calculation and returns + * null if stopped during the calculation. + */ + Image calculateImage() { + Thread me = Thread.currentThread(); + + int width = canvas.getSize().width; + int height = canvas.getSize().height; + int xvals[] = new int[2]; + int yvals[] = new int[2]; + int xmethod = XControls.getParams(xvals); + int ymethod = YControls.getParams(yvals); + 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)); - public String getInfo() { - return "An interactive demonstration of dithering."; - } + } + // Poll once per row to see if we've been told to stop. + if (runner != me) { + return null; + } + } - public String[][] getParameterInfo() { - String[][] info = { - {"xaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", - "The color of the Y axis. Default is RED."}, - {"yaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", - "The color of the X axis. Default is BLUE."} - }; - return info; - } -} + return createImage(new MemoryImageSource(width, height, + ColorModel.getRGBdefault(), pixels, 0, width)); + } -class DitherControls extends Panel implements ActionListener { - TextField start; - TextField end; - Button button; - Choice choice; - DitherTest dt; - - static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, 10, 5); - - public DitherControls(DitherTest app, int s, int e, int type, - boolean vertical) { - dt = app; - setLayout(dcLayout); - add(new Label(vertical ? "Vertical" : "Horizontal")); - add(choice = new Choice()); - choice.addItem("Noop"); - choice.addItem("Red"); - choice.addItem("Green"); - choice.addItem("Blue"); - choice.addItem("Alpha"); - choice.addItem("Saturation"); - choice.select(type); - add(start = new TextField(Integer.toString(s), 4)); - add(end = new TextField(Integer.toString(e), 4)); - } + public String getInfo() { + return "An interactive demonstration of dithering."; + } - public void addRenderButton() { - add(button = new Button("New Image")); - button.addActionListener(this); + public String[][] getParameterInfo() { + String[][] info = { + {"xaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", + "The color of the Y axis. Default is RED."}, + {"yaxis", "{RED, GREEN, BLUE, PINK, ORANGE, MAGENTA, CYAN, WHITE, YELLOW, GRAY, DARKGRAY}", + "The color of the X axis. Default is BLUE."} + }; + return info; + } } - public int getParams(int vals[]) { - vals[0] = Integer.parseInt(start.getText()); - vals[1] = Integer.parseInt(end.getText()); - return choice.getSelectedIndex(); - } + static class DitherControls extends Panel implements ActionListener { + TextField start; + TextField end; + Button button; + Choice choice; + DitherTest dt; + + static LayoutManager dcLayout = new FlowLayout(FlowLayout.CENTER, 10, 5); + + public DitherControls(DitherTest app, int s, int e, int type, + boolean vertical) { + dt = app; + setLayout(dcLayout); + add(new Label(vertical ? "Vertical" : "Horizontal")); + add(choice = new Choice()); + choice.addItem("Noop"); + choice.addItem("Red"); + choice.addItem("Green"); + choice.addItem("Blue"); + choice.addItem("Alpha"); + choice.addItem("Saturation"); + choice.select(type); + add(start = new TextField(Integer.toString(s), 4)); + add(end = new TextField(Integer.toString(e), 4)); + } - public void actionPerformed(ActionEvent e) { - if (e.getSource() == button) { - dt.start(); + public void addRenderButton() { + add(button = new Button("New Image")); + button.addActionListener(this); + } + + public int getParams(int vals[]) { + vals[0] = Integer.parseInt(start.getText()); + vals[1] = Integer.parseInt(end.getText()); + return choice.getSelectedIndex(); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == button) { + dt.start(); + } } } } diff --git a/test/jdk/java/awt/FullScreen/DisplayModeNoRefreshTest.java b/test/jdk/java/awt/FullScreen/DisplayModeNoRefreshTest.java new file mode 100644 index 000000000000..a52990371221 --- /dev/null +++ b/test/jdk/java/awt/FullScreen/DisplayModeNoRefreshTest.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2004, 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 5041225 + * @key headful + * @summary Tests that we can set a display mode with unknown refresh rate + * if corresponding system display mode (with equal w/h/d) is available. + * @run main DisplayModeNoRefreshTest + */ + +import java.awt.Color; +import java.awt.DisplayMode; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; + +public class DisplayModeNoRefreshTest extends Frame { + + private static DisplayModeNoRefreshTest fs; + + private static final GraphicsDevice gd = + GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice(); + + private static final DisplayMode origMode = gd.getDisplayMode(); + + public DisplayModeNoRefreshTest() { + super("DisplayModeNoRefreshTest"); + if (!gd.isFullScreenSupported()) { + System.out.println("Full Screen is not supported, test considered passed."); + return; + } + setBackground(Color.green); + gd.setFullScreenWindow(this); + DisplayMode dlMode = getNoRefreshDisplayMode(gd.getDisplayModes()); + if (dlMode != null) { + System.out.println("Selected Display Mode: " + + " Width " + dlMode.getWidth() + + " Height " + dlMode.getHeight() + + " BitDepth " + dlMode.getBitDepth() + + " Refresh Rate " + dlMode.getRefreshRate()); + try { + gd.setDisplayMode(dlMode); + } catch (IllegalArgumentException ex) { + throw new RuntimeException("Test Failed due to IAE", ex); + } + } else { + System.out.println("No suitable display mode available, test considered passed."); + return; + } + + try { Thread.sleep(2000); } catch (InterruptedException e) {} + + System.out.println("Test Passed."); + } + + public DisplayMode getNoRefreshDisplayMode(DisplayMode dm[]) { + DisplayMode mode = new DisplayMode(640, 480, 32, DisplayMode.REFRESH_RATE_UNKNOWN); + int i = 0; + for (i = 0; i < dm.length; i++) { + if (mode.getWidth() == dm[i].getWidth() + && mode.getHeight() == dm[i].getHeight() + && mode.getBitDepth() == dm[i].getBitDepth()) { + return mode; + } + } + if (dm.length > 0) { + return + new DisplayMode(dm[0].getWidth(), dm[0].getHeight(), + dm[0].getBitDepth(), + DisplayMode.REFRESH_RATE_UNKNOWN); + } + + return null; + } + + public static void main(String[] args) throws Exception { + try { + EventQueue.invokeAndWait(() -> { + System.setProperty("sun.java2d.noddraw", "true"); + fs = new DisplayModeNoRefreshTest(); + }); + } finally { + gd.setDisplayMode(origMode); + EventQueue.invokeAndWait(() -> { + if (fs != null) { + fs.dispose(); + } + }); + } + } +} diff --git a/test/jdk/java/awt/Graphics2D/CopyAreaOOB.java b/test/jdk/java/awt/Graphics2D/CopyAreaOOB.java index 8d218d9f1891..27a1a3a868a9 100644 --- a/test/jdk/java/awt/Graphics2D/CopyAreaOOB.java +++ b/test/jdk/java/awt/Graphics2D/CopyAreaOOB.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -26,17 +26,75 @@ * @key headful * @bug 6430601 8198613 * @summary Verifies that copyArea() works properly when the - * destination parameters are outside the destination bounds. + * destination parameters are outside the destination bounds. * @run main/othervm CopyAreaOOB - * @author campbelc */ -import java.awt.*; -import java.awt.image.*; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.awt.image.MultiResolutionImage; +import java.awt.image.RenderedImage; +import java.io.File; +import java.io.IOException; +import java.util.List; + +import javax.imageio.ImageIO; public class CopyAreaOOB extends Canvas { + private static Frame frame; + private static Robot robot; + private static BufferedImage captureImg; - private static Robot robot = null; + private static StringBuffer errorLog = new StringBuffer(); + + private static final Point OFF_FRAME_LOC = new Point(50, 50); + private static final int SIZE = 400; + + public static void main(String[] args) throws Exception { + try { + robot = new Robot(); + + // added to move mouse pointer away from test UI + // so that it is not captured in the screenshot + robot.mouseMove(OFF_FRAME_LOC.x, OFF_FRAME_LOC.y); + robot.waitForIdle(); + robot.delay(100); + + createTestUI(); + robot.delay(1000); + + if (!errorLog.isEmpty()) { + saveImages(); + throw new RuntimeException("Test failed: \n" + errorLog.toString()); + } + } finally { + if (frame != null) { + frame.dispose(); + } + } + } + + private static void createTestUI() { + CopyAreaOOB canvas = new CopyAreaOOB(); + frame = new Frame(); + frame.setUndecorated(true); + frame.add(canvas); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } public void paint(Graphics g) { int w = getWidth(); @@ -50,73 +108,69 @@ public void paint(Graphics g) { g2d.fillRect(0, 0, w, 10); g2d.setColor(Color.red); - g2d.fillRect(0, 10, 50, h-10); + g2d.fillRect(0, 10, 50, h - 10); // copy the region such that part of it goes below the bottom of the // destination surface - g2d.copyArea(0, 10, 50, h-10, 60, 10); + g2d.copyArea(0, 10, 50, h - 10, 60, 10); Toolkit.getDefaultToolkit().sync(); - BufferedImage capture = null; - try { - Thread.sleep(500); - if (robot == null) robot = new Robot(); - Point pt1 = getLocationOnScreen(); - Rectangle rect = new Rectangle(pt1.x, pt1.y, 400, 400); - capture = robot.createScreenCapture(rect); - } catch (Exception e) { - throw new RuntimeException("Problems handling Robot"); - } + robot.delay(500); + + Point pt1 = this.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, SIZE, SIZE); + captureImg = robot.createScreenCapture(rect); + // Test pixels - testRegion(capture, "green", 0, 0, 400, 10, 0xff00ff00); - testRegion(capture, "original red", 0, 10, 50, 400, 0xffff0000); - testRegion(capture, "background", 50, 10, 60, 400, 0xff000000); - testRegion(capture, "in-between", 60, 10, 110, 20, 0xff000000); - testRegion(capture, "copied red", 60, 20, 110, 400, 0xffff0000); - testRegion(capture, "background", 110, 10, 400, 400, 0xff000000); + testRegion("green", 0, 0, 400, 10, 0xff00ff00); + testRegion("original-red", 0, 10, 50, 400, 0xffff0000); + testRegion("background", 50, 10, 60, 400, 0xff000000); + testRegion("in-between", 60, 10, 110, 20, 0xff000000); + testRegion("copied-red", 60, 20, 110, 400, 0xffff0000); + testRegion("background", 110, 10, 400, 400, 0xff000000); } public Dimension getPreferredSize() { - return new Dimension(400, 400); + return new Dimension(SIZE, SIZE); } - private static void testRegion(BufferedImage bi, String name, + private static void testRegion(String region, int x1, int y1, int x2, int y2, - int expected) - { + int expected) { + System.out.print("Test region: " + region); for (int y = y1; y < y2; y++) { for (int x = x1; x < x2; x++) { - int actual = bi.getRGB(x, y); + int actual = captureImg.getRGB(x, y); if (actual != expected) { - throw new RuntimeException("Test failed for " + name + - " region at x="+x+" y="+y+ - " (expected="+ - Integer.toHexString(expected) + - " actual="+ - Integer.toHexString(actual) + - ")"); + System.out.print(" Status: FAILED\n"); + errorLog.append("Test failed for " + region + + " region at x: " + x + " y: " + y + + " (expected: " + + Integer.toHexString(expected) + + " actual: " + + Integer.toHexString(actual) + ")\n"); + return; } } } + System.out.print(" Status: PASSED\n"); } - public static void main(String[] args) { - boolean show = (args.length == 1) && ("-show".equals(args[0])); + private static void saveImages() { + GraphicsConfiguration ge = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .getDefaultConfiguration(); - CopyAreaOOB test = new CopyAreaOOB(); - Frame frame = new Frame(); - frame.setUndecorated(true); - frame.add(test); - frame.pack(); - frame.setLocationRelativeTo(null); - frame.setVisible(true); + MultiResolutionImage mrImage = robot.createMultiResolutionScreenCapture(ge.getBounds()); + List variants = mrImage.getResolutionVariants(); + RenderedImage screenCapture = (RenderedImage) variants.get(variants.size() - 1); try { - Thread.sleep(3000); - } catch (InterruptedException ex) {} - if (!show) { - frame.dispose(); + ImageIO.write(screenCapture, "png", new File("fullscreen.png")); + ImageIO.write(captureImg, "png", new File("canvas.png")); + } catch (IOException e) { + System.err.println("Can't write image " + e); } } } diff --git a/test/jdk/java/awt/GraphicsDevice/CheckDisplayModes.java b/test/jdk/java/awt/GraphicsDevice/CheckDisplayModes.java index 3d909e2185e8..2a5feef89fea 100644 --- a/test/jdk/java/awt/GraphicsDevice/CheckDisplayModes.java +++ b/test/jdk/java/awt/GraphicsDevice/CheckDisplayModes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, 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 @@ -35,18 +35,30 @@ public class CheckDisplayModes { public static void main(String[] args) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); - for (GraphicsDevice graphicDevice : ge.getScreenDevices()) { + GraphicsDevice[] allDevices = ge.getScreenDevices(); + + for (GraphicsDevice gd : allDevices) { + System.out.println("Available screen device: " + gd.getIDstring()); + } + + for (GraphicsDevice graphicDevice : allDevices) { + System.out.println("On screen device " + graphicDevice.getIDstring()); if (!graphicDevice.isDisplayChangeSupported()) { System.err.println("Display mode change is not supported on this host. Test is considered passed."); continue; } DisplayMode defaultDisplayMode = graphicDevice.getDisplayMode(); + System.out.println("Default display mode: " + defaultDisplayMode); checkDisplayMode(defaultDisplayMode); graphicDevice.setDisplayMode(defaultDisplayMode); DisplayMode[] displayModes = graphicDevice.getDisplayModes(); + for (int i = 0; i < displayModes.length; i++) { + System.out.println("displayModes[" + i + "] = " + displayModes[i]); + } boolean isDefaultDisplayModeIncluded = false; for (DisplayMode displayMode : displayModes) { + System.out.println("Attempting display mode " + displayMode); checkDisplayMode(displayMode); graphicDevice.setDisplayMode(displayMode); if (defaultDisplayMode.equals(displayMode)) { diff --git a/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java b/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java index 5b2dc2844f17..60c05fb05a67 100644 --- a/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java +++ b/test/jdk/java/awt/KeyboardFocusmanager/ConsumeNextMnemonicKeyTypedTest/ConsumeNextMnemonicKeyTypedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -24,7 +24,7 @@ /* @test @key headful - @bug 6346690 + @bug 6346690 8361606 8321303 @summary Tests that key_typed is consumed after mnemonic key_pressed is handled for a menu item. @library /test/lib @build jdk.test.lib.Platform diff --git a/test/jdk/java/awt/KeyboardFocusmanager/TypeAhead/ButtonActionKeyTest/ButtonActionKeyTest.java b/test/jdk/java/awt/KeyboardFocusmanager/TypeAhead/ButtonActionKeyTest/ButtonActionKeyTest.java index 7f9a07878f1b..52b7eeccd12d 100644 --- a/test/jdk/java/awt/KeyboardFocusmanager/TypeAhead/ButtonActionKeyTest/ButtonActionKeyTest.java +++ b/test/jdk/java/awt/KeyboardFocusmanager/TypeAhead/ButtonActionKeyTest/ButtonActionKeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -31,9 +31,16 @@ @run main ButtonActionKeyTest */ -import java.awt.*; -import java.awt.event.*; -import javax.swing.*; +import java.awt.FlowLayout; +import java.awt.Robot; +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import java.awt.event.ActionEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; import java.util.concurrent.atomic.AtomicBoolean; import test.java.awt.regtesthelpers.Util; @@ -42,7 +49,7 @@ public class ButtonActionKeyTest { JFrame frame = new JFrame("Frame"); JButton button = new JButton("button"); JTextField text = new JTextField("text"); - AtomicBoolean gotEvent = new AtomicBoolean(false); + final AtomicBoolean gotEvent = new AtomicBoolean(false); public static void main(String[] args) { ButtonActionKeyTest app = new ButtonActionKeyTest(); @@ -82,9 +89,11 @@ public void keyTyped(KeyEvent e) { frame.setLocationRelativeTo(null); frame.setVisible(true); Util.waitForIdle(robot); + robot.delay(1000); Util.clickOnComp(button, robot); Util.waitForIdle(robot); + robot.delay(500); if (!button.isFocusOwner()) { throw new Error("Test error: a button didn't gain focus."); diff --git a/test/jdk/java/awt/LightweightComponent/LightWeightTabFocus/LightWeightTabFocus.java b/test/jdk/java/awt/LightweightComponent/LightWeightTabFocus/LightWeightTabFocus.java index 05889580fd42..2d0b742c3196 100644 --- a/test/jdk/java/awt/LightweightComponent/LightWeightTabFocus/LightWeightTabFocus.java +++ b/test/jdk/java/awt/LightweightComponent/LightWeightTabFocus/LightWeightTabFocus.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -97,6 +97,7 @@ public static void main(String[] args) throws Exception { } catch (Exception e) { e.printStackTrace(); } finally { + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); EventQueue.invokeAndWait(() -> { if (f != null) { f.dispose(); diff --git a/test/jdk/java/awt/MenuBar/8007006/bug8007006.java b/test/jdk/java/awt/MenuBar/8007006/bug8007006.java index cebf9cd8da9b..0bc9bdeefffe 100644 --- a/test/jdk/java/awt/MenuBar/8007006/bug8007006.java +++ b/test/jdk/java/awt/MenuBar/8007006/bug8007006.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, 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 @@ -21,76 +21,86 @@ * questions. */ -/** +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsEnvironment; +import java.awt.Insets; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.InputEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/* * @test * @key headful * @bug 8007006 * @requires (os.family == "mac") * @summary [macosx] Closing subwindow loses main window menus. - * @library /test/lib - * @build jdk.test.lib.Platform - * @run main bug8007006 */ -import java.awt.*; -import java.awt.event.*; - -import jdk.test.lib.Platform; - public class bug8007006 { - private static Frame frame1; - private static Frame frame2; - private static volatile boolean isActionPerformed; + private static Frame mainFrame; + private static Frame subFrame; + private static final CountDownLatch isActionPerformed = new CountDownLatch(1); public static void main(String[] args) throws Exception { - if (!Platform.isOSX()) { - System.out.println("This test is for MacOS only. Automatically passed on other platforms."); - return; - } - - System.setProperty("apple.laf.useScreenMenuBar", "true"); + try { + System.setProperty("apple.laf.useScreenMenuBar", "true"); + Robot robot = new Robot(); - Robot robot = new Robot(); - robot.setAutoDelay(300); + EventQueue.invokeAndWait(bug8007006::createAndShowGUI); + robot.waitForIdle(); + robot.delay(1000); - createAndShowGUI(); - robot.waitForIdle(); - frame2.dispose(); - robot.waitForIdle(); + EventQueue.invokeAndWait(() -> subFrame.dispose()); + robot.waitForIdle(); + robot.delay(300); - performMenuItemTest(robot); + performMenuItemTest(robot); - frame1.dispose(); - if (!isActionPerformed) { - throw new Exception("Test failed: menu item action was not performed"); + if (!isActionPerformed.await(1, TimeUnit.SECONDS)) { + throw new Exception("Test failed: menu item action was not performed"); + } + } finally { + EventQueue.invokeAndWait(() -> { + if (mainFrame != null) { + mainFrame.dispose(); + } + }); } } private static void createAndShowGUI() { - frame1 = new Frame("Frame 1"); - frame1.setMenuBar(createMenuBar()); - frame1.setSize(200, 200); - - frame2 = new Frame("Frame 2"); - frame2.setMenuBar(createMenuBar()); - frame2.setSize(200, 200); - - frame1.setVisible(true); - frame2.setVisible(true); + mainFrame = new Frame("Frame 1"); + mainFrame.setMenuBar(createMenuBar()); + mainFrame.setSize(200, 200); + mainFrame.setBackground(Color.GREEN); + mainFrame.setLocationRelativeTo(null); + + subFrame = new Frame("Frame 2"); + subFrame.setMenuBar(createMenuBar()); + subFrame.setSize(200, 200); + subFrame.setBackground(Color.RED); + subFrame.setLocationRelativeTo(null); + + mainFrame.setVisible(true); + subFrame.setVisible(true); } private static MenuBar createMenuBar() { - // A very long name makes it more likely that the robot will hit the - // menu + // A very long name makes it more likely + // that the robot will hit the menu Menu menu = new Menu("TestTestTestTestTestTestTestTestTestTest"); MenuItem item = new MenuItem("TestTestTestTestTestTestTestTestTestTest"); - item.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent ev) { - isActionPerformed = true; - } - }); menu.add(item); + item.addActionListener(ev -> isActionPerformed.countDown()); + MenuBar mb = new MenuBar(); mb.add(menu); return mb; @@ -102,29 +112,29 @@ private static void performMenuItemTest(Robot robot) { // of the first menu. // Unfortunately, the application name can vary based on how the // application is run. - // The work around is to make the menu and the menu item names very + // The workaround is to make the menu and the menu item names very // long. + Toolkit toolkit = Toolkit.getDefaultToolkit(); + GraphicsConfiguration gc = + GraphicsEnvironment.getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .getDefaultConfiguration(); + + Insets screenInsets = toolkit.getScreenInsets(gc); + System.out.println("Screen insets: " + screenInsets); + int menuBarX = 250; - int menuBarY = 11; + int menuBarY = screenInsets.top / 2; int menuItemX = menuBarX; - int menuItemY = 34; + int menuItemY = screenInsets.top + 10; robot.mouseMove(menuBarX, menuBarY); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - robot.mouseMove(menuItemX, menuItemY); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.waitForIdle(); - waitForAction(); - } - private static void waitForAction() { - try { - for (int i = 0; i < 10; i++) { - if (isActionPerformed) { - return; - } - Thread.sleep(100); - } - } catch (InterruptedException ex) { - } + robot.mouseMove(menuItemX, menuItemY); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); } } diff --git a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.html b/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.html deleted file mode 100644 index a562b886ab0e..000000000000 --- a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.html +++ /dev/null @@ -1,44 +0,0 @@ - - - - - PrintDialogsTest - - - - -Please select dialog modality type and parent; also select -the print auxiliary dialog to be displayed (Page Setup or Print dialog). -Then click "Start test" button. - -When the windows will appear check if modal blocking for Dialog works as expected. -Then push "Open" button on the Dialog to show the auxiliary dialog and check -if it blocks the rest of the application. Then close it and check correctness -of modal blocking behavior for the Dialog again. To close all the test -windows please push "Finish" button. - -To finish the overall test push "Pass" or "Fail" button depending on result. - - - diff --git a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java b/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java index 989c48295b01..3e191fa0c4c0 100644 --- a/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java +++ b/test/jdk/java/awt/Modal/PrintDialogsTest/PrintDialogsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2014, 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 @@ -25,21 +25,71 @@ /* * @test * @bug 8055836 8057694 8055752 - * @summary Check if Print and Page Setup dialogs lock other windows; + * @summary Check if Print and Page Setup dialogs block other windows; * check also correctness of modal behavior for other dialogs. - * - * @run applet/manual=yesno PrintDialogsTest.html + * @library /java/awt/regtesthelpers + * @run main/manual PrintDialogsTest */ -import java.applet.Applet; -import java.awt.*; +import java.awt.BorderLayout; +import java.awt.Button; +import java.awt.Checkbox; +import java.awt.CheckboxGroup; +import java.awt.Dialog; +import java.awt.Frame; +import java.awt.EventQueue; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -public class PrintDialogsTest extends Applet implements ActionListener { +public class PrintDialogsTest extends Panel implements ActionListener { + + static final String INSTRUCTIONS = + "1. On the Test UI Select:\n" + + "\tThe dialog parent type. (e.g. Frame, Dialog, Hidden, Null)\n" + + "\tThe dialog modality type. (e.g. Modal, Non-Modal, Toolkit modal).\n" + + "\tThe print dialog type. (Print dialog or Page Setup dialog).\n\n" + + "2. Next, click on 'Start test' - Three windows will appear:\n" + + "\tWindow (1) -a Frame or Dialog (depending on selected parent type).\n" + + "\tWindow (2) -an undecorated top-level Window.\n" + + "\tWindow (3) -a Dialog containing two buttons: 'Open' and 'Finish'.\n" + + "\tWindows (1) & (2) have a Dummy button.\n\n" + + "3. Press the button on Window (1) & Window (2) \n" + + "Verification step:\n" + + "\tIf Modality is 'Non-modal' or 'Modeless', Button is pressed \n" + + "\tIf Modality is 'Document' & parent is not Frame/Dialog, Button is pressed \n" + + "\tIn all other cases, button is not pressed & Window (3) should \n" + + "\tblock input to Windows (1) & (2).\n\n" + + "4. Next, press the 'Open' button in Window (3) to open print dialog.\n\n" + + "5. Press the button on Window (1) & Window (2)\n" + + "Verification step:\n" + + "\tThe print dialog should block all three windows (1, 2, and 3).\n\n" + + "6. Cancel the print dialog, Check again if Window (3) " + + "blocks Windows (1) and (2) correctly.\n" + + "Verification step:\n" + + "\tConditions as seen in Verification step 3 " + + "should be seen, as before.\n" + + "To close all test windows, press 'Finish'.\n\n" + + "7. Repeat the steps for different combinations of Dialog Parent, Dialog Modality Type, Print Dialg Type.\n" + + "Try every dialog parent type and every dialog modality type.\n\n" + + "If any of the Verification step fails, note the combination and press 'Fail'.\n"; + + public static void main(String[] args) throws Exception { + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows(35) + .columns(60) + .testUI(PrintDialogsTest::createUI) + .testTimeOut(10) + .build() + .awaitAndCheck(); + } private Button btnTest; private Checkbox cbPage, cbPrint, @@ -48,6 +98,14 @@ public class PrintDialogsTest extends Applet implements ActionListener { private CheckboxGroup groupDialog, groupParent, groupModType; + private static Frame createUI() { + Frame frame = new Frame("Dialog Modality Testing"); + PrintDialogsTest test = new PrintDialogsTest(); + test.createGUI(); + frame.add(test); + frame.pack(); + return frame; + } public void actionPerformed(ActionEvent e) { @@ -99,13 +157,13 @@ private void createGUI() { setLayout(new BorderLayout()); - setSize(350, 200); Panel panel = new Panel(); - panel.setLayout(new GridLayout(18, 1)); + panel.setLayout(new GridLayout(21, 1)); btnTest = new Button("Start test"); btnTest.addActionListener(this); panel.add(btnTest); + panel.add(new Label(" ")); // spacing panel.add(new Label("Dialog parent:")); @@ -123,6 +181,7 @@ private void createGUI() { panel.add(cbHiddFrm); panel.add(cbDlg); panel.add(cbFrm); + panel.add(new Label(" ")); // spacing panel.add(new Label("Dialog modality type:")); groupModType = new CheckboxGroup(); @@ -139,7 +198,7 @@ private void createGUI() { panel.add(cbDocModal); panel.add(cbTKModal); panel.add(cbModeless); - add(panel); + panel.add(new Label(" ")); // spacing panel.add(new Label("Print dialog type:")); groupDialog = new CheckboxGroup(); @@ -148,13 +207,6 @@ private void createGUI() { panel.add(cbPage); panel.add(cbPrint); - validate(); - setVisible(true); - } - - public void start() { - try { - EventQueue.invokeAndWait(this::createGUI); - } catch (Exception e) {} + add(panel); } } diff --git a/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java b/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java index 3c8faceb3a9a..0f1909711862 100644 --- a/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java +++ b/test/jdk/java/awt/Modal/PrintDialogsTest/Test.java @@ -191,6 +191,7 @@ private void createGUI() { break; case DIALOG: dialog = new CustomDialog(parent); + break; case FRAME: dialog = new CustomDialog(frame); break; diff --git a/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java b/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java index 4faea19db2f4..928bfd027eac 100644 --- a/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java +++ b/test/jdk/java/awt/Modal/ToFront/DialogToFrontModeless1Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, 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 @@ -34,12 +34,27 @@ * @build Flag * @build TestDialog * @build TestFrame + * @build jdk.test.lib.Platform * @run main DialogToFrontModeless1Test */ +import jdk.test.lib.Platform; +import jtreg.SkippedException; + public class DialogToFrontModeless1Test { public static void main(String[] args) throws Exception { + if (Platform.isOnWayland()) { + // Some tested systems are still use XTEST(X11 protocol) + // for key and mouse press emulation, but this will not work + // outside of X11. + // An emulated input event will reach X11 clients, but not the + // Wayland compositor, which is responsible for window restacking. + // + // This skip can be removed later once all systems switch to + // the default remote desktop XDG portal. + throw new SkippedException("SKIPPED: robot functionality is limited on the current platform."); + } (new DialogToFrontModelessTest()).doTest(); } } diff --git a/test/jdk/java/awt/Mouse/EnterExitEvents/DragWindowTest.java b/test/jdk/java/awt/Mouse/EnterExitEvents/DragWindowTest.java index 4f789668c4a5..2a77f294298d 100644 --- a/test/jdk/java/awt/Mouse/EnterExitEvents/DragWindowTest.java +++ b/test/jdk/java/awt/Mouse/EnterExitEvents/DragWindowTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, 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 @@ -26,11 +26,8 @@ * @key headful * @bug 7154048 * @summary Window created under a mouse does not receive mouse enter event. - * Mouse Entered/Exited events are wrongly generated during dragging the window - * from one component to another - * @library ../../regtesthelpers - * @build Util - * @author alexandr.scherbatiy area=awt.event + * Mouse Entered/Exited events are wrongly generated during dragging the + * window from one component to another * @run main DragWindowTest */ @@ -50,76 +47,67 @@ import javax.swing.JPanel; import javax.swing.SwingUtilities; -import java.util.concurrent.Callable; - -import test.java.awt.regtesthelpers.Util; - public class DragWindowTest { - private static volatile int dragWindowMouseEnteredCount = 0; - private static volatile int dragWindowMouseReleasedCount = 0; private static volatile int buttonMouseEnteredCount = 0; private static volatile int labelMouseReleasedCount = 0; + + private static volatile Point pointToClick; + private static volatile Point pointToDrag; + private static MyDragWindow dragWindow; private static JLabel label; private static JButton button; + private static JFrame frame; public static void main(String[] args) throws Exception { + try { + Robot robot = new Robot(); + robot.setAutoDelay(100); - Robot robot = new Robot(); - robot.setAutoDelay(100); - - SwingUtilities.invokeAndWait(new Runnable() { + SwingUtilities.invokeAndWait(DragWindowTest::createAndShowGUI); - @Override - public void run() { - createAndShowGUI(); - } - }); + robot.delay(250); + robot.waitForIdle(); - robot.delay(250); - robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + pointToClick = getCenterPoint(label); + pointToDrag = getCenterPoint(button); + }); - Point pointToClick = Util.invokeOnEDT(new Callable() { + robot.mouseMove(pointToClick.x, pointToClick.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(250); - @Override - public Point call() throws Exception { - return getCenterPoint(label); + if (dragWindowMouseEnteredCount != 1) { + throw new RuntimeException("No MouseEntered event on Drag Window!"); } - }); + // Reset entered count to check if mouse entered starting from here + buttonMouseEnteredCount = 0; + robot.mouseMove(pointToDrag.x, pointToDrag.y); + robot.waitForIdle(); + robot.delay(250); - robot.mouseMove(pointToClick.x, pointToClick.y); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.waitForIdle(); - - if (dragWindowMouseEnteredCount != 1) { - throw new RuntimeException("No MouseEntered event on Drag Window!"); - } - - Point pointToDrag = Util.invokeOnEDT(new Callable() { - - @Override - public Point call() throws Exception { - button.addMouseListener(new ButtonMouseListener()); - return getCenterPoint(button); + if (buttonMouseEnteredCount != 0) { + throw new RuntimeException("Extra MouseEntered event on button!"); } - }); - - robot.mouseMove(pointToDrag.x, pointToDrag.y); - robot.waitForIdle(); - - if (buttonMouseEnteredCount != 0) { - throw new RuntimeException("Extra MouseEntered event on button!"); - } - robot.mouseRelease(InputEvent.BUTTON1_MASK); - robot.waitForIdle(); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(250); - if (labelMouseReleasedCount != 1) { - throw new RuntimeException("No MouseReleased event on label!"); + if (labelMouseReleasedCount != 1) { + throw new RuntimeException("No MouseReleased event on label!"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } - } private static Point getCenterPoint(Component comp) { @@ -129,8 +117,7 @@ private static Point getCenterPoint(Component comp) { } private static void createAndShowGUI() { - - JFrame frame = new JFrame("Main Frame"); + frame = new JFrame("DragWindowTest"); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); @@ -142,6 +129,7 @@ private static void createAndShowGUI() { button = new JButton("Button"); Panel panel = new Panel(new BorderLayout()); + button.addMouseListener(new ButtonMouseListener()); panel.add(label, BorderLayout.NORTH); panel.add(button, BorderLayout.CENTER); @@ -149,7 +137,6 @@ private static void createAndShowGUI() { frame.getContentPane().add(panel); frame.setLocationRelativeTo(null); frame.setVisible(true); - } private static Point getAbsoluteLocation(MouseEvent e) { @@ -157,7 +144,6 @@ private static Point getAbsoluteLocation(MouseEvent e) { } static class MyDragWindow extends Window { - static int d = 30; public MyDragWindow(Window parent, Point location) { @@ -176,8 +162,6 @@ void dragTo(Point point) { } static class LabelMouseListener extends MouseAdapter { - - Point origin; Window parent; public LabelMouseListener(Window parent) { @@ -210,20 +194,13 @@ public void mouseDragged(MouseEvent e) { } static class DragWindowMouseListener extends MouseAdapter { - @Override public void mouseEntered(MouseEvent e) { dragWindowMouseEnteredCount++; } - - @Override - public void mouseReleased(MouseEvent e) { - dragWindowMouseReleasedCount++; - } } static class ButtonMouseListener extends MouseAdapter { - @Override public void mouseEntered(MouseEvent e) { buttonMouseEnteredCount++; diff --git a/test/jdk/java/awt/PopupMenu/PopupMenuVisuals.java b/test/jdk/java/awt/PopupMenu/PopupMenuVisuals.java index 3aa437e48454..966ce30593e1 100644 --- a/test/jdk/java/awt/PopupMenu/PopupMenuVisuals.java +++ b/test/jdk/java/awt/PopupMenu/PopupMenuVisuals.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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,12 +20,13 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 6180413 6184485 6267144 * @summary test for popup menu visual bugs in XAWT - * @library /java/awt/regtesthelpers - * @build PassFailJFrame + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame jdk.test.lib.Platform * @run main/manual PopupMenuVisuals */ @@ -40,16 +41,20 @@ import java.awt.event.ActionListener; import java.awt.event.KeyEvent; +import jdk.test.lib.Platform; + public class PopupMenuVisuals { private static final String INSTRUCTIONS = """ This test should show a button 'Popup'. Click on the button. A popup menu should be shown. If following conditions are met: - - Menu is disabled - - Menu has caption 'Popup menu' (only applicable for linux) - - Menu items don't show shortcuts + - Menu is disabled %s%s - Click Pass else click Fail."""; + Click Pass else click Fail.""" + .formatted( + Platform.isLinux() ? "\n - Menu has caption 'Popup menu'" : "", + !Platform.isOSX() ? "\n - Menu items don't show shortcuts" : "" + ); static PopupMenu pm; static Frame frame; @@ -58,7 +63,6 @@ public static void main(String[] args) throws Exception { PassFailJFrame.builder() .title("PopupMenu Instructions") .instructions(INSTRUCTIONS) - .rows((int) INSTRUCTIONS.lines().count() + 2) .columns(35) .testUI(PopupMenuVisuals::createTestUI) .build() @@ -79,9 +83,9 @@ private static Frame createTestUI() { CheckboxMenuItem mi3 = new CheckboxMenuItem("Item 3"); Menu sm = new Menu("Submenu"); - //Get things going. Request focus, set size, et cetera + // Get things going. Request focus, set size, et cetera frame = new Frame("PopupMenuVisuals"); - frame.setSize (200,200); + frame.setSize(200, 200); frame.validate(); frame.add(b); diff --git a/test/jdk/java/awt/PrintJob/TestPrintNoException.java b/test/jdk/java/awt/PrintJob/TestPrintNoException.java new file mode 100644 index 000000000000..b54ac8de56bd --- /dev/null +++ b/test/jdk/java/awt/PrintJob/TestPrintNoException.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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.Frame; +import java.awt.JobAttributes; +import java.awt.PrintJob; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.event.KeyEvent; + +/* + * @test + * @bug 8378417 + * @key headful printer + * @summary Verifies No Exception is thrown when Printing "All" pages + * @run main TestPrintNoException + */ + +public class TestPrintNoException { + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + Thread t = new Thread (() -> { + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + robot.waitForIdle(); + }); + + Frame testFrame = new Frame("print"); + try { + t.start(); + PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(testFrame, null, null); + if (pj != null) { + pj.end(); + } + } finally { + testFrame.dispose(); + } + } +} diff --git a/test/jdk/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java b/test/jdk/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java index 1f2de081cce1..c0a9c90feba3 100644 --- a/test/jdk/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java +++ b/test/jdk/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved. * 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,30 +22,25 @@ */ import java.awt.Color; -import java.awt.Dialog; import java.awt.Frame; import java.awt.Graphics; -import java.awt.Graphics2D; import java.awt.GraphicsEnvironment; -import java.awt.Panel; import java.awt.Rectangle; import java.awt.Robot; import java.awt.SplashScreen; import java.awt.TextField; -import java.awt.Window; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; -import javax.imageio.ImageIO; -import sun.java2d.SunGraphics2D; +import java.io.IOException; +import javax.imageio.ImageIO; -/** +/* * @test * @key headful * @bug 8043869 8075244 8078082 8145173 8151787 8212213 * @summary Tests the HiDPI splash screen support for windows and MAC - * @modules java.desktop/sun.java2d * @run main MultiResolutionSplashTest GENERATE_IMAGES * @run main/othervm -splash:splash1.png MultiResolutionSplashTest TEST_SPLASH 0 * @run main/othervm -splash:splash2 MultiResolutionSplashTest TEST_SPLASH 1 @@ -56,47 +51,54 @@ public class MultiResolutionSplashTest { private static final int IMAGE_WIDTH = 300; private static final int IMAGE_HEIGHT = 200; - private static boolean isMac; - static { - isMac = System.getProperty("os.name").contains("OS X"); - } + private static final boolean isMac = System.getProperty("os.name") + .contains("OS X"); + private static final ImageInfo[] tests = { - new ImageInfo("splash1.png", "splash1@2x.png", Color.BLUE, Color.GREEN), - new ImageInfo("splash2", "splash2@2x", Color.WHITE, Color.BLACK), - new ImageInfo("splash3.", "splash3@2x.", Color.YELLOW, Color.RED) + new ImageInfo("splash1", ".png", Color.BLUE, Color.GREEN), + new ImageInfo("splash2", "", Color.WHITE, Color.BLACK), + new ImageInfo("splash3", ".", Color.YELLOW, Color.RED) }; public static void main(String[] args) throws Exception { - - String test = args[0]; - switch (test) { + switch (args[0]) { case "GENERATE_IMAGES": generateImages(); break; case "TEST_SPLASH": - int index = Integer.parseInt(args[1]); - testSplash(tests[index]); + testSplash(tests[Integer.parseInt(args[1])]); break; case "TEST_FOCUS": testFocus(); break; default: - throw new RuntimeException("Unknown test: " + test); + throw new RuntimeException("Unknown test: " + args[0]); } } static void testSplash(ImageInfo test) throws Exception { SplashScreen splashScreen = SplashScreen.getSplashScreen(); - if (splashScreen == null) { throw new RuntimeException("Splash screen is not shown!"); } - Graphics2D g = splashScreen.createGraphics(); - Rectangle splashBounds = splashScreen.getBounds(); - int screenX = (int) splashBounds.getCenterX(); - int screenY = (int) splashBounds.getCenterY(); + final Rectangle splashBounds = splashScreen.getBounds(); + final double scaleFactor = getScreenScaleFactor(); + + final Robot robot = new Robot(); + // Allow time for the splash screen to show + robot.delay(100); + + BufferedImage splashCapture = robot.createScreenCapture(splashBounds); + String captureFileName = "splashscreen-%1.2f-%s.png" + .formatted(scaleFactor, test.name1x); + saveImageNoError(splashCapture, new File(captureFileName)); + + // Close the splash screen; this gives time for it to be fully removed + splashScreen.close(); + robot.waitForIdle(); + if (splashBounds.width != IMAGE_WIDTH) { throw new RuntimeException( "SplashScreen#getBounds has wrong width"); @@ -106,19 +108,19 @@ static void testSplash(ImageInfo test) throws Exception { "SplashScreen#getBounds has wrong height"); } - Robot robot = new Robot(); - Color splashScreenColor = robot.getPixelColor(screenX, screenY); - float scaleFactor = getScaleFactor(); + Color splashScreenColor = + new Color(splashCapture.getRGB(splashBounds.width / 2, + splashBounds.height / 2)); Color testColor = (1 < scaleFactor) ? test.color2x : test.color1x; if (!compare(testColor, splashScreenColor)) { throw new RuntimeException( - "Image with wrong resolution is used for splash screen!"); + "Image with wrong resolution is used for splash screen! " + + "Refer to " + captureFileName); } } static void testFocus() throws Exception { - Robot robot = new Robot(); robot.setAutoWaitForIdle(true); robot.setAutoDelay(50); @@ -157,94 +159,85 @@ static boolean compare(int n, int m) { return Math.abs(n - m) <= 50; } - static float getScaleFactor() { - - final Dialog dialog = new Dialog((Window) null); - dialog.setSize(100, 100); - dialog.setModal(true); - final float[] scaleFactors = new float[1]; - Panel panel = new Panel() { - - @Override - public void paint(Graphics g) { - float scaleFactor = 1; - if (g instanceof SunGraphics2D) { - scaleFactor = getScreenScaleFactor(); - } - scaleFactors[0] = scaleFactor; - dialog.setVisible(false); - } - }; - - dialog.add(panel); - dialog.setVisible(true); - dialog.dispose(); - - return scaleFactors[0]; - } - static void generateImages() throws Exception { for (ImageInfo test : tests) { - generateImage(test.name1x, test.color1x, 1); - generateImage(test.name2x, test.color2x, getScreenScaleFactor()); + generateImage(test.name1x, test.color1x, 1.0); + + // Ensure the second image uses scale greater than 1.0 + double scale = getAdjustedScaleFactor(); + generateImage(test.name2x, test.color2x, scale); } } - static void generateImage(String name, Color color, float scale) throws Exception { + static void generateImage(final String name, + final Color color, + final double scale) throws Exception { File file = new File(name); if (file.exists()) { return; } - BufferedImage image = new BufferedImage((int) (scale * IMAGE_WIDTH), - (int) (scale * IMAGE_HEIGHT), BufferedImage.TYPE_INT_RGB); + + final int width = (int) (scale * IMAGE_WIDTH); + final int height = (int) (scale * IMAGE_HEIGHT); + BufferedImage image = new BufferedImage(width, + height, + BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(color); - g.fillRect(0, 0, (int) (scale * IMAGE_WIDTH), (int) (scale * IMAGE_HEIGHT)); + g.fillRect(0, 0, width, height); + + saveImage(image, file); + } + + private static void saveImage(BufferedImage image, + File file) throws IOException { ImageIO.write(image, "png", file); } - static float getScreenScaleFactor() { - return (float) GraphicsEnvironment. - getLocalGraphicsEnvironment(). - getDefaultScreenDevice().getDefaultConfiguration(). - getDefaultTransform().getScaleX(); + private static void saveImageNoError(BufferedImage image, + File file) { + try { + saveImage(image, file); + } catch (IOException ignored) { + } } - static class ImageInfo { + static double getScreenScaleFactor() { + return GraphicsEnvironment + .getLocalGraphicsEnvironment() + .getDefaultScreenDevice() + .getDefaultConfiguration() + .getDefaultTransform() + .getScaleX(); + } + + // Ensure the second image uses scale greater than 1.0 + static double getAdjustedScaleFactor() { + double scale = getScreenScaleFactor(); + return scale < 1.25 ? 2.0 : scale; + } + static class ImageInfo { final String name1x; final String name2x; final Color color1x; final Color color2x; - public ImageInfo(String name1x, String name2x, Color color1x, Color color2x) { - this.name1x = name1x; - if (!isMac) { - float scale = getScreenScaleFactor(); - StringBuffer buff = new StringBuffer(); - if (scale - (int) scale > 0) { - buff.append("@").append((int) (scale * 100)).append("pct"); - } else { - buff.append("@").append((int) scale).append("x"); - } - StringBuffer buffer = new StringBuffer(); - String[] splitStr = name1x.split("\\."); - if (splitStr.length == 2) { - this.name2x = buffer.append(splitStr[0]).append(buff) - .append(".").append(splitStr[1]).toString(); - } else { - if (name1x.indexOf(".") > 0) { - this.name2x = buffer.append(splitStr[0]).append(buff).append(".").toString(); - } else { - this.name2x = buffer.append(splitStr[0]).append(buff).toString(); - } - } - } else { - this.name2x = name2x; - } + public ImageInfo(String baseName, String ext, + Color color1x, Color color2x) { + this.name1x = baseName + ext; + this.name2x = createName2x(baseName, ext); this.color1x = color1x; this.color2x = color2x; } + + private static String createName2x(String baseName, String ext) { + double scale = getAdjustedScaleFactor(); + if (!isMac && (((int) (scale * 100)) % 100 != 0)) { + return baseName + "@" + ((int) (scale * 100)) + "pct" + ext; + } else { + return baseName + "@" + ((int) scale) + "x" + ext; + } + } } } - diff --git a/test/jdk/java/awt/TextArea/PrintTextTest.java b/test/jdk/java/awt/TextArea/PrintTextTest.java new file mode 100644 index 000000000000..8cf147747328 --- /dev/null +++ b/test/jdk/java/awt/TextArea/PrintTextTest.java @@ -0,0 +1,98 @@ +/* + * 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.BorderLayout; +import java.awt.Button; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Label; +import java.awt.Panel; +import java.awt.PrintJob; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4075786 + * @key printer + * @summary Test that container prints multiline text properly + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual PrintTextTest +*/ + +public class PrintTextTest extends Frame implements ActionListener { + Panel p; + + static final String INSTRUCTIONS = """ + Press "Print" button and check that multiline test + printed correctly. If so press Pass, otherwise Fail. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("PrintTextTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(35) + .testUI(PrintTextTest::new) + .build() + .awaitAndCheck(); + } + + public PrintTextTest() { + p = new Panel(); + p.setLayout(new BorderLayout()); + TextArea text_area = new TextArea("multi\nline\ntext\nfield\nis \nhere\n!!!!\n"); + + TextField text_field = new TextField("single line textfield"); + Button button = new Button("button"); + Label label = new Label("single line label"); + p.add("South", text_area); + p.add("North", new TextArea("one single line of textarea")); + p.add("Center", text_field); + p.add("West", button); + + add("North", p); + + Button b = new Button("Print"); + b.addActionListener(this); + add("South", b); + pack(); + } + + public void actionPerformed(ActionEvent e) { + PrintJob pjob = getToolkit().getPrintJob(this, "Print", null); + if (pjob != null) { + Graphics pg = pjob.getGraphics(); + + if (pg != null) { + p.printAll(pg); + pg.dispose(); //flush page + } + pjob.end(); + } + } +} diff --git a/test/jdk/java/awt/TextArea/ScrollBarArrowScrollTest.java b/test/jdk/java/awt/TextArea/ScrollBarArrowScrollTest.java new file mode 100644 index 000000000000..cf54bd575855 --- /dev/null +++ b/test/jdk/java/awt/TextArea/ScrollBarArrowScrollTest.java @@ -0,0 +1,65 @@ +/* + * 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 + * 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.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 6175401 + * @summary Keeping the left arrow pressedon horiz scrollbar + * does not scroll the text in TextArea, XToolkit + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual ScrollBarArrowScrollTest +*/ + + +public class ScrollBarArrowScrollTest extends Frame { + private static final String INSTRUCTIONS = """ + 1) Make sure, that the TextArea component has focus. + 2) Press 'END' key in order to keep cursor at the end + of the text of the TextArea component. + 3) Click on the left arrow on the horizontal scrollbar + of the TextArea component and keep it pressed. + 4) If the text just scrolls once and stops, the test failed. + Otherwise, the test passed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("ScrollBarArrowScrollTest") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(ScrollBarArrowScrollTest::new) + .build() + .awaitAndCheck(); + } + + public ScrollBarArrowScrollTest() { + TextArea textarea = new TextArea("Very very very long string !!!! ", 10, 3); + add(textarea); + pack(); + + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest.java b/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest.java new file mode 100644 index 000000000000..f506f54f6f14 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest.java @@ -0,0 +1,98 @@ +/* + * 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 + * 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.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 5003402 + * @summary TextArea must scroll automatically when calling append and select, even when not in focus + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaAppendScrollTest + */ + +public class TextAreaAppendScrollTest extends Frame implements ActionListener { + int phase; + int pos1, pos2; + TextArea area; + private static final String INSTRUCTIONS = """ + Press "Click Here" button. + The word "First" should be visible in the TextArea. + + Press "Click Here" button again. + The word "Next" should be visible in the TextArea. + + Press "Click Here" button again. + The word "Last" should be visible in the TextArea. + If you have seen all three words, press Pass, else press Fail. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaAppendScrollTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaAppendScrollTest::new) + .build() + .awaitAndCheck(); + } + + public TextAreaAppendScrollTest() { + area = new TextArea(); + add("Center", area); + Button bt1 = new Button("Click Here"); + add("South", bt1); + String filler = ""; + for (int i = 0; i < 100; i++) { + filler = filler + i + "\n"; + } + String text = filler; + pos1 = text.length(); + text = text + "First\n" + filler; + pos2 = text.length(); + text = text + "Next\n" + filler; + area.setText(text); + phase = 0; + bt1.addActionListener(this); + pack(); + } + + public void actionPerformed(ActionEvent ev) { + if (phase == 0) { + area.select(pos1, pos1); + phase = 1; + } else if (phase == 1) { + area.select(pos2, pos2); + phase = 2; + } else { + area.append("Last\n"); + phase = 0; + } + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest2.java b/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest2.java new file mode 100644 index 000000000000..2f0e44b415e1 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaAppendScrollTest2.java @@ -0,0 +1,68 @@ +/* + * 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 + * 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.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 6192116 + * @summary Auto-scrolling does not work properly for TextArea when appending some text, on XToolkit + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaAppendScrollTest2 + */ + +public class TextAreaAppendScrollTest2 extends Frame { + TextArea area; + private static final String INSTRUCTIONS = """ + Press pass if you see exclamation marks in the bottom of textarea. + Press fail if you don't. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaAppendScrollTest2") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaAppendScrollTest2::new) + .build() + .awaitAndCheck(); + } + + public TextAreaAppendScrollTest2() { + setLayout(new BorderLayout()); + area = new TextArea("AWT is cool ", 3, 3, TextArea.SCROLLBARS_NONE); + add("Center", area); + setSize(200, 200); + StringBuilder coolStr = new StringBuilder(""); + // I count 15 lines with 12 cools per line + for (int i = 0; i < 12 * 15; i++) { + coolStr.append("cool "); + } + coolStr.append("!!!!!!!"); + area.append(coolStr.toString()); + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaAppendTest.java b/test/jdk/java/awt/TextArea/TextAreaAppendTest.java new file mode 100644 index 000000000000..c47d621e788a --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaAppendTest.java @@ -0,0 +1,68 @@ +/* + * 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 java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 4118915 + * @summary Test appending to a TextArea after the peer is created + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaAppendTest + */ + +public class TextAreaAppendTest { + private static final String INSTRUCTIONS = """ + If all four lines are visible in TextArea, the test passed. + If the last two lines have only one character visible, the test failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaAppendTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaAppendTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame f = new Frame("TextAreaAppendTest"); + TextArea ta = new TextArea(); + f.add(ta); + ta.append("line 1 (added before drawing)\n"); + ta.append("line 2 (added before drawing)\n"); + + f.pack(); + f.show(); + + ta.append("line 3 (added after drawing)\n"); + ta.append("line 4 (added after drawing)\n"); + + return f; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaCRLFAutoDetectManualTest.java b/test/jdk/java/awt/TextArea/TextAreaCRLFAutoDetectManualTest.java new file mode 100644 index 000000000000..c8c3f0662a5c --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaCRLFAutoDetectManualTest.java @@ -0,0 +1,106 @@ +/* + * 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 + * 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.GridLayout; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.TextField; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4800187 + * @summary REGRESSION:show the wrong selection when there are \r characters in the text + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaCRLFAutoDetectManualTest + */ + +public class TextAreaCRLFAutoDetectManualTest { + static int flag = 1; + + private static final String INSTRUCTIONS = """ + Please click the button several times. + If you see the text '679' selected on the left TextArea + and the same text on the right TextArea + each time you press the button, + the test passed, else failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaCRLFAutoDetectManualTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaCRLFAutoDetectManualTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame f = new Frame("TextAreaCRLFAutoDetectManualTest"); + + TextArea ta1 = new TextArea(5, 20); + TextArea ta2 = new TextArea(5, 20); + + TextField tf1 = new TextField("123", 20); + TextField tf2 = new TextField("567", 20); + TextField tf3 = new TextField("90", 20); + + Button b = new Button("Click Me Several Times"); + + b.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent evt) { + ta1.setText(""); + ta2.setText(""); + flag++; + String eoln = ((flag % 2) != 0) ? "\r\n" : "\n"; + ta1.setText(eoln + tf1.getText() + eoln + tf2.getText() + eoln + tf3.getText() + eoln); + ta1.select(6, 10); + ta2.setText(ta1.getSelectedText()); + ta1.requestFocus(); + } + }); + + f.setLayout(new FlowLayout()); + + Panel tfpanel = new Panel(); + tfpanel.setLayout(new GridLayout(3, 1)); + tfpanel.add(tf1); + tfpanel.add(tf2); + tfpanel.add(tf3); + f.add(tfpanel); + + f.add(ta1); + f.add(ta2); + f.add(b); + + f.pack(); + return f; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaCursorTest.java b/test/jdk/java/awt/TextArea/TextAreaCursorTest.java new file mode 100644 index 000000000000..ec342e38a155 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaCursorTest.java @@ -0,0 +1,86 @@ +/* + * 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.BorderLayout; +import java.awt.Button; +import java.awt.Cursor; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.TextArea; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/* + * @test + * @bug 4060320 + * @summary Test TextArea cursor shape on its scrollbars + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaCursorTest + */ + +public class TextAreaCursorTest { + private static final String INSTRUCTIONS = """ + Move the cursor into textarea and on scrollbar. Verify that the shape of + cursor on scrollbar should not be I-beam. Also, when the cursor in textarea + is set to some other shape, it does not affect the cursor shape on the + scrollbars. + """; + + public static void main(String args[]) throws Exception { + PassFailJFrame.builder() + .title("TextAreaCursorTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaCursorTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI () { + Frame f = new Frame("TextAreaCursorTest"); + BorderLayout layout = new BorderLayout(); + f.setLayout(layout); + + TextArea ta = new TextArea("A test to make sure that cursor \n" + + "on scrollbars has the correct shape\n\n" + + "Press button to change the textarea\n" + + "cursor to Hand_Cursor\n" + + "Make sure that the cursor on scrollbars\n" + + "remains the same", 10, 30); + + Button bu = new Button("Change Cursor"); + + f.add(ta, BorderLayout.NORTH); + f.add(bu, BorderLayout.SOUTH); + bu.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + Cursor curs1 = new Cursor(Cursor.HAND_CURSOR); + ta.setCursor(curs1); + } + }); + f.pack(); + return f; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaHScrollbarTest.java b/test/jdk/java/awt/TextArea/TextAreaHScrollbarTest.java new file mode 100644 index 000000000000..3bf1c6997638 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaHScrollbarTest.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +import java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 4648702 + * @summary TextArea horizontal scrollbar behavior is incorrect + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaHScrollbarTest + */ + +public class TextAreaHScrollbarTest { + private static final String INSTRUCTIONS = """ + Please look at the frame. + If the vertical and horizontal scrollbars are visible + the test passed else failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaHScrollbarTest") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(TextAreaHScrollbarTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame test = new Frame(); + test.add(new TextArea("TextAreaHScrollbarTest", 5, 60, + TextArea.SCROLLBARS_BOTH)); + test.setSize(200, 100); + return test; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaKeypadTest.java b/test/jdk/java/awt/TextArea/TextAreaKeypadTest.java new file mode 100644 index 000000000000..24fabdd01ab8 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaKeypadTest.java @@ -0,0 +1,62 @@ +/* + * 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.BorderLayout; +import java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 6240876 + * @summary Number pad up & down arrows don't work in XToolkit TextArea + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaKeypadTest + */ + +public class TextAreaKeypadTest { + private static final String INSTRUCTIONS = """ + Press pass if you can move the caret in the textarea with _number pad_ UP/DOWN keys. + Press fail if you don't. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaKeypadTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaKeypadTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame frame = new Frame("TextAreaKeypadTest"); + frame.setLayout(new BorderLayout()); + TextArea area = new TextArea("One\nTwo\nThree", 3, 3, TextArea.SCROLLBARS_NONE); + frame.add("Center", area); + frame.pack(); + return frame; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaLimit.java b/test/jdk/java/awt/TextArea/TextAreaLimit.java new file mode 100644 index 000000000000..424305c90ead --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaLimit.java @@ -0,0 +1,70 @@ +/* + * 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.BorderLayout; +import java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 4341196 + * @summary Tests that TextArea can handle more than 64K of text + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaLimit + */ + +public class TextAreaLimit extends Frame { + static TextArea text; + private static final String INSTRUCTIONS = """ + You will see a text area with 40000 lines of text + each with its own line number. If you see the caret after line 39999 + then test passes. Otherwise it fails. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaLimit") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaLimit::new) + .build() + .awaitAndCheck(); + } + + public TextAreaLimit() { + setLayout(new BorderLayout()); + + text = new TextArea(); + add(text); + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 40000; i++) { + buf.append(i + "\n"); + } + text.setText(buf.toString()); + text.setCaretPosition(buf.length()); + text.requestFocus(); + setSize(200, 200); + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaLineScrollWrapTest.java b/test/jdk/java/awt/TextArea/TextAreaLineScrollWrapTest.java new file mode 100644 index 000000000000..72ec7c08a6ce --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaLineScrollWrapTest.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +import java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 4776535 + * @summary Regression: line should not wrap around into multi lines in TextArea. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaLineScrollWrapTest + */ + +public class TextAreaLineScrollWrapTest { + private static final String INSTRUCTIONS = """ + You should see a frame "TextAreaLineScrollWrapTest" with + a TextArea that contains a very long line. + If the line is wrapped the test is failed. + + Insert a lot of text lines and move a caret to the last one. + If a caret hides and a content of the TextArea + does not scroll the test is failed + else the test is passed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaLineScrollWrapTest") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(TextAreaLineScrollWrapTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame f = new Frame("TextAreaLineScrollWrapTest"); + f.add(new TextArea("long long long long long long long line...........", + 3, 4)); + f.setSize(100, 100); + return f; + } +} diff --git a/test/jdk/java/awt/TextArea/TextAreaScrollbarTest.java b/test/jdk/java/awt/TextArea/TextAreaScrollbarTest.java new file mode 100644 index 000000000000..ee61922fdb16 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaScrollbarTest.java @@ -0,0 +1,116 @@ +/* + * 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 java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; +import java.awt.TextArea; + +/* + * @test + * @bug 4158997 + * @key headful + * @summary Make sure that the TextArea has both horizontal and + * vertical scrollbars when bad scrollbar arguments are passed + * into the constructor. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaScrollbarTest + */ + +public class TextAreaScrollbarTest { + private static final String INSTRUCTIONS = """ + Check to see that each TextArea has the specified + number and placement of scrollbars, i.e., both scrollbars, + horizontal only, vertical only, or no scrollbars at all. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaScrollbarTest") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(TestFrame::new) + .build() + .awaitAndCheck(); + } +} + +class TestFrame extends Frame { + private String both = "Both Scrollbars Both Scrollbars Both Scrollbars\n"; + private String horiz = "Horizontal Scrollbar Only Horizontal Scrollbar Only\n"; + private String vert = "Vertical Scrollbar Only Vertical Scrollbar Only\n"; + private String none = "No Scrollbars No Scrollbars No Scrollbars No Scrollbars\n"; + + public TestFrame() { + super("Test frame"); + + // sets a GridLayout w/ 2 columns and an unspecified # of rows + setLayout(new GridLayout(0, 2, 15, 5)); + + TextArea t1 = new TextArea(both + both + both + both + both + both, 3, 8, 0); + add(new Label("TA should have both scrollbars: arg = 0")); + add(t1); + + TextArea t2 = new TextArea(both + both + both + both + both + both, 3, 8, -1); + add(new Label("TA should have both scrollbars: arg = -1")); + add(t2); + + TextArea t3 = new TextArea(both + both + both + both + both + both, 3, 8, 4); + add(new Label("TA should have both scrollbars: arg = 4")); + add(t3); + + TextArea t4 = new TextArea(horiz + horiz + horiz + horiz + horiz + horiz, 3, 8, 2); + add(new Label("TA should have horizontal scrollbar: arg = 2")); + add(t4); + + TextArea t5 = new TextArea(vert + vert + vert + vert + vert + vert, 3, 8, 1); + add(new Label("TA should have vertical scrollbar: arg = 1")); + add(t5); + + TextArea t6 = new TextArea(none + none + none + none + none + none, 3, 8, 3); + add(new Label("TA should have no scrollbars: arg = 3")); + add(t6); + + TextArea t7 = new TextArea(); + t7.setText(both + both + both + both + both + both); + add(new Label("Both scrollbars: TextArea()")); + add(t7); + + TextArea t8 = new TextArea(both + both + both + both + both + both); + add(new Label("Both scrollbars: TextArea(String text)")); + add(t8); + + TextArea t9 = new TextArea(3, 8); + t9.setText(both + both + both + both + both + both); + add(new Label("Both scrollbars: TextArea(int rows, int columns)")); + add(t9); + + TextArea t10 = new TextArea(both + both + both + both + both + both, 3, 8); + add(new Label("Both scrollbars: TextArea(text, rows, columns)")); + add(t10); + + setSize(600, 600); + } +} + diff --git a/test/jdk/java/awt/TextArea/TextAreaSelectionTest.java b/test/jdk/java/awt/TextArea/TextAreaSelectionTest.java new file mode 100644 index 000000000000..ed6ccb34fa25 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextAreaSelectionTest.java @@ -0,0 +1,111 @@ +/* + * 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.FlowLayout; +import java.awt.Frame; +import java.awt.Menu; +import java.awt.MenuBar; +import java.awt.MenuItem; +import java.awt.TextArea; +import java.awt.TextField; + +/* + * @test + * @bug 4095946 + * @summary 592677:TEXTFIELD TAB SELECTION CONFUSING; REMOVE ES_NOHIDESEL STYLE IN + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextAreaSelectionTest + */ + +public class TextAreaSelectionTest { + private static final String INSTRUCTIONS = """ + Please look at the 'TextAreaSelectionTest' frame. + + If you see that the all TextFields and TextAreas have + the highlighted selections, the test FAILED. Else, if + you see that the text of the focused component is + highlighted, it is ok. + + Try to traverse the focus through all components by + pressing CTRL+TAB. If the focused component highlights + its selection, the test is passed for a while. + + Please select the entire/part of the text of some component + by mouse and choose some menu item. If the highlighted + selection is hidden, the test FAILED. + + Please select the entire/part of the text of some component + by mouse and click right mouse button. A context menu + should appear. Please check its items. + Press ESC to hide the context menu. If the selection + of the text component is not visible, the test FAILED. + + Please double click on the word 'DoubleClickMe' in the + first text area. If there are several words selected, the + test FAILED, if the word 'DoubleClickMe' is selected only, + the test PASSED! + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextAreaSelectionTest") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(TextAreaSelectionTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame f = new Frame("TextAreaSelectionTest"); + f.setLayout(new FlowLayout()); + + MenuBar mb = new MenuBar(); + String name = "Submenu"; + Menu m = new Menu(name, false); + m.add(new MenuItem(name + " item 1")); + m.add(new MenuItem(name + " item 2")); + m.add(new MenuItem(name + " item 3")); + mb.add(m); + + TextField tf1, tf2; + TextArea ta1, ta2; + f.setMenuBar(mb); + f.add(tf1 = new TextField("some text")); + f.add(tf2 = new TextField("more text")); + String eoln = System.getProperty("line.separator", "\n"); + f.add(ta1 = new TextArea("some text" + eoln + eoln + "DoubleClickMe")); + f.add(ta2 = new TextArea("more text")); + + tf1.selectAll(); + tf2.selectAll(); + ta1.selectAll(); + ta2.selectAll(); + + f.pack(); + return f; + } + +} diff --git a/test/jdk/java/awt/TextArea/TextScrollTest.java b/test/jdk/java/awt/TextArea/TextScrollTest.java new file mode 100644 index 000000000000..4a92391e7af5 --- /dev/null +++ b/test/jdk/java/awt/TextArea/TextScrollTest.java @@ -0,0 +1,69 @@ +/* + * 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 java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.Panel; +import java.awt.TextArea; + +/* + * @test + * @bug 4127272 + * @summary TextArea displays head of text when scrolling horizontal bar. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TextScrollTest + */ + +public class TextScrollTest extends Frame { + private static final String INSTRUCTIONS = """ + 1. A TextArea whose content starts with the text ", + 'Scroll till the' will appear on the applet ", + 2. Use the Horizontal thumb button of the TextArea to view the entire", + content of the TextArea", + 3. While scrolling, if the text 'Scroll till the' appears repeatedly, Click Fail ", + else Click Pass" + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("TextScrollTest") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(TextScrollTest::new) + .build() + .awaitAndCheck(); + } + + public TextScrollTest() { + this.setLayout(new BorderLayout()); + + Panel p = new Panel(); + TextArea ta = new TextArea("Scroll till the right end of the " + + "TextArea is reached. Action Done?\n", 10, 20); + + p.add(ta); + add("Center", p); + setSize(200, 200); + } +} diff --git a/test/jdk/java/awt/TextArea/WordWrappingTest.java b/test/jdk/java/awt/TextArea/WordWrappingTest.java new file mode 100644 index 000000000000..7309bc510082 --- /dev/null +++ b/test/jdk/java/awt/TextArea/WordWrappingTest.java @@ -0,0 +1,66 @@ +/* + * 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 + * 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.FlowLayout; +import java.awt.Frame; +import java.awt.TextArea; + +/* + * @test + * @bug 4992455 + * @summary REGRESSION: TextArea does not wrap text in JDK 1.5 as JDK 1.4.x + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual WordWrappingTest +*/ + +public class WordWrappingTest { + private static final String INSTRUCTIONS = """ + Please look at the frame 'WordWrappingTest' + It contains two TextAreas that have text 'This text should be wrapped.' + One of them has a vertical scrollbar only. Another has no + scrollbars at all. + If their text is not wrapped at word boundaries and you partially see + mentioned text, the test failed. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("WordWrappingTest") + .instructions(INSTRUCTIONS) + .testUI(WordWrappingTest::createGUI) + .build() + .awaitAndCheck(); + } + + public static Frame createGUI() { + Frame f = new Frame("WordWrappingTest"); + f.setLayout(new FlowLayout()); + f.add(new TextArea("This text should be wrapped.", 5, 10, + TextArea.SCROLLBARS_VERTICAL_ONLY)); + f.add(new TextArea("This text should be wrapped.", 5, 10, + TextArea.SCROLLBARS_NONE)); + f.pack(); + return f; + } +} diff --git a/test/jdk/java/awt/Toolkit/ScreenInsetsTest/ScreenInsetsTest.java b/test/jdk/java/awt/Toolkit/ScreenInsetsTest/ScreenInsetsTest.java index 2cd05b08fc51..207954c521b6 100644 --- a/test/jdk/java/awt/Toolkit/ScreenInsetsTest/ScreenInsetsTest.java +++ b/test/jdk/java/awt/Toolkit/ScreenInsetsTest/ScreenInsetsTest.java @@ -24,7 +24,7 @@ /* * @test * @key headful - * @bug 8020443 6899304 4737732 + * @bug 8020443 6899304 4737732 8357390 * @summary Tests that Toolkit.getScreenInsets() returns correct insets * @library /test/lib * @build jdk.test.lib.Platform @@ -44,7 +44,7 @@ public class ScreenInsetsTest { private static final int SIZE = 100; // Allow a margin tolerance of 1 pixel due to scaling - private static final int MARGIN_TOLERANCE = 1; + private static final int MARGIN_TOLERANCE = 2; public static void main(String[] args) throws InterruptedException { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); diff --git a/test/jdk/java/awt/font/BoldItalicFontTest.java b/test/jdk/java/awt/font/BoldItalicFontTest.java new file mode 100644 index 000000000000..7fdefcfe2b52 --- /dev/null +++ b/test/jdk/java/awt/font/BoldItalicFontTest.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2004, 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.Font; +import java.awt.Frame; +import java.awt.GridLayout; +import java.awt.Label; + +/* + * @test + * @bug 4935871 + * @summary Check that correct type faces are used regardless of bold/italic styles + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual/othervm -Duser.language=ja -Duser.country=JP BoldItalicFontTest + */ + +public class BoldItalicFontTest { + + public static void main(String[] args) throws Exception { + final String INSTRUCTIONS = """ + This test is reproduced with a non-English user locale only. + All the letters "X" in the first line should be in serif font. + All the letters "X" in the second line should be in sans-serif font. + + If so, press Pass, else press Fail."""; + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(BoldItalicFontTest::createUI) + .build() + .awaitAndCheck(); + } + + private static Frame createUI() { + String[] faces = { Font.SERIF, Font.SANS_SERIF }; + int[] styles = { 0, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC }; + + Frame f = new Frame("BoldItalicFontTest Test UI"); + f.setLayout(new GridLayout(faces.length, styles.length)); + for (int fn = 0; fn < faces.length; fn++) { + for (int sn = 0; sn < styles.length; sn++) { + Label l = new Label("X"); + Font f1 = new Font(faces[fn], styles[sn], 36); + l.setFont(f1); + f.add(l); + } + } + f.setSize(300, 300); + return f; + } +} diff --git a/test/jdk/java/awt/font/GlyphVector/TestGlyphVectorLayout.java b/test/jdk/java/awt/font/GlyphVector/TestGlyphVectorLayout.java new file mode 100644 index 000000000000..b183b6526421 --- /dev/null +++ b/test/jdk/java/awt/font/GlyphVector/TestGlyphVectorLayout.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2002, 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.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.font.GlyphVector; +import java.awt.font.FontRenderContext; +import java.awt.geom.AffineTransform; +import java.awt.geom.Rectangle2D; + +import javax.swing.JPanel; + +/* + * @test + * @bug 4615017 + * @summary Display two GlyphVectors, and ensure they are of the same length. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestGlyphVectorLayout + */ + +public class TestGlyphVectorLayout extends JPanel { + private final Font font; + private final FontRenderContext frc; + private final String text; + + private GlyphVector aftergv; + private Rectangle pbounds; + private Rectangle2D vbounds; + + public static void main(String[] args) throws Exception { + final String INSTRUCTIONS = """ + Two lines of text should appear, the top one with boxes + (red and blue) around it. + The two lines should be of the same length, and the boxes around the + top line should 'fit' the text with no empty space between the end + of the text and the box. + + Pass the test if this is true."""; + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(TestGlyphVectorLayout::new) + .build() + .awaitAndCheck(); + } + + private TestGlyphVectorLayout() { + setBackground(Color.WHITE); + font = new Font(Font.DIALOG, Font.PLAIN, 24); + frc = new FontRenderContext(null, false, false); + text = "this is a test of glyph vector"; + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(550, 150); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + Graphics2D g2d = (Graphics2D) g; + + float x = 50; + float y = 50; + AffineTransform oldtx = g2d.getTransform(); + g2d.translate(x, y); + g2d.scale(1.5, 1.5); + + g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, + RenderingHints.VALUE_FRACTIONALMETRICS_OFF); + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); + + g2d.setColor(Color.BLACK); + + GlyphVector gv = font.createGlyphVector(frc, text); // new each time + g2d.drawGlyphVector(gv, 0, 0); + + if (vbounds == null) { + vbounds = gv.getVisualBounds(); + pbounds = gv.getPixelBounds(g2d.getFontRenderContext(), 0, 0); + aftergv = gv; + } + g2d.drawGlyphVector(aftergv, 0, 30); + + g2d.setColor(Color.BLUE); + g2d.draw(vbounds); + + g2d.setTransform(oldtx); + g2d.setColor(Color.RED); + g2d.draw(pbounds); + } +} diff --git a/test/jdk/java/awt/font/GlyphVector/TestSetGlyphPositions.java b/test/jdk/java/awt/font/GlyphVector/TestSetGlyphPositions.java new file mode 100644 index 000000000000..f56d82143950 --- /dev/null +++ b/test/jdk/java/awt/font/GlyphVector/TestSetGlyphPositions.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 1999, 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.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.font.GlyphVector; +import java.awt.font.FontRenderContext; +import java.awt.geom.Point2D; + +import javax.swing.JPanel; + +/* + * @test + * @bug 4180379 + * @summary set the positions of glyphs in the GlyphVector to other than + * their default x, y positions, and verify that the rendered glyphs are + * in the new positions, not the default positions. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestSetGlyphPositions + */ + +public class TestSetGlyphPositions extends JPanel { + GlyphVector gv = null; + + public static void main(String[] args) throws Exception { + final String INSTRUCTIONS = """ + 'TopLeft text and >' should appear towards the top left of the frame, + and '< and BottomRight text' should appear towards the bottom right. + + There should be some space between the '>' and '<' symbols, both vertically + and horizontally. + + Pass the test if this is true."""; + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(TestSetGlyphPositions::new) + .build() + .awaitAndCheck(); + } + + public TestSetGlyphPositions() { + setBackground(Color.WHITE); + setSize(550, 150); + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(550, 150); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + Graphics2D g2d = (Graphics2D) g; + + if (gv == null) { + Font font = new Font(Font.DIALOG, Font.PLAIN, 36); + FontRenderContext frc = g2d.getFontRenderContext(); + String str = "TopLeft> 0 && args[0].equalsIgnoreCase("verbose")); + + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .rows(20) + .columns(50) + .testTimeOut(15) + .screenCapture() + .testUI(RotFontBoundsTest::createUI) + .build() + .awaitAndCheck(); + } + + private static final int ROTATIONS = 8; + + private static JComponent createUI() { + final RotatedTextBounds rotatedText = new RotatedTextBounds(); + + final JPanel checkBoxes = new JPanel(new FlowLayout(FlowLayout.CENTER, + 4, 4)); + checkBoxes.setBorder(createEmptyBorder(0, 8, 8, 8)); + for (int i = 0; i < ROTATIONS; i++) { + checkBoxes.add(new JCheckBox(new SelectRotationAction(i, rotatedText))); + } + + JButton selectAll = new JButton("Select All"); + selectAll.addActionListener( + e -> selectAllCheckBoxes(checkBoxes.getComponents(), true)); + selectAll.setMnemonic('S'); + + JButton clearAll = new JButton("Clear All"); + clearAll.addActionListener( + e -> selectAllCheckBoxes(checkBoxes.getComponents(), false)); + clearAll.setMnemonic('C'); + + Box controls = Box.createHorizontalBox(); + controls.add(new JLabel("Visible Rotations:")); + controls.add(Box.createHorizontalGlue()); + controls.add(selectAll); + controls.add(Box.createHorizontalStrut(4)); + controls.add(clearAll); + controls.setBorder(createEmptyBorder(8, 8, 0, 8)); + + Box controlPanel = Box.createVerticalBox(); + controlPanel.add(controls); + controlPanel.add(checkBoxes); + + Box javaVersion = Box.createHorizontalBox(); + javaVersion.setBorder(createEmptyBorder(8, 8, 8, 8)); + javaVersion.add(new JLabel("Java version: " + + System.getProperty("java.runtime.version"))); + javaVersion.add(Box.createHorizontalGlue()); + + Box main = Box.createVerticalBox(); + main.setName("Rotated TextLayout Test"); + main.add(controlPanel); + main.add(rotatedText); + main.add(javaVersion); + + return main; + } + + private static final class RotatedTextBounds extends JComponent { + private final Font font = new Font(Font.DIALOG, Font.PLAIN, 24); + + private final boolean[] rotationVisible = new boolean[ROTATIONS]; + + private RotatedTextBounds() { + setBackground(Color.WHITE); + setPreferredSize(new Dimension(400, 400)); + Arrays.fill(rotationVisible, true); + } + + public void setRotationVisible(int rotation, boolean visible) { + rotationVisible[rotation] = visible; + repaint(); + } + + // Counts the number of paints + private int counter = 0; + + @Override + public void paintComponent(Graphics _g) { + Graphics2D g = (Graphics2D) _g; + Dimension d = getSize(); + + g.setColor(getBackground()); + g.fillRect(0, 0, d.width, d.height); + + counter++; + int x = d.width / 2; + int y = d.height / 2; + FontRenderContext frc = g.getFontRenderContext(); + + for (int i = 0; i < ROTATIONS; i++) { + if (!rotationVisible[i]) { + continue; + } + + double angle = -Math.PI / 4.0 * i; + AffineTransform flip = AffineTransform.getRotateInstance(angle); + Font flippedFont = font.deriveFont(flip); + TextLayout tl = new TextLayout(TEXT, flippedFont, frc); + Rectangle2D bb = tl.getBounds(); + g.setPaint(Color.BLACK); + tl.draw(g, x, y); + g.setPaint(Color.RED); + g.drawRect(x + (int) bb.getX(), y + (int) bb.getY(), + (int) bb.getWidth(), (int) bb.getHeight()); + + if (verbose) { + if (counter == 1) { + printDetails(angle, tl); + } else if (i == 0) { + System.out.println("Paint, counter=" + counter); + } + } + } + } + + private static void printDetails(double angle, TextLayout tl) { + System.out.println("Angle: " + angle); + System.out.println("getAscent: " + tl.getAscent()); + System.out.println("getAdvance: " + tl.getAdvance()); + System.out.println("getBaseline: " + tl.getBaseline()); + System.out.println("getBounds: " + tl.getBounds()); + System.out.println("getDescent: " + tl.getDescent()); + System.out.println("getLeading: " + tl.getLeading()); + System.out.println("getVisibleAdvance: " + tl.getVisibleAdvance()); + System.out.println("."); + } + } + + private static final class SelectRotationAction + extends AbstractAction + implements PropertyChangeListener { + private final int rotation; + private final RotatedTextBounds rotatedText; + + private SelectRotationAction(int rotation, + RotatedTextBounds rotatedText) { + super(rotation * (360 / ROTATIONS) + "\u00B0"); + this.rotation = rotation; + this.rotatedText = rotatedText; + + putValue(SELECTED_KEY, true); + + addPropertyChangeListener(this); + } + + private void updateRotationVisible() { + rotatedText.setRotationVisible(rotation, + (Boolean) getValue(SELECTED_KEY)); + } + + @Override + public void actionPerformed(ActionEvent e) { + updateRotationVisible(); + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + if (evt.getPropertyName().equals(SELECTED_KEY)) { + updateRotationVisible(); + } + } + } + + private static void selectAllCheckBoxes(Component[] checkBoxes, + boolean visible) { + Arrays.stream(checkBoxes) + .forEach(c -> ((JCheckBox) c).setSelected(visible)); + } +} diff --git a/test/jdk/java/awt/font/TextLayout/TestControls.java b/test/jdk/java/awt/font/TextLayout/TestControls.java new file mode 100644 index 000000000000..ee15038a8459 --- /dev/null +++ b/test/jdk/java/awt/font/TextLayout/TestControls.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2001, 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.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Insets; +import java.awt.Panel; +import java.awt.ScrollPane; +import java.awt.font.FontRenderContext; +import java.awt.font.TextLayout; + +/* + * @test + * @bug 4517298 + * @summary Display special control characters using both TextLayout.draw and + * Graphics.drawString. In no case should a missing glyph appear. + * Also display the advance of the control characters, in all cases + * these should be 0. The space character is also displayed as a reference. + * Note, the character is rendered between '><' but owing to the directional + * properties of two of the characters, the second '<' is rendered as '>'. + * This is correct behavior. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestControls + */ + +public class TestControls { + private static String fontName = Font.DIALOG; + + public static void main(String[] args) throws Exception { + final String INSTRUCTIONS = """ + A number of control characters are displayed, one per line. + Each line displays the hex value of the character, the character + between '><' as rendered by TextLayout, the character between '><' + as rendered by drawString, and the advance of the character. + The first line renders the space character, as a reference. + The following lines all render the controls. + All controls should not render (even as space) and report a zero advance. + + Pass the test if this is true. + + Note: two of the control characters have the effect of changing the '<' + following the control character so that it renders as '>'. + This is not an error."""; + + PassFailJFrame.builder() + .title("TestControls Instruction") + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(TestControls::createUI) + .build() + .awaitAndCheck(); + } + + private static Frame createUI() { + Frame f = new Frame("TestControls Test UI"); + Panel panel = new ControlPanel(fontName); + ScrollPane sp = new ScrollPane(); + sp.add("Center", panel); + f.add(sp); + f.setSize(450, 400); + return f; + } + + static class ControlPanel extends Panel { + + static final char[] chars = { + (char)0x0020, (char)0x0009, + (char)0x000A, (char)0x000D, (char)0x200C, (char)0x200D, (char)0x200E, + (char)0x200F, (char)0x2028, (char)0x2029, (char)0x202A, (char)0x202B, + (char)0x202C, (char)0x202D, (char)0x202E, (char)0x206A, (char)0x206B, + (char)0x206C, (char)0x206D, (char)0x206E, (char)0x206F + }; + + ControlPanel(String fontName) { + Font font = new Font(fontName, Font.PLAIN, 24); + System.out.println("using font: " + font); + setFont(font); + setForeground(Color.BLACK); + setBackground(Color.WHITE); + } + + @Override + public Dimension getPreferredSize() { + return new Dimension(400, 750); + } + + @Override + public Dimension getMaximumSize() { + return getPreferredSize(); + } + + @Override + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D)g; + FontRenderContext frc = g2d.getFontRenderContext(); + Font font = g2d.getFont(); + FontMetrics fm = g2d.getFontMetrics(); + Insets insets = getInsets(); + + String jvmString = System.getProperty("java.version"); + String osString = System.getProperty("os.name") + " / " + + System.getProperty("os.arch") + " / " + + System.getProperty("os.version"); + + int x = insets.left + 10; + int y = insets.top; + + y += 30; + g2d.drawString("jvm: " + jvmString, x, y); + + y += 30; + g2d.drawString("os: " + osString, x, y); + + y += 30; + g2d.drawString("font: " + font.getFontName(), x, y); + + for (int i = 0; i < chars.length; ++i) { + String s = ">" + chars[i] + "<"; + x = insets.left + 10; + y += 30; + + g2d.drawString(Integer.toHexString(chars[i]), x, y); + x += 100; + + new TextLayout(s, font, frc).draw(g2d, x, y); + x += 100; + + g2d.drawString(s, x, y); + x += 100; + + g2d.drawString(Integer.toString(fm.charWidth(chars[i])), x, y); + } + } + } +} diff --git a/test/jdk/java/awt/font/TextLayout/TestGraphicOutline.java b/test/jdk/java/awt/font/TextLayout/TestGraphicOutline.java new file mode 100644 index 000000000000..42efd4185f4c --- /dev/null +++ b/test/jdk/java/awt/font/TextLayout/TestGraphicOutline.java @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2003, 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.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Shape; +import java.awt.font.FontRenderContext; +import java.awt.font.GraphicAttribute; +import java.awt.font.ShapeGraphicAttribute; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.awt.geom.Ellipse2D; +import java.awt.geom.Rectangle2D; +import java.text.AttributedCharacterIterator; +import java.text.AttributedString; + +import javax.swing.JPanel; + +/* + * @test + * @bug 4915565 4920820 4920952 + * @summary Display graphics (circles) embedded in text, and draw both the outline (top) + * and black box bounds (bottom) of the result. The circles should each display at a + * different height. The outline and frames should approximately (within a pixel + * or two) surround each character. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual TestGraphicOutline + */ + +public class TestGraphicOutline { + + public static void main(String[] args) throws Exception { + final String INSTRUCTIONS = """ + Display graphics (circles) embedded in text, and draw both the + outline (top) and black box bounds (bottom) of the result. + + The circles should each display at a different height. + The outline and frames should approximately (within a pixel or two) + surround each character. + + Pass the test if these conditions hold. + + 'Black box bounds' is a term that refers to the bounding rectangles + of each glyph, see the TextLayout API getBlackBoxBounds. It does not + mean that the rendered outlines in the test are supposed to be black. + The color of the outlines does not matter and is not part of the test + conditions. Since there is no API for embedded graphics to return an + outline that matches the shape of the graphics, the outlines of the + graphics are their visual bounding boxes, which are rectangles. + + This is not an error. These outlines, as stated, should surround each + character's graphic."""; + + PassFailJFrame.builder() + .title("TestGraphicOutline Instruction") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(TestGraphicsPanel::new) + .build() + .awaitAndCheck(); + } + + private static final class TestGraphicsPanel extends JPanel { + + TextLayout tl; + + public TestGraphicsPanel() { + setBackground(Color.white); + setPreferredSize(new Dimension(650, 300)); + setName("2D Text"); + } + + @Override + public void paint(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + int w = getSize().width; + int h = getSize().height; + + g2.setColor(getBackground()); + g2.fillRect(0, 0, w, h); + + Font f1 = new Font(Font.SANS_SERIF, Font.BOLD, 60); + Font f2 = new Font(Font.SERIF, Font.ITALIC, 80); + String str = "The Starry Night ok?"; + + AttributedString ats = new AttributedString(str); + + Shape s = new Ellipse2D.Float(0, -10, 12, 12); + GraphicAttribute iga1 = new ShapeGraphicAttribute(s, GraphicAttribute.TOP_ALIGNMENT, false); + GraphicAttribute iga2 = new ShapeGraphicAttribute(s, GraphicAttribute.HANGING_BASELINE, false); + GraphicAttribute iga3 = new ShapeGraphicAttribute(s, GraphicAttribute.CENTER_BASELINE, false); + GraphicAttribute iga4 = new ShapeGraphicAttribute(s, GraphicAttribute.ROMAN_BASELINE, false); + GraphicAttribute iga5 = new ShapeGraphicAttribute(s, GraphicAttribute.BOTTOM_ALIGNMENT, false); + + ats.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga1, 1, 2); + ats.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga2, 3, 4); + ats.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga3, 7, 8); + ats.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga4, 10, 11); + ats.addAttribute(TextAttribute.CHAR_REPLACEMENT, iga5, 14, 15); + ats.addAttribute(TextAttribute.FONT, f1, 0, 20); + ats.addAttribute(TextAttribute.FONT, f2, 4, 10); + AttributedCharacterIterator iter = ats.getIterator(); + + FontRenderContext frc = g2.getFontRenderContext(); + tl = new TextLayout(iter, frc); + Rectangle2D bounds = tl.getBounds(); + float sw = (float) bounds.getWidth(); + float sh = (float) bounds.getHeight(); + + g2.translate((w - sw) / 2f, h / 2f - sh + tl.getAscent() - 2); + + g2.setColor(Color.blue); + tl.draw(g2, 0, 0); + g2.draw(bounds); + + g2.setColor(Color.black); + Shape shape = tl.getOutline(null); + g2.draw(shape); + + g2.translate(0, sh + 5); + + g2.setColor(Color.blue); + tl.draw(g2, 0, 0); + g2.draw(bounds); + + g2.setColor(Color.red); + shape = tl.getBlackBoxBounds(0, tl.getCharacterCount()); + g2.draw(shape); + } + } +} diff --git a/test/jdk/java/awt/print/PrinterJob/ImagePrinting/BitmaskImage.java b/test/jdk/java/awt/print/PrinterJob/ImagePrinting/BitmaskImage.java new file mode 100644 index 000000000000..f6a19fb20703 --- /dev/null +++ b/test/jdk/java/awt/print/PrinterJob/ImagePrinting/BitmaskImage.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2006, 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 6444688 + * @key printer + * @summary Print an image with an IndexedColorModel with transparent pixel. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual BitmaskImage + */ + +import java.awt.Button; +import java.awt.Color; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.geom.AffineTransform; +import java.awt.image.BufferedImage; +import java.awt.image.DataBuffer; +import java.awt.image.IndexColorModel; +import java.awt.print.PageFormat; +import java.awt.print.PrinterJob; +import java.awt.print.Printable; +import java.awt.print.PrinterException; + +import static java.awt.print.Printable.NO_SUCH_PAGE; +import static java.awt.print.Printable.PAGE_EXISTS; + +public class BitmaskImage implements Printable, ActionListener { + + static int sz = 1000; + BufferedImage bi; + + public BitmaskImage() { + int i = 0; + int[] cmap = new int[256]; + for (int r = 0; r < 256; r += 51) { + for (int g = 0; g < 256; g += 51) { + for (int b = 0; b < 256; b += 51) { + cmap[i++] = (0xff << 24) | (r << 16) | (g << 8) | b; + } + } + } + + IndexColorModel icm = new + IndexColorModel(8, 256, cmap, 0, true, 253, DataBuffer.TYPE_BYTE); + bi = new BufferedImage(sz, sz, BufferedImage.TYPE_BYTE_INDEXED, icm); + Graphics g = bi.getGraphics(); + Graphics2D g2d = (Graphics2D)g; + g.setColor(Color.white); + g.fillRect(0, 0, sz, sz); + g.setColor(Color.black); + int off = sz / 20; + int wh = sz / 10; + for (int x = off; x < sz; x += wh * 2) { + for (int y = off; y < sz; y += wh * 2) { + g.fillRect(x, y, wh, wh); + } + } + } + + public int print(Graphics g, PageFormat pf, int page) throws + PrinterException { + + if (page > 0) { /* We have only one page, and 'page' is zero-based */ + return NO_SUCH_PAGE; + } + + Graphics2D g2d = (Graphics2D)g; + AffineTransform tx = g2d.getTransform(); + double sx = tx.getScaleX(); + double sy = tx.getScaleY(); + g2d.translate(pf.getImageableX(), pf.getImageableY()); + g2d.scale(1/sx, 1/sx); + g.drawImage(bi, 10, 10, null); + + /* tell the caller that this page is part of the printed document */ + return PAGE_EXISTS; + } + + public void actionPerformed(ActionEvent e) { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(this); + boolean ok = job.printDialog(); + if (ok) { + try { + job.print(); + } catch (PrinterException ex) { + /* The job did not successfully complete */ + } + } + System.out.println("done"); + } + + static String INSTRUCTIONS = """ + Press the "Print Simple ICM Image" button and if a printer is available, + choose one in the dialog and click OK to start printing. + This test will print an image which contains a grid of black squares. + If it prints so, press Pass otherwise press Fail."""; + + public static Frame initTest() { + Frame f = new Frame("Image Printer"); + Button printButton = new Button("Print Simple ICM image..."); + printButton.addActionListener(new BitmaskImage()); + f.add(printButton); + f.pack(); + return f; + } + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .testUI(BitmaskImage::initTest) + .columns(35) + .build() + .awaitAndCheck(); + } +} diff --git a/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java b/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java index eea118733de4..ed02c64b48eb 100644 --- a/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java +++ b/test/jdk/java/awt/print/PrinterJob/PageDialogTest.java @@ -22,11 +22,12 @@ */ /* - @test - @bug 6302514 - @key printer - @run main/manual PageDialogTest - @summary A toolkit modal dialog should not be blocked by Page/Print dialog. + * @test + * @bug 6302514 + * @key printer + * @requires (os.family != "mac") + * @run main/manual PageDialogTest + * @summary A toolkit modal dialog should not be blocked by Page/Print dialog. */ import java.awt.BorderLayout; diff --git a/test/jdk/java/awt/print/PrinterJob/PageRanges.java b/test/jdk/java/awt/print/PrinterJob/PageRanges.java index accde99ae956..c5d05cbce354 100644 --- a/test/jdk/java/awt/print/PrinterJob/PageRanges.java +++ b/test/jdk/java/awt/print/PrinterJob/PageRanges.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 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,58 +21,63 @@ * questions. */ -/** +/* * @test - * @bug 6575331 + * @bug 6575331 8297191 8373239 8378417 * @key printer * @summary The specified pages should be printed. - * @run main/manual=yesno PageRanges + * @library /java/awt/regtesthelpers + * @library /test/lib + * @build PassFailJFrame + * @build jtreg.SkippedException + * @run main/manual PageRanges */ -import java.awt.*; -import java.awt.print.*; +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 jtreg.SkippedException; public class PageRanges implements Printable { - - static String[] instr = { - "This test prints two jobs, and tests that the specified range", - "of pages is printed. You must have a printer installed for this test.", - "In the first dialog, select a page range of 2 to 3, and press OK", - "In the second dialog, select ALL, to print all pages (in total 5 pages).", - "Collect the two print outs and confirm the jobs printed correctly", - }; + private static final String INSTRUCTIONS = """ + This test prints two jobs and tests that the specified range + of pages is printed. + In the first dialog, select a page range of 2 to 3, and press OK. + In the second dialog, select ALL, to print all pages (in total 5 pages). + Collect the two print outs and confirm the jobs are printed correctly. + """; public static void main(String args[]) throws Exception { - for (int i=0;i= 5) { return NO_SUCH_PAGE; } g.drawString("Page : " + (pi+1), 200, 200); - return PAGE_EXISTS; } } diff --git a/test/jdk/java/awt/print/PrinterJob/PageRangesAuto.java b/test/jdk/java/awt/print/PrinterJob/PageRangesAuto.java new file mode 100644 index 000000000000..8d50ef9c2c22 --- /dev/null +++ b/test/jdk/java/awt/print/PrinterJob/PageRangesAuto.java @@ -0,0 +1,199 @@ +/* + * Copyright (c) 2007, 2026, Oracle and/or its affiliates. All rights reserved. + * 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.Font; +import java.awt.Graphics; +import java.awt.print.PageFormat; +import java.awt.print.Pageable; +import java.awt.print.Printable; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.BitSet; +import java.util.List; +import java.util.stream.IntStream; + +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.print.attribute.PrintRequestAttributeSet; +import javax.print.attribute.standard.Destination; +import javax.print.attribute.standard.PageRanges; + +/* + * @test + * @bug 6575331 8297191 + * @key printer + * @summary Automatically verifies all the pages in a range are printed + * @run main PageRangesAuto + */ +public class PageRangesAuto implements Pageable, Printable { + + private static final Font font = new Font(Font.SERIF, Font.PLAIN, 50); + + private static final int MAX_PAGE = 10; + + private static final int[][] ranges = { + {1, 1}, + {1, MAX_PAGE}, + {2, 3}, + {3, 6}, + {4, 7}, + {7, 7}, + {9, MAX_PAGE}, + {MAX_PAGE, MAX_PAGE}, + }; + + private enum Type { + PRINTABLE, + PAGEABLE + } + + private final BitSet printedPages = new BitSet(); + + /** + * Configures a printer job and prints it. + * @param type the type of the interface tested + * ({@code Printable} or {@code Pageable}) + * @param pageRange the range of pages to print; + * if {@code null}, print all pages + * @return a bit set of printed page numbers + */ + private static BitSet printJob(final Type type, + final PageRanges pageRange) + throws PrinterException { + final PageRangesAuto test = new PageRangesAuto(); + + final PrinterJob job = PrinterJob.getPrinterJob(); + final String baseName = type.name().toLowerCase(); + + switch (type) { + case PRINTABLE -> job.setPrintable(test); + case PAGEABLE -> job.setPageable(test); + } + + String fileName = pageRange == null + ? baseName + "-all.pdf" + : String.format("%s-%d-%d.pdf", + baseName, + pageRange.getMembers()[0][0], + pageRange.getMembers()[0][1]); + + PrintRequestAttributeSet set = new HashPrintRequestAttributeSet(); + set.add(new Destination(new File(fileName) + .toURI())); + if (pageRange != null) { + set.add(pageRange); + } + + job.print(set); + + return test.printedPages; + } + + public static void main(String[] args) throws Exception { + final List errors = new ArrayList<>(); + + for (Type type : Type.values()) { + BitSet pages; // Printed pages + + // Print all pages + System.out.println(type + " - all pages"); + pages = printJob(type, null); + if (!IntStream.range(0, MAX_PAGE) + .allMatch(pages::get)) { + errors.add(new Error("Not all pages printed in " + type + ": " + + pages)); + } + + // Print page range + for (int[] range : ranges) { + System.out.println(type + " - " + Arrays.toString(range)); + pages = printJob(type, new PageRanges(range[0], range[1])); + if (!IntStream.range(range[0] - 1, range[1]) + .allMatch(pages::get)) { + errors.add(new Error("Not all pages printed in " + type + + " within the range " + + Arrays.toString(range) + + ": " + pages)); + } + } + } + + if (!errors.isEmpty()) { + errors.forEach(System.err::println); + throw new RuntimeException("Errors detected: " + errors.size() + + ". - " + errors.getFirst()); + } + } + + @Override + public int print(Graphics g, PageFormat format, int pageIndex) + throws PrinterException { + printedPages.set(pageIndex); + + final int pageNo = pageIndex + 1; + System.out.println(" test.printPage " + pageNo); + if (pageIndex >= MAX_PAGE) { + return NO_SUCH_PAGE; + } + + g.setFont(font); + g.drawString("Page: " + pageNo, + 100, 150); + + return PAGE_EXISTS; + } + + @Override + public int getNumberOfPages() { + System.out.println(" test.getNumberOfPages = " + MAX_PAGE); + return MAX_PAGE; + } + + @Override + public PageFormat getPageFormat(int pageIndex) + throws IndexOutOfBoundsException { + checkPageIndex(pageIndex); + return new PageFormat(); + } + + @Override + public Printable getPrintable(int pageIndex) + throws IndexOutOfBoundsException { + checkPageIndex(pageIndex); + System.out.println(" test.getPrintable(" + (pageIndex + 1) + ")"); + return this; + } + + private static void checkPageIndex(int pageIndex) + throws IndexOutOfBoundsException { + if (pageIndex < 0) { + throw new IndexOutOfBoundsException("pageIndex < 0"); + } + + if (pageIndex >= MAX_PAGE) { + throw new IndexOutOfBoundsException("pageIndex >= " + MAX_PAGE); + } + } +} diff --git a/test/jdk/java/awt/print/PrinterJob/PolylinePrintingTest.java b/test/jdk/java/awt/print/PrinterJob/PolylinePrintingTest.java index 7d8568c01f98..c9dcdfdd450f 100644 --- a/test/jdk/java/awt/print/PrinterJob/PolylinePrintingTest.java +++ b/test/jdk/java/awt/print/PrinterJob/PolylinePrintingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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,31 +21,56 @@ * questions. */ -/** +/* + * @test * @bug 8041902 * @key printer * @summary Test printing of wide poly lines. - * @run main/manual=yesno PolylinePrintingTest + * @library /java/awt/regtesthelpers + * @library /test/lib + * @build PassFailJFrame + * @build jtreg.SkippedException + * @run main/manual PolylinePrintingTest */ -import java.awt.Dialog; -import java.awt.Frame; -import java.awt.TextArea; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Path2D; 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 jtreg.SkippedException; public class PolylinePrintingTest implements Printable { + private static final String INSTRUCTIONS = """ + Press OK in the print dialog and collect the printed page. + Passing test : Output should show two identical chevrons. + Failing test : The line joins will appear different. + """; + + public static void main(String[] args) throws Exception { + PrinterJob job = PrinterJob.getPrinterJob(); + if (job.getPrintService() == null) { + throw new SkippedException("Printer not configured or available."); + } + + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(45) + .build(); + + job.setPrintable(new PolylinePrintingTest()); + if (job.printDialog()) { + job.print(); + } + + passFailJFrame.awaitAndCheck(); + } public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { - if (pageIndex > 0) { return NO_SUCH_PAGE; } @@ -66,7 +91,6 @@ public int print(Graphics graphics, PageFormat pageFormat, private void drawPolylineGOOD(Graphics2D g2d, int[] x2Points, int[] y2Points) { - Path2D polyline = new Path2D.Float(Path2D.WIND_EVEN_ODD, x2Points.length); @@ -83,141 +107,4 @@ private void drawPolylineBAD(Graphics2D g, int[] xp, int[] yp) { g.translate(0, offset); g.drawPolyline(xp, yp, xp.length); } - - public PolylinePrintingTest() throws PrinterException { - 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(this, pf); - if (job.printDialog()) { - job.print(); - } - } - - public static void main(String[] args) throws PrinterException { - String[] instructions = { - "You must have a printer available to perform this test.", - "OK the print dialog, and collect the printed page.", - "Passing test : Output should show two identical chevrons.", - "Failing test : The line joins will appear different." - }; - Sysout.createDialog(); - Sysout.printInstructions(instructions); - new PolylinePrintingTest(); - } } - -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 --git a/test/jdk/java/awt/print/PrinterJob/SwingUIText.java b/test/jdk/java/awt/print/PrinterJob/SwingUIText.java index 5fcd5e391581..6ef5064fc306 100644 --- a/test/jdk/java/awt/print/PrinterJob/SwingUIText.java +++ b/test/jdk/java/awt/print/PrinterJob/SwingUIText.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 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,44 +21,70 @@ * questions. */ -/** +/* * @test * @bug 6488219 6560738 7158350 8017469 * @key printer * @summary Test that text printed in Swing UI measures and looks OK. - * @run main/manual=yesno PrintTextTest + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame jtreg.SkippedException + * @run main/manual SwingUIText */ -import java.awt.*; -import javax.swing.*; -import java.awt.print.*; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GridLayout; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import java.awt.print.PrinterJob; +import javax.swing.JButton; +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import jtreg.SkippedException; public class SwingUIText implements Printable { + private static JFrame frame; + private static final String INSTRUCTIONS = """ + This test checks that when a Swing UI is printed, + the text in each component aligns with the component’s length as seen on-screen. + It also ensures the text spacing is reasonably even, though this is subjective. + The comparison should be made with JDK 1.5 GA or JDK 1.6 GA. + + Steps: + 1. Press the "Print" or "OK" button on the Print dialog. + This will print the content of the "Swing UI Text Printing Test" JFrame. + 2. Compare the printout with the content of the JFrame. + 3. If they match, press Pass; otherwise, press Fail. + """; + + public static void main(String args[]) throws Exception { + PrinterJob job = PrinterJob.getPrinterJob(); + if (job.getPrintService() == null) { + throw new SkippedException("Printer not configured or available."); + } - static String[] instructions = { - "This tests that when a Swing UI is printed, that the text", - "in each component properly matches the length of the component", - "as seen on-screen, and that the spacing of the text is of", - "reasonable even-ness. This latter part is very subjective and", - "the comparison has to be with JDK1.5 GA, or JDK 1.6 GA", - }; + PassFailJFrame passFailJFrame = PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(45) + .testUI(SwingUIText::createTestUI) + .build(); - static JFrame frame; + job.setPrintable(new SwingUIText()); + if (job.printDialog()) { + job.print(); + } - public static void main(String args[]) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - createUI(); - } - }); + passFailJFrame.awaitAndCheck(); } - public static void createUI() { - - Sysout.createDialogWithInstructions(instructions); - + public static JFrame createTestUI() { + frame = new JFrame(); JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(4,1)); + panel.setLayout(new GridLayout(4, 1)); String text = "marvelous suspicious solving"; displayText(panel, text); @@ -89,24 +115,12 @@ public static void createUI() { frame = new JFrame("Swing UI Text Printing Test"); frame.getContentPane().add(panel); frame.pack(); - frame.setVisible(true); - - PrinterJob job = PrinterJob.getPrinterJob(); - PageFormat pf = job.defaultPage(); - job.setPrintable(new SwingUIText(), pf); - if (job.printDialog()) { - try { job.print(); } - catch (Exception e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } + return frame; } - static void displayText(JPanel p, String text) { JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(2,1)); + panel.setLayout(new GridLayout(2, 1)); JPanel row = new JPanel(); Font font = new Font("Dialog", Font.PLAIN, 12); @@ -114,7 +128,7 @@ static void displayText(JPanel p, String text) { label.setFont(font); row.add(label); - JButton button = new JButton("Print "+text); + JButton button = new JButton("Print " + text); button.setMnemonic('P'); button.setFont(font); row.add(button); @@ -133,132 +147,14 @@ static void displayText(JPanel p, String text) { p.add(panel); } - public int print(Graphics g, PageFormat pf, int pageIndex) - throws PrinterException { - + public int print(Graphics g, PageFormat pf, int pageIndex) { if (pageIndex >= 1) { return Printable.NO_SUCH_PAGE; } + g.translate((int)pf.getImageableX(), (int)pf.getImageableY()); frame.printAll(g); - 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( "", 10, 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 --git a/test/jdk/java/io/FileDescriptor/Sharing.java b/test/jdk/java/io/FileDescriptor/Sharing.java index 24f4fb70b02b..e4ceb2d69065 100644 --- a/test/jdk/java/io/FileDescriptor/Sharing.java +++ b/test/jdk/java/io/FileDescriptor/Sharing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * 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,14 @@ * @run main/othervm Sharing */ -import java.io.*; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.Writer; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.concurrent.CountDownLatch; @@ -71,7 +78,7 @@ private static void TestFinalizer() throws Exception { // encourage gc System.gc(); // read from fis2 - when fis1 is gc'ed and finalizer is run, read will fail - System.out.print("."); + System.err.print("."); ret = fis2.read(); } } @@ -93,7 +100,7 @@ private static void TestFinalizer() throws Exception { * read from fis3 - when raf is gc'ed and finalizer is run, * fd should still be valid. */ - System.out.print("."); + System.err.print("."); ret = fis3.read(); } } finally { @@ -290,7 +297,7 @@ private static void TestCloseAll() throws Exception { FileInputStream fis = new FileInputStream(raf.getFD()); fis.close(); if (raf.getFD().valid()) { - throw new RuntimeException("FD should not be valid."); + throw new RuntimeException("FD should not be valid."); } // Test the suppressed exception handling - FileInputStream @@ -308,7 +315,7 @@ private static void TestCloseAll() throws Exception { ioe.printStackTrace(); if (ioe.getSuppressed().length != 2) { throw new RuntimeException("[FIS]Incorrect number of suppressed " + - "exceptions received : " + ioe.getSuppressed().length); + "exceptions received : " + ioe.getSuppressed().length); } } if (raf.getFD().valid()) { @@ -332,7 +339,7 @@ private static void TestCloseAll() throws Exception { ioe.printStackTrace(); if (ioe.getSuppressed().length != 2) { throw new RuntimeException("[FOS]Incorrect number of suppressed " + - "exceptions received : " + ioe.getSuppressed().length); + "exceptions received : " + ioe.getSuppressed().length); } } if (raf.getFD().valid()) { @@ -347,10 +354,8 @@ private static void TestCloseAll() throws Exception { * FileOutputStreams referencing the same native file descriptor. */ private static class OpenClose extends Thread { - private FileDescriptor fd = null; - private CountDownLatch done; - FileInputStream[] fisArray = new FileInputStream[numFiles]; - FileOutputStream[] fosArray = new FileOutputStream[numFiles]; + private final FileDescriptor fd; + private final CountDownLatch done; OpenClose(FileDescriptor filedescriptor, CountDownLatch done) { this.fd = filedescriptor; @@ -358,29 +363,32 @@ private static class OpenClose extends Thread { } public void run() { - try { - for(int i=0;i clazz, Object expectedXValue) throws Exception { @@ -93,7 +97,7 @@ public void testWithDifferentTypes(Class clazz, Object expectedXValue) Object obj = deserialize(bytes); out.println("deserialized: " + obj); Object actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); } // --- all together @@ -108,18 +112,18 @@ public void testWithAllTogether() throws Exception { R15 obj = (R15)deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.a, false); - assertEquals(obj.b, 0); - assertEquals(obj.c, 0); - assertEquals(obj.d, '\u0000'); - assertEquals(obj.e, 0); - assertEquals(obj.f, 0l); - assertEquals(obj.g, 0f); - assertEquals(obj.h, 0d); - assertEquals(obj.i, null); - assertEquals(obj.j, null); - assertEquals(obj.k, null); - assertEquals(obj.l, null); + assertEquals(false, obj.a); + assertEquals(0, obj.b); + assertEquals(0, obj.c); + assertEquals('\u0000', obj.d); + assertEquals(0, obj.e); + assertEquals(0l, obj.f); + assertEquals(0f, obj.g); + assertEquals(0d, obj.h); + assertEquals(null, obj.i); + assertEquals(null, obj.j); + assertEquals(null, obj.k); + assertEquals(null, obj.l); } // --- generic type @@ -133,8 +137,8 @@ public void testGenericType() throws Exception { R16 obj = (R16)deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.t, null); - assertEquals(obj.u, null); + assertEquals(null, obj.t); + assertEquals(null, obj.u); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java b/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java index 8b0a1ae625bc..2d3ec8ce4ecf 100644 --- a/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java +++ b/test/jdk/java/io/Serializable/records/BadCanonicalCtrTest.java @@ -28,7 +28,7 @@ * cannot be found during deserialization. * @library /test/lib * @modules java.base/jdk.internal.org.objectweb.asm - * @run testng BadCanonicalCtrTest + * @run junit BadCanonicalCtrTest */ import java.io.ByteArrayInputStream; @@ -44,20 +44,23 @@ import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.test.lib.compiler.InMemoryJavaCompiler; import jdk.test.lib.ByteCodeLoader; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static jdk.internal.org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static jdk.internal.org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import static jdk.internal.org.objectweb.asm.Opcodes.*; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Checks that an InvalidClassException is thrown when the canonical * constructor cannot be found during deserialization. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BadCanonicalCtrTest { // ClassLoader for creating instances of the records to test with. @@ -74,7 +77,7 @@ public class BadCanonicalCtrTest { * the initial bytecode for the record classes using javac, then removes or * modifies the generated canonical constructor. */ - @BeforeTest + @BeforeAll public void setup() { { byte[] byteCode = InMemoryJavaCompiler.compile("R1", @@ -131,7 +134,6 @@ Object newR3(long l) throws Exception { return c.getConstructor(long.class).newInstance(l); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() throws Exception { return new Object[][] { new Object[] { newR1() }, @@ -146,13 +148,14 @@ public Object[][] recordInstances() throws Exception { * Tests that InvalidClassException is thrown when no constructor is * present. */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void missingConstructorTest(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); byte[] bytes = serialize(objToSerialize); out.println("deserializing"); - InvalidClassException ice = expectThrows(ICE, () -> deserialize(bytes, missingCtrClassLoader)); + InvalidClassException ice = Assertions.assertThrows(ICE, () -> deserialize(bytes, missingCtrClassLoader)); out.println("caught expected ICE: " + ice); assertTrue(ice.getMessage().contains("record canonical constructor not found")); } @@ -162,13 +165,14 @@ public void missingConstructorTest(Object objToSerialize) throws Exception { * constructor is not present. ( a non-canonical constructor is * present ). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void nonCanonicalConstructorTest(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); byte[] bytes = serialize(objToSerialize); out.println("deserializing"); - InvalidClassException ice = expectThrows(ICE, () -> deserialize(bytes, nonCanonicalCtrClassLoader)); + InvalidClassException ice = Assertions.assertThrows(ICE, () -> deserialize(bytes, nonCanonicalCtrClassLoader)); out.println("caught expected ICE: " + ice); assertTrue(ice.getMessage().contains("record canonical constructor not found")); } diff --git a/test/jdk/java/io/Serializable/records/BadValues.java b/test/jdk/java/io/Serializable/records/BadValues.java index 4e3dbaa200f8..9d5e0c7be827 100644 --- a/test/jdk/java/io/Serializable/records/BadValues.java +++ b/test/jdk/java/io/Serializable/records/BadValues.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -24,7 +24,7 @@ /* * @test * @summary Basic test for ClassNotFoundException - * @run testng BadValues + * @run junit BadValues */ import java.io.ByteArrayInputStream; @@ -32,10 +32,11 @@ import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; /** * Not directly related to records but provokes surrounding code, and ensures @@ -73,7 +74,7 @@ static byte[] byteStreamFor(String className, long uid, byte flags) public void testNotFoundSer() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("XxYyZz", 0L, (byte)SC_SERIALIZABLE); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -81,7 +82,7 @@ public void testNotFoundSer() throws Exception { public void testNotFoundSerWr() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("XxYyZz", 0L, (byte)(SC_SERIALIZABLE | SC_WRITE_METHOD)); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -89,7 +90,7 @@ public void testNotFoundSerWr() throws Exception { public void testNotFoundExt() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("AaBbCc", 0L, (byte)SC_EXTERNALIZABLE); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } @@ -97,7 +98,7 @@ public void testNotFoundExt() throws Exception { public void testNotFoundExtWr() throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor("AaBbCc", 0L, (byte)(SC_SERIALIZABLE | SC_WRITE_METHOD)); - Throwable t = expectThrows(CNFE, () -> deserialize(bytes)); + Throwable t = assertThrows(CNFE, () -> deserialize(bytes)); out.println("caught expected CNFE: " + t); } diff --git a/test/jdk/java/io/Serializable/records/BasicRecordSer.java b/test/jdk/java/io/Serializable/records/BasicRecordSer.java index ee50f630351e..81e54b39c100 100644 --- a/test/jdk/java/io/Serializable/records/BasicRecordSer.java +++ b/test/jdk/java/io/Serializable/records/BasicRecordSer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Basic test that serializes and deserializes a number of records - * @run testng BasicRecordSer - * @run testng/othervm/java.security.policy=empty_security.policy BasicRecordSer + * @run junit BasicRecordSer + * @run junit/othervm/java.security.policy=empty_security.policy BasicRecordSer */ import java.io.ByteArrayInputStream; @@ -40,19 +40,24 @@ import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.String.format; import static java.lang.System.out; import static java.net.InetAddress.getLoopbackAddress; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; -import static org.testng.Assert.fail; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Basic test that serializes and deserializes a number of simple records. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BasicRecordSer { // a mix of a few record and non-record classes @@ -102,7 +107,6 @@ record Wobble (Foo foo) implements ThrowingExternalizable { } record Wubble (Wobble wobble, Wibble wibble, String s) implements ThrowingExternalizable { } - @DataProvider(name = "serializable") public Object[][] serializable() { Foo foo = new Foo(23); return new Object[][] { @@ -122,14 +126,20 @@ public Object[][] serializable() { } /** Tests serializing and deserializing a number of records. */ - @Test(dataProvider = "serializable") + @ParameterizedTest + @MethodSource("serializable") public void testSerializable(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + if (objToSerialize.getClass().isArray()) { + assertArrayEquals((Object[]) objDeserialized, (Object[]) objToSerialize); + assertArrayEquals((Object[]) objToSerialize, (Object[]) objDeserialized); + } else { + assertEquals(objDeserialized, objToSerialize); + assertEquals(objToSerialize, objDeserialized); + } } /** Tests serializing and deserializing of local records. */ @@ -155,8 +165,8 @@ public void testSerializableBackRefs() throws Exception { out.println("serializing : " + objToSerialize); Foo[] objDeserialized = (Foo[])serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objToSerialize, objDeserialized); for (Foo f : objDeserialized) assertTrue(objDeserialized[0] == f); @@ -172,8 +182,8 @@ public void testExternalizableBackRefs() throws Exception { out.println("serializing : " + objToSerialize); Wobble[] objDeserialized = (Wobble[])serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); - assertEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objDeserialized, objToSerialize); + Assertions.assertArrayEquals(objToSerialize, objDeserialized); for (Wobble w : objDeserialized) { assertTrue(objDeserialized[0] == w); @@ -193,7 +203,6 @@ static class A implements Serializable { final NotSer notSer = new NotSer(7); } - @DataProvider(name = "notSerializable") public Object[][] notSerializable() { return new Object[][] { new Object[] { new NotSerEmpty() }, @@ -210,11 +219,12 @@ public Object[][] notSerializable() { static final Class NSE = NotSerializableException.class; /** Tests that non-Serializable record objects throw NotSerializableException. */ - @Test(dataProvider = "notSerializable") + @ParameterizedTest + @MethodSource("notSerializable") public void testNotSerializable(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); - NotSerializableException expected = expectThrows(NSE, () -> serialize(objToSerialize)); + NotSerializableException expected = Assertions.assertThrows(NSE, () -> serialize(objToSerialize)); out.println("caught expected NSE:" + expected); } @@ -236,9 +246,9 @@ public void testCtrCalledOnlyOnce() throws Exception { out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); assertEquals(objDeserialized, objToSerialize); - assertEquals(e_ctrInvocationCount, 1); + assertEquals(objToSerialize, objDeserialized); + assertEquals(1, e_ctrInvocationCount); } // --- @@ -259,9 +269,9 @@ public void testCtrNotCalled() { var objToSerialize = new G(); g_ctrInvocationCount = 0; // reset out.println("serializing : " + objToSerialize); - NotSerializableException expected = expectThrows(NSE, () -> serialize(objToSerialize)); + NotSerializableException expected = Assertions.assertThrows(NSE, () -> serialize(objToSerialize)); out.println("caught expected NSE:" + expected); - assertEquals(g_ctrInvocationCount, 0); + assertEquals(0, g_ctrInvocationCount); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java b/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java index c9f2be0e18f8..293489d845ec 100644 --- a/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java +++ b/test/jdk/java/io/Serializable/records/ConstructorAccessTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -26,8 +26,8 @@ * @bug 8246774 * @summary Ensures that the serialization implementation can *always* access * the record constructor - * @run testng ConstructorAccessTest - * @run testng/othervm/java.security.policy=empty_security.policy ConstructorAccessTest + * @run junit ConstructorAccessTest + * @run junit/othervm/java.security.policy=empty_security.policy ConstructorAccessTest */ import java.io.ByteArrayInputStream; @@ -39,16 +39,19 @@ import java.io.ObjectOutputStream; import java.io.Externalizable; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /*implicit*/ record Aux1 (int x) implements Serializable { } /*implicit*/ record Aux2 (int x) implements Serializable { } +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ConstructorAccessTest { public record A (int x) implements Serializable { } @@ -76,7 +79,6 @@ protected static record F (long l) implements ThrowingExternalizable { } private record H (double d) implements ThrowingExternalizable { } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { new A(34) }, @@ -92,7 +94,8 @@ public Object[][] recordInstances() { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); diff --git a/test/jdk/java/io/Serializable/records/CycleTest.java b/test/jdk/java/io/Serializable/records/CycleTest.java index 9df703c3bc10..79db38707999 100644 --- a/test/jdk/java/io/Serializable/records/CycleTest.java +++ b/test/jdk/java/io/Serializable/records/CycleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Ensures basic behavior of cycles from record components - * @run testng CycleTest - * @run testng/othervm/java.security.policy=empty_security.policy CycleTest + * @run junit CycleTest + * @run junit/othervm/java.security.policy=empty_security.policy CycleTest */ import java.io.ByteArrayInputStream; @@ -35,10 +35,11 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class CycleTest { @@ -62,10 +63,10 @@ public void testCycle1() throws Exception { out.println("serializing : " + r); R deserializedObj = serializeDeserialize(r); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj.x(), 1); // sanity - assertEquals(deserializedObj.y(), 2); // sanity + assertEquals(1, deserializedObj.x()); // sanity + assertEquals(2, deserializedObj.y()); // sanity assertTrue(deserializedObj.c() instanceof C); // sanity - assertEquals(deserializedObj.c().obj, null); // cycle, expect null + assertEquals(null, deserializedObj.c().obj); // cycle, expect null } /** @@ -85,8 +86,8 @@ public void testCycle2() throws Exception { out.println("deserialized: " + deserializedObj); assertTrue(deserializedObj instanceof C); // sanity assertTrue(deserializedObj.obj != null); // expect non-null, r - assertEquals(((R)deserializedObj.obj).x(), 3); // sanity - assertEquals(((R)deserializedObj.obj).y(), 4); // sanity + assertEquals(3, ((R)deserializedObj.obj).x()); // sanity + assertEquals(4, ((R)deserializedObj.obj).y()); // sanity } record R2 (int x, int y, C c1, C c2) implements Serializable { } @@ -106,8 +107,8 @@ public void testCycle3() throws Exception { out.println("serializing : " + r); R2 deserializedObj = serializeDeserialize(r); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj.x(), 5); // sanity - assertEquals(deserializedObj.y(), 6); // sanity + assertEquals(5, deserializedObj.x()); // sanity + assertEquals(6, deserializedObj.y()); // sanity c1 = deserializedObj.c1(); c2 = deserializedObj.c2(); @@ -133,11 +134,11 @@ public void testCycle4() throws Exception { R3 deserializedObj = serializeDeserialize(r3); out.println("deserialized: " + deserializedObj); assertTrue(deserializedObj.r() != null); - assertEquals(deserializedObj.l(), 9); // sanity - assertEquals(deserializedObj.r().x(), 7); // sanity - assertEquals(deserializedObj.r().y(), 8); // sanity + assertEquals(9, deserializedObj.l()); // sanity + assertEquals(7, deserializedObj.r().x()); // sanity + assertEquals(8, deserializedObj.r().y()); // sanity assertTrue(deserializedObj.r().c() instanceof C); // sanity - assertEquals(deserializedObj.r().c().obj, null); // cycle, expect null + assertEquals(null, deserializedObj.r().c().obj); // cycle, expect null } // --- infra diff --git a/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java b/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java index d4101f9894b2..dc22b1def0a9 100644 --- a/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/DifferentStreamFieldsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -26,8 +26,8 @@ * @bug 8246774 * @summary Checks that the appropriate value is given to the canonical ctr * @library /test/lib - * @run testng DifferentStreamFieldsTest - * @run testng/othervm/java.security.policy=empty_security.policy DifferentStreamFieldsTest + * @run junit DifferentStreamFieldsTest + * @run junit/othervm/java.security.policy=empty_security.policy DifferentStreamFieldsTest */ import java.io.ByteArrayInputStream; @@ -39,14 +39,19 @@ import java.io.ObjectOutputStream; import java.io.Serializable; import jdk.test.lib.serial.SerialObjectBuilder; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Checks that the appropriate value is given to the canonical ctr. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DifferentStreamFieldsTest { record R01(boolean x) implements Serializable {} @@ -77,7 +82,6 @@ record R13(R12 x) implements Serializable {} record R14(R13[]x) implements Serializable {} - @DataProvider(name = "recordTypeAndExpectedValue") public Object[][] recordTypeAndExpectedValue() { return new Object[][]{ new Object[]{R01.class, false}, @@ -97,7 +101,8 @@ public Object[][] recordTypeAndExpectedValue() { }; } - @Test(dataProvider = "recordTypeAndExpectedValue") + @ParameterizedTest + @MethodSource("recordTypeAndExpectedValue") public void testWithDifferentTypes(Class clazz, Object expectedXValue) throws Exception { out.println("\n---"); @@ -109,7 +114,7 @@ public void testWithDifferentTypes(Class clazz, Object expectedXValue) Object obj = deserialize(bytes); out.println("deserialized: " + obj); Object actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); bytes = SerialObjectBuilder .newBuilder(clazz.getName()) @@ -119,7 +124,7 @@ public void testWithDifferentTypes(Class clazz, Object expectedXValue) obj = deserialize(bytes); out.println("deserialized: " + obj); actualXValue = clazz.getDeclaredMethod("x").invoke(obj); - assertEquals(actualXValue, expectedXValue); + assertEquals(expectedXValue, actualXValue); } // --- all together @@ -138,18 +143,18 @@ record R15(boolean a, byte b, short c, char d, int e, long f, float g, R15 obj = deserialize(bytes); out.println("deserialized: " + obj); - assertEquals(obj.a, false); - assertEquals(obj.b, 0); - assertEquals(obj.c, 0); - assertEquals(obj.d, '\u0000'); - assertEquals(obj.e, 0); - assertEquals(obj.f, 0l); - assertEquals(obj.g, 0f); - assertEquals(obj.h, 0d); - assertEquals(obj.i, null); - assertEquals(obj.j, null); - assertEquals(obj.k, null); - assertEquals(obj.l, null); + assertEquals(false, obj.a); + assertEquals(0, obj.b); + assertEquals(0, obj.c); + assertEquals('\u0000', obj.d); + assertEquals(0, obj.e); + assertEquals(0l, obj.f); + assertEquals(0f, obj.g); + assertEquals(0d, obj.h); + assertEquals(null, obj.i); + assertEquals(null, obj.j); + assertEquals(null, obj.k); + assertEquals(null, obj.l); } @Test @@ -167,9 +172,9 @@ record R(int x) implements Serializable {} .build(); var deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } { record R(int x, int y) implements Serializable {} @@ -177,7 +182,7 @@ record R(int x, int y) implements Serializable {} var r = new R(7, 8); byte[] OOSBytes = serialize(r); var deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -186,7 +191,7 @@ record R(int x, int y) implements Serializable {} .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -194,7 +199,7 @@ record R(int x, int y) implements Serializable {} .addPrimitiveField("x", int.class, 7) .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -204,12 +209,12 @@ record R(int x, int y) implements Serializable {} .addPrimitiveField("z", int.class, 9) // additional fields .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); r = new R(0, 0); OOSBytes = serialize(r); deser1 = deserialize(OOSBytes); - assertEquals(deser1, r); + assertEquals(r, deser1); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) @@ -217,13 +222,13 @@ record R(int x, int y) implements Serializable {} .addPrimitiveField("x", int.class, 0) .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(R.class.getName()) // no field values .build(); deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } } @@ -235,7 +240,7 @@ record Str(String part1, String part2) implements Serializable {} var r = new Str("Hello", "World!"); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(Str.class.getName()) @@ -244,7 +249,7 @@ record Str(String part1, String part2) implements Serializable {} .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); builderBytes = SerialObjectBuilder .newBuilder(Str.class.getName()) @@ -255,7 +260,7 @@ record Str(String part1, String part2) implements Serializable {} .build(); var deser3 = deserialize(builderBytes); - assertEquals(deser3, deser1); + assertEquals(deser1, deser3); } @Test @@ -265,8 +270,8 @@ public void testArrays() throws Exception { record IntArray(int[]ints, long[]longs) implements Serializable {} IntArray r = new IntArray(new int[]{5, 4, 3, 2, 1}, new long[]{9L}); IntArray deser1 = deserialize(serialize(r)); - assertEquals(deser1.ints(), r.ints()); - assertEquals(deser1.longs(), r.longs()); + Assertions.assertArrayEquals(r.ints(), deser1.ints()); + Assertions.assertArrayEquals(r.longs(), deser1.longs()); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntArray.class.getName()) @@ -275,14 +280,14 @@ record IntArray(int[]ints, long[]longs) implements Serializable {} .build(); IntArray deser2 = deserialize(builderBytes); - assertEquals(deser2.ints(), deser1.ints()); - assertEquals(deser2.longs(), deser1.longs()); + Assertions.assertArrayEquals(deser1.ints(), deser2.ints()); + Assertions.assertArrayEquals(deser1.longs(), deser2.longs()); } { record StrArray(String[]stringArray) implements Serializable {} StrArray r = new StrArray(new String[]{"foo", "bar"}); StrArray deser1 = deserialize(serialize(r)); - assertEquals(deser1.stringArray(), r.stringArray()); + Assertions.assertArrayEquals(r.stringArray(), deser1.stringArray()); byte[] builderBytes = SerialObjectBuilder .newBuilder(StrArray.class.getName()) @@ -290,7 +295,7 @@ record StrArray(String[]stringArray) implements Serializable {} .build(); StrArray deser2 = deserialize(builderBytes); - assertEquals(deser2.stringArray(), deser1.stringArray()); + Assertions.assertArrayEquals(deser1.stringArray(), deser2.stringArray()); } } @@ -303,7 +308,7 @@ record NumberHolder(Number n) implements Serializable {} var r = new NumberHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(NumberHolder.class.getName()) @@ -311,7 +316,7 @@ record NumberHolder(Number n) implements Serializable {} .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } { @@ -319,7 +324,7 @@ record IntegerHolder(Integer i) implements Serializable {} var r = new IntegerHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntegerHolder.class.getName()) @@ -327,7 +332,7 @@ record IntegerHolder(Integer i) implements Serializable {} .build(); var deser2 = deserialize(builderBytes); - assertEquals(deser2, deser1); + assertEquals(deser1, deser2); } } @@ -339,7 +344,7 @@ record StringHolder(String s) implements Serializable {} var r = new StringHolder("123"); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(StringHolder.class.getName()) @@ -363,7 +368,7 @@ record IntHolder(int i) implements Serializable {} var r = new IntHolder(123); var deser1 = deserialize(serialize(r)); - assertEquals(deser1, r); + assertEquals(r, deser1); byte[] builderBytes = SerialObjectBuilder .newBuilder(IntHolder.class.getName()) diff --git a/test/jdk/java/io/Serializable/records/ProhibitedMethods.java b/test/jdk/java/io/Serializable/records/ProhibitedMethods.java index 099008b4306e..7465c80e4533 100644 --- a/test/jdk/java/io/Serializable/records/ProhibitedMethods.java +++ b/test/jdk/java/io/Serializable/records/ProhibitedMethods.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -27,7 +27,7 @@ * @summary Basic tests for prohibited magic serialization methods * @library /test/lib * @modules java.base/jdk.internal.org.objectweb.asm - * @run testng ProhibitedMethods + * @run junit ProhibitedMethods */ import java.io.ByteArrayInputStream; @@ -51,23 +51,27 @@ import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.test.lib.compiler.InMemoryJavaCompiler; import jdk.test.lib.ByteCodeLoader; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static jdk.internal.org.objectweb.asm.ClassWriter.COMPUTE_FRAMES; import static jdk.internal.org.objectweb.asm.ClassWriter.COMPUTE_MAXS; import static jdk.internal.org.objectweb.asm.Opcodes.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; -import static org.testng.Assert.fail; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Checks that the various prohibited Serialization magic methods, and * Externalizable methods, are not invoked ( effectively ignored ) for * record objects. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ProhibitedMethods { public interface ThrowingExternalizable extends Externalizable { @@ -101,7 +105,7 @@ record Wubble (Wobble wobble, Wibble wibble, String s) implements ThrowingExtern * fail("readObjectNoData should not be invoked"); } * } */ - @BeforeTest + @BeforeAll public void setup() { { byte[] byteCode = InMemoryJavaCompiler.compile("Foo", @@ -166,7 +170,6 @@ Object newBaz(Object u, Object v) { } } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newFoo() }, @@ -178,7 +181,8 @@ public Object[][] recordInstances() { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); @@ -271,7 +275,8 @@ public void visitEnd() { MethodVisitor mv = cv.visitMethod(ACC_PRIVATE, WRITE_OBJECT_NAME, WRITE_OBJECT_DESC, null, null); mv.visitCode(); mv.visitLdcInsn(WRITE_OBJECT_NAME + " should not be invoked"); - mv.visitMethodInsn(INVOKESTATIC, "org/testng/Assert", "fail", "(Ljava/lang/String;)V", false); + mv.visitMethodInsn(INVOKESTATIC, "org/junit/jupiter/api/Assertions", "fail", + "(Ljava/lang/String;)Ljava/lang/Object;", false); mv.visitInsn(RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); @@ -332,38 +337,38 @@ public void wellFormedGeneratedClasses() throws Exception { Method m = obj.getClass().getDeclaredMethod("writeObject", ObjectOutputStream.class); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj, new ObjectOutputStream(OutputStream.nullOutputStream()))); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "writeObject should not be invoked"); + assertEquals("writeObject should not be invoked", assertionError.getMessage()); } { // readObject Method m = obj.getClass().getDeclaredMethod("readObject", ObjectInputStream.class); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj, new ObjectInputStream() { })); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "readObject should not be invoked"); + assertEquals("readObject should not be invoked", assertionError.getMessage()); } { // readObjectNoData Method m = obj.getClass().getDeclaredMethod("readObjectNoData"); assertTrue((m.getModifiers() & Modifier.PRIVATE) != 0); m.setAccessible(true); - ReflectiveOperationException t = expectThrows(ROE, () -> m.invoke(obj)); + ReflectiveOperationException t = Assertions.assertThrows(ROE, () -> m.invoke(obj)); Throwable assertionError = t.getCause(); out.println("caught expected AssertionError: " + assertionError); assertTrue(assertionError instanceof AssertionError, "Expected AssertionError, got:" + assertionError); - assertEquals(assertionError.getMessage(), "readObjectNoData should not be invoked"); + assertEquals("readObjectNoData should not be invoked", assertionError.getMessage()); } } } -} +} \ No newline at end of file diff --git a/test/jdk/java/io/Serializable/records/ReadResolveTest.java b/test/jdk/java/io/Serializable/records/ReadResolveTest.java index 725f2cb49eab..cb36e3821fea 100644 --- a/test/jdk/java/io/Serializable/records/ReadResolveTest.java +++ b/test/jdk/java/io/Serializable/records/ReadResolveTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Basic tests for readResolve - * @run testng ReadResolveTest - * @run testng/othervm/java.security.policy=empty_security.policy ReadResolveTest + * @run junit ReadResolveTest + * @run junit/othervm/java.security.policy=empty_security.policy ReadResolveTest */ import java.io.ByteArrayInputStream; @@ -36,15 +36,19 @@ import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.String.format; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests records being used as a serial proxy. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ReadResolveTest { static class C1 implements Serializable { @@ -95,7 +99,6 @@ private Object writeReplace() { } } - @DataProvider(name = "objectsToSerialize") public Object[][] objectsToSerialize() { return new Object[][] { new Object[] { new C1(3,4) }, @@ -104,13 +107,14 @@ public Object[][] objectsToSerialize() { }; } - @Test(dataProvider = "objectsToSerialize") + @ParameterizedTest + @MethodSource("objectsToSerialize") public void testSerialize(Object objectToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, objectToSerialize); + assertEquals(objectToSerialize, deserializedObj); } // -- null replacement @@ -129,7 +133,7 @@ public void testNull() throws Exception { out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, null); + assertEquals(null, deserializedObj); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/RecordClassTest.java b/test/jdk/java/io/Serializable/records/RecordClassTest.java index 6506f9f85e43..b6e35d13626e 100644 --- a/test/jdk/java/io/Serializable/records/RecordClassTest.java +++ b/test/jdk/java/io/Serializable/records/RecordClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Basic tests for serializing and deserializing record classes - * @run testng RecordClassTest - * @run testng/othervm/java.security.policy=empty_security.policy RecordClassTest + * @run junit RecordClassTest + * @run junit/othervm/java.security.policy=empty_security.policy RecordClassTest */ import java.io.ByteArrayInputStream; @@ -39,15 +39,18 @@ import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Serializes and deserializes record classes. Ensures that the SUID is 0. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class RecordClassTest { record Foo () implements Serializable { } @@ -75,7 +78,6 @@ record Wobble (long l) implements ThrowingExternalizable { } record Wubble (Wobble wobble, Wibble wibble, String s) implements ThrowingExternalizable { } - @DataProvider(name = "recordClasses") public Object[][] recordClasses() { return new Object[][] { new Object[] { Foo.class , 0L }, @@ -88,7 +90,8 @@ public Object[][] recordClasses() { } /** Tests that the serialized and deserialized instances are equal. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testClassSerialization(Class recordClass, long unused) throws Exception { @@ -96,21 +99,22 @@ public void testClassSerialization(Class recordClass, long unused) out.println("serializing : " + recordClass); var deserializedClass = serializeDeserialize(recordClass); out.println("deserialized: " + deserializedClass); - assertEquals(recordClass, deserializedClass); assertEquals(deserializedClass, recordClass); + assertEquals(recordClass, deserializedClass); } /** Tests that the SUID is always 0 unless explicitly declared. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testSerialVersionUID(Class recordClass, long expectedUID) { out.println("\n---"); ObjectStreamClass osc = ObjectStreamClass.lookup(recordClass); out.println("ObjectStreamClass::lookup : " + osc); - assertEquals(osc.getSerialVersionUID(), expectedUID); + assertEquals(expectedUID, osc.getSerialVersionUID()); osc = ObjectStreamClass.lookupAny(recordClass); out.println("ObjectStreamClass::lookupAny: " + osc); - assertEquals(osc.getSerialVersionUID(), expectedUID); + assertEquals(expectedUID, osc.getSerialVersionUID()); } // --- not Serializable @@ -121,7 +125,6 @@ record NotSerializable2(int x) { } record NotSerializable3(T t) { } - @DataProvider(name = "notSerRecordClasses") public Object[][] notSerRecordClasses() { return new Object[][] { new Object[] { NotSerializable1.class }, @@ -131,16 +134,17 @@ public Object[][] notSerRecordClasses() { } /** Tests that the generated SUID is always 0 for all non-Serializable record classes. */ - @Test(dataProvider = "notSerRecordClasses") + @ParameterizedTest + @MethodSource("notSerRecordClasses") public void testSerialVersionUIDNonSer(Class recordClass) { out.println("\n---"); ObjectStreamClass osc = ObjectStreamClass.lookup(recordClass); out.println("ObjectStreamClass::lookup : " + osc); - assertEquals(osc, null); + assertEquals(null, osc); osc = ObjectStreamClass.lookupAny(recordClass); out.println("ObjectStreamClass::lookupAny: " + osc); - assertEquals(osc.getSerialVersionUID(), 0L); + assertEquals(0L, osc.getSerialVersionUID()); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java b/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java index 0d88074bdbcc..13d81ee3c49e 100644 --- a/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/SerialPersistentFieldsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -27,7 +27,7 @@ * @summary Basic tests for prohibited magic serialPersistentFields * @library /test/lib * @modules java.base/jdk.internal.org.objectweb.asm - * @run testng SerialPersistentFieldsTest + * @run junit SerialPersistentFieldsTest */ import java.io.ByteArrayInputStream; @@ -49,18 +49,21 @@ import jdk.internal.org.objectweb.asm.Type; import jdk.test.lib.ByteCodeLoader; import jdk.test.lib.compiler.InMemoryJavaCompiler; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; import static jdk.internal.org.objectweb.asm.ClassWriter.*; import static jdk.internal.org.objectweb.asm.Opcodes.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Checks that the serialPersistentFields declaration is effectively ignored. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SerialPersistentFieldsTest { ClassLoader serializableRecordLoader; @@ -78,7 +81,7 @@ public class SerialPersistentFieldsTest { * }; * } */ - @BeforeTest + @BeforeAll public void setup() { { // R1 byte[] byteCode = InMemoryJavaCompiler.compile("R1", @@ -164,7 +167,6 @@ Object newR5(int x) { return newRecord("R5", new Class[]{int.class}, new Object[]{x}); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newR1() }, @@ -175,14 +177,15 @@ public Object[][] recordInstances() { }; } - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void roundTrip(Object objToSerialize) throws Exception { out.println("\n---"); out.println("serializing : " + objToSerialize); var objDeserialized = serializeDeserialize(objToSerialize); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize, objDeserialized); assertEquals(objDeserialized, objToSerialize); + assertEquals(objToSerialize, objDeserialized); } byte[] serialize(T obj) throws IOException { @@ -323,7 +326,8 @@ static String getPrimitiveBoxClass(final Class clazz) { // -- infra sanity -- /** Checks to ensure correct operation of the test's generation logic. */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void wellFormedGeneratedClasses(Object obj) throws Exception { out.println("\n---"); out.println(obj); @@ -336,4 +340,4 @@ public void wellFormedGeneratedClasses(Object obj) throws Exception { assertTrue(fv != null, "Unexpected null value"); assertTrue(fv.length >= 0, "Unexpected negative length:" + fv.length); } -} +} \ No newline at end of file diff --git a/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java b/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java index d1018c125542..ae0c3b9af14c 100644 --- a/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java +++ b/test/jdk/java/io/Serializable/records/SerialVersionUIDTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Basic tests for SUID in the serial stream - * @run testng SerialVersionUIDTest - * @run testng/othervm/java.security.policy=empty_security.policy SerialVersionUIDTest + * @run junit SerialVersionUIDTest + * @run junit/othervm/java.security.policy=empty_security.policy SerialVersionUIDTest */ import java.io.ByteArrayInputStream; @@ -40,13 +40,16 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.LongStream; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SerialVersionUIDTest { record R1 () implements Serializable { @@ -65,7 +68,6 @@ record R5 (long l) implements Serializable { private static final long serialVersionUID = 5678L; } - @DataProvider(name = "recordObjects") public Object[][] recordObjects() { return new Object[][] { new Object[] { new R1(), 1L }, @@ -79,7 +81,8 @@ public Object[][] recordObjects() { /** * Tests that a declared SUID for a record class is inserted into the stream. */ - @Test(dataProvider = "recordObjects") + @ParameterizedTest + @MethodSource("recordObjects") public void testSerialize(Object objectToSerialize, long expectedUID) throws Exception { @@ -91,17 +94,16 @@ public void testSerialize(Object objectToSerialize, long expectedUID) DataInputStream dis = new DataInputStream(bais); // sanity - assertEquals(dis.readShort(), STREAM_MAGIC); - assertEquals(dis.readShort(), STREAM_VERSION); - assertEquals(dis.readByte(), TC_OBJECT); - assertEquals(dis.readByte(), TC_CLASSDESC); - assertEquals(dis.readUTF(), objectToSerialize.getClass().getName()); + assertEquals(STREAM_MAGIC, dis.readShort()); + assertEquals(STREAM_VERSION, dis.readShort()); + assertEquals(TC_OBJECT, dis.readByte()); + assertEquals(TC_CLASSDESC, dis.readByte()); + assertEquals(objectToSerialize.getClass().getName(), dis.readUTF()); // verify that the UID is as expected - assertEquals(dis.readLong(), expectedUID); + assertEquals(expectedUID, dis.readLong()); } - @DataProvider(name = "recordClasses") public Object[][] recordClasses() { List list = new ArrayList<>(); List> recordClasses = List.of(R1.class, R2.class, R3.class, R4.class, R5.class); @@ -116,14 +118,15 @@ public Object[][] recordClasses() { * Tests that matching of the serialVersionUID values ( stream value * and runtime class value ) is waived for record classes. */ - @Test(dataProvider = "recordClasses") + @ParameterizedTest + @MethodSource("recordClasses") public void testSerializeFromClass(Class cl, long suid) throws Exception { out.println("\n---"); byte[] bytes = byteStreamFor(cl.getName(), suid); Object obj = deserialize(bytes); - assertEquals(obj.getClass(), cl); + assertEquals(cl, obj.getClass()); assertTrue(obj.getClass().isRecord()); } diff --git a/test/jdk/java/io/Serializable/records/StreamRefTest.java b/test/jdk/java/io/Serializable/records/StreamRefTest.java index b0c72ec8a966..d0d3e353bdb5 100644 --- a/test/jdk/java/io/Serializable/records/StreamRefTest.java +++ b/test/jdk/java/io/Serializable/records/StreamRefTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,7 +25,7 @@ * @test * @bug 8246774 * @summary Tests for stream references - * @run testng StreamRefTest + * @run junit StreamRefTest */ import java.io.ByteArrayInputStream; @@ -36,11 +36,12 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * Tests for stream references. @@ -123,14 +124,14 @@ public void basicRefWithInvalidA() throws Exception { updateIntValue(3, -3, bytes, 40); var byteStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - InvalidObjectException ioe = expectThrows(IOE, () -> deserializeOne(byteStream)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t instanceof IllegalArgumentException, "Expected IAE, got:" + t); out.println("expected cause IAE: " + t); B b1 = (B)deserializeOne(byteStream); - assertEquals(b1.a, null); + assertEquals(null, b1.a); } @Test @@ -144,14 +145,14 @@ public void reverseBasicRefWithInvalidA() throws Exception { updateIntValue(3, -3, bytes, 96); var byteStream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - InvalidObjectException ioe = expectThrows(IOE, () -> deserializeOne(byteStream)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t instanceof IllegalArgumentException, "Expected IAE, got:" + t); out.println("expected cause IAE: " + t); A a1 = (A)deserializeOne(byteStream); - assertEquals(a1, null); + assertEquals(null, a1); } // --- @@ -211,7 +212,7 @@ static void assertExpectedIntValue(int expectedValue, byte[] bytes, int offset) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(bytes, offset, 4); DataInputStream dis = new DataInputStream(bais); - assertEquals(dis.readInt(), expectedValue); + assertEquals(expectedValue, dis.readInt()); } static void updateIntValue(int expectedValue, int newValue, byte[] bytes, int offset) diff --git a/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java b/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java index feb148f5d5ce..247837bb963c 100644 --- a/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java +++ b/test/jdk/java/io/Serializable/records/ThrowingConstructorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Tests constructor invocation exceptions are handled appropriately - * @run testng ThrowingConstructorTest - * @run testng/othervm/java.security.policy=empty_security.policy ThrowingConstructorTest + * @run junit ThrowingConstructorTest + * @run junit/othervm/java.security.policy=empty_security.policy ThrowingConstructorTest */ import java.io.ByteArrayInputStream; @@ -36,17 +36,20 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * If the constructor invocation throws an exception, an * `InvalidObjectException` is thrown with that exception as its cause. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ThrowingConstructorTest { /** "big switch" that can be used to allow/disallow record construction @@ -85,7 +88,6 @@ static class C implements Serializable { static final Class IOE = InvalidObjectException.class; - @DataProvider(name = "exceptionInstances") public Object[][] exceptionInstances() { Object[][] objs = new Object[][] { new Object[] { new R1(), NullPointerException.class, "thrown from R1" }, @@ -99,7 +101,8 @@ public Object[][] exceptionInstances() { return objs; } - @Test(dataProvider = "exceptionInstances") + @ParameterizedTest + @MethodSource("exceptionInstances") public void testExceptions(Object objectToSerialize, Class expectedExType, String expectedExMessage) @@ -108,13 +111,13 @@ public void testExceptions(Object objectToSerialize, out.println("\n---"); out.println("serializing: " + objectToSerialize); byte[] bytes = serialize(objectToSerialize); - InvalidObjectException ioe = expectThrows(IOE, () -> deserialize(bytes)); + InvalidObjectException ioe = Assertions.assertThrows(IOE, () -> deserialize(bytes)); out.println("caught expected IOE: " + ioe); Throwable t = ioe.getCause(); assertTrue(t.getClass().equals(expectedExType), "Expected:" + expectedExType + ", got:" + t); out.println("expected cause " + expectedExType +" : " + t); - assertEquals(t.getMessage(), expectedExMessage); + assertEquals(expectedExMessage, t.getMessage()); } // -- errors ( pass through unwrapped ) @@ -144,7 +147,6 @@ public R6(int x, int y) { } } - @DataProvider(name = "errorInstances") public Object[][] errorInstances() { Object[][] objs = new Object[][] { new Object[] { new R4(), OutOfMemoryError.class, "thrown from R4" }, @@ -158,7 +160,8 @@ public Object[][] errorInstances() { return objs; } - @Test(dataProvider = "errorInstances") + @ParameterizedTest + @MethodSource("errorInstances") public void testErrors(Object objectToSerialize, Class expectedExType, String expectedExMessage) @@ -167,11 +170,11 @@ public void testErrors(Object objectToSerialize, out.println("\n---"); out.println("serializing: " + objectToSerialize); byte[] bytes = serialize(objectToSerialize); - Throwable t = expectThrows(expectedExType, () -> deserialize(bytes)); + Throwable t = Assertions.assertThrows(expectedExType, () -> deserialize(bytes)); assertTrue(t.getClass().equals(expectedExType), "Expected:" + expectedExType + ", got:" + t); out.println("caught expected " + expectedExType +" : " + t); - assertEquals(t.getMessage(), expectedExMessage); + assertEquals(expectedExMessage, t.getMessage()); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/UnsharedTest.java b/test/jdk/java/io/Serializable/records/UnsharedTest.java index c96010c83ab9..114e2dc6e10d 100644 --- a/test/jdk/java/io/Serializable/records/UnsharedTest.java +++ b/test/jdk/java/io/Serializable/records/UnsharedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -25,7 +25,7 @@ * @test * @bug 8238763 8246774 * @summary ObjectInputStream readUnshared method handling of Records - * @run testng UnsharedTest + * @run junit UnsharedTest */ import java.io.ByteArrayInputStream; @@ -35,10 +35,11 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; +import org.junit.jupiter.api.Assertions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /** * Tests OOS::writeUnshared and OIS::readUnshared to verify that records @@ -56,16 +57,16 @@ public void testReadUnshared() throws Exception { { // shared - sanity to ensure the second foo is a ref var byteStream = serialize(foo, foo); var foo1 = (Foo) deserializeOne(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOne(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 == foo1); } { // unshared var byteStream = serialize(foo, foo); var foo1 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo1.x, foo.x); - var expected = expectThrows(IOE, () -> deserializeOne(byteStream)); + assertEquals(foo.x, foo1.x); + var expected = Assertions.assertThrows(IOE, () -> deserializeOne(byteStream)); assertTrue(expected.getMessage().contains("cannot read back reference to unshared object")); } } @@ -76,17 +77,17 @@ public void testWriteUnshared() throws Exception { { // shared - sanity to ensure the second foo is NOT a ref var byteStream = serializeUnshared(foo, foo); var foo1 = (Foo) deserializeOne(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOne(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 != foo1); } { // unshared var byteStream = serializeUnshared(foo, foo); var foo1 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo1.x, foo.x); + assertEquals(foo.x, foo1.x); var foo2 = (Foo) deserializeOneUnshared(byteStream); - assertEquals(foo2.x, foo.x); + assertEquals(foo.x, foo2.x); assertTrue(foo2 != foo1); } } diff --git a/test/jdk/java/io/Serializable/records/WriteReplaceTest.java b/test/jdk/java/io/Serializable/records/WriteReplaceTest.java index 8dda381e6713..1c3990078c21 100644 --- a/test/jdk/java/io/Serializable/records/WriteReplaceTest.java +++ b/test/jdk/java/io/Serializable/records/WriteReplaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,8 +25,8 @@ * @test * @bug 8246774 * @summary Basic tests for writeReplace - * @run testng WriteReplaceTest - * @run testng/othervm/java.security.policy=empty_security.policy WriteReplaceTest + * @run junit WriteReplaceTest + * @run junit/othervm/java.security.policy=empty_security.policy WriteReplaceTest */ import java.io.ByteArrayInputStream; @@ -35,11 +35,15 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class WriteReplaceTest { record R1 () implements Serializable { @@ -72,7 +76,6 @@ static class Replacement implements Serializable { } } - @DataProvider(name = "recordObjects") public Object[][] recordObjects() { return new Object[][] { new Object[] { new R1(), R1.class }, @@ -82,7 +85,8 @@ public Object[][] recordObjects() { }; } - @Test(dataProvider = "recordObjects") + @ParameterizedTest + @MethodSource("recordObjects") public void testSerialize(Object objectToSerialize, Class expectedType) throws Exception { @@ -91,9 +95,9 @@ public void testSerialize(Object objectToSerialize, Class expectedType) Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); if (objectToSerialize.getClass().equals(expectedType)) - assertEquals(deserializedObj, objectToSerialize); + assertEquals(objectToSerialize, deserializedObj); else - assertEquals(deserializedObj.getClass(), expectedType); + assertEquals(expectedType, deserializedObj.getClass()); } // -- null replacement @@ -109,7 +113,7 @@ public void testNull() throws Exception { out.println("serializing : " + objectToSerialize); Object deserializedObj = serializeDeserialize(objectToSerialize); out.println("deserialized: " + deserializedObj); - assertEquals(deserializedObj, null); + assertEquals(null, deserializedObj); } // --- infra diff --git a/test/jdk/java/io/Serializable/records/migration/AbstractTest.java b/test/jdk/java/io/Serializable/records/migration/AbstractTest.java index e0bbc5745005..488f4a33acda 100644 --- a/test/jdk/java/io/Serializable/records/migration/AbstractTest.java +++ b/test/jdk/java/io/Serializable/records/migration/AbstractTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -34,8 +34,9 @@ import java.net.URLClassLoader; import java.nio.file.Path; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; /** * An abstract superclass for tests that require to serialize and deserialize @@ -54,7 +55,7 @@ public class AbstractTest { static final Path RECORD_SRC_DIR = Path.of(TEST_SRC, "record"); static final Path RECORD_DEST_DIR = Path.of("record"); - @BeforeTest + @BeforeAll public void setup() throws IOException { assertTrue(CompilerUtils.compile(PLAIN_SRC_DIR, PLAIN_DEST_DIR, "--class-path", TEST_CLASSES_DIR.toString())); diff --git a/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java b/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java index 6097e2477df2..117a8474c678 100644 --- a/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java +++ b/test/jdk/java/io/Serializable/records/migration/AssignableFromTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -29,24 +29,26 @@ * @modules jdk.compiler * @compile AssignableFrom.java Point.java * DefaultValues.java SuperStreamFields.java - * @run testng AssignableFromTest + * @run junit AssignableFromTest */ import java.math.BigDecimal; import java.math.BigInteger; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Basic test to check that stream field values that are not the exact * declared param/field type, but assignable to a declared supertype, * are bound/assigned correctly. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class AssignableFromTest extends AbstractTest { - @DataProvider(name = "plainInstances") public Object[][] plainInstances() { return new Object[][] { new Object[] { newPlainAssignableFrom(Byte.valueOf((byte)11)) }, @@ -59,7 +61,8 @@ public Object[][] plainInstances() { } /** Serialize non-record (plain) instances, deserialize as a record. */ - @Test(dataProvider = "plainInstances") + @ParameterizedTest + @MethodSource("plainInstances") public void testPlainToRecord(AssignableFrom objToSerialize) throws Exception { assert !objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -68,13 +71,12 @@ public void testPlainToRecord(AssignableFrom objToSerialize) throws Exception { assert objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number(), objToSerialize.number()); + assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number().getClass(), objDeserialized.number().getClass()); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newRecordAssignableFrom(Byte.valueOf((byte)21)) }, @@ -87,7 +89,8 @@ public Object[][] recordInstances() { } /** Serialize record instances, deserialize as non-record (plain). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void testRecordToPlain(AssignableFrom objToSerialize) throws Exception { assert objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -96,8 +99,8 @@ public void testRecordToPlain(AssignableFrom objToSerialize) throws Exception { assert !objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number(), objToSerialize.number()); + assertEquals(objToSerialize.number(), objDeserialized.number()); assertEquals(objDeserialized.number().getClass(), objDeserialized.number().getClass()); } diff --git a/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java b/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java index 4af684156c65..357c94007777 100644 --- a/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java +++ b/test/jdk/java/io/Serializable/records/migration/DefaultValuesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -28,21 +28,24 @@ * @library /test/lib * @modules jdk.compiler * @compile AssignableFrom.java Point.java DefaultValues.java SuperStreamFields.java - * @run testng DefaultValuesTest + * @run junit DefaultValuesTest */ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; -import org.testng.annotations.Test; import static java.io.ObjectStreamConstants.*; import static java.lang.System.out; -import static org.testng.Assert.*; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; /** * Basic test to check that default primitive / reference values are * presented to the record's canonical constructor, for fields not in * the stream. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DefaultValuesTest extends AbstractTest { /** @@ -77,13 +80,13 @@ public void testPoint() throws Exception { Point point = deserializeAsPlain(bytes); out.println("deserialized: " + point); - assertEquals(point.x(), 0); - assertEquals(point.y(), 0); + assertEquals(0, point.x()); + assertEquals(0, point.y()); point = deserializeAsRecord(bytes); out.println("deserialized: " + point); - assertEquals(point.x(), 0); - assertEquals(point.y(), 0); + assertEquals(0, point.x()); + assertEquals(0, point.y()); } // --- @@ -115,8 +118,8 @@ public void testAllDefaults() throws Exception { DefaultValues o1 = deserializeAsRecord(bytes); out.println("deserialized: " + o1); - assertEquals(o1.point().x(), point.x()); // sanity - assertEquals(o1.point().y(), point.y()); // sanity + assertEquals(point.x(), o1.point().x()); // sanity + assertEquals(point.y(), o1.point().y()); // sanity assertTrue(o1.bool() == Defaults.bool); assertTrue(o1.by() == Defaults.by); assertTrue(o1.ch() == Defaults.ch); diff --git a/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java b/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java index 6090d71003e6..35e75341dbff 100644 --- a/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java +++ b/test/jdk/java/io/Serializable/records/migration/SuperStreamFieldsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -28,20 +28,23 @@ * @library /test/lib * @modules jdk.compiler * @compile AssignableFrom.java Point.java DefaultValues.java SuperStreamFields.java - * @run testng SuperStreamFieldsTest + * @run junit SuperStreamFieldsTest */ -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.System.out; -import static org.testng.Assert.assertEquals; + +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * Tests that superclass fields in the stream are discarded. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SuperStreamFieldsTest extends AbstractTest { - @DataProvider(name = "plainInstances") public Object[][] plainInstances() { return new Object[][] { new Object[] { newPlainSuperStreamFields("cat", new int[] { 1 }, 1) }, @@ -51,7 +54,8 @@ public Object[][] plainInstances() { } /** Serializes non-record (plain) instance, deserializes as a record. */ - @Test(dataProvider = "plainInstances") + @ParameterizedTest + @MethodSource("plainInstances") public void testPlainToRecord(SuperStreamFields objToSerialize) throws Exception { assert !objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -60,12 +64,11 @@ public void testPlainToRecord(SuperStreamFields objToSerialize) throws Exception assert objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.str(), objDeserialized.str()); - assertEquals(objToSerialize.x(), objDeserialized.x()); - assertEquals(objToSerialize.y(), objDeserialized.y()); + assertEquals(objDeserialized.str(), objToSerialize.str()); + Assertions.assertArrayEquals(objDeserialized.x(), objToSerialize.x()); + assertEquals(objDeserialized.y(), objToSerialize.y()); } - @DataProvider(name = "recordInstances") public Object[][] recordInstances() { return new Object[][] { new Object[] { newRecordSuperStreamFields("goat", new int[] { 56 }, 66) }, @@ -75,7 +78,8 @@ public Object[][] recordInstances() { } /** Serializes record instance, deserializes as non-record (plain). */ - @Test(dataProvider = "recordInstances") + @ParameterizedTest + @MethodSource("recordInstances") public void testRecordToPlain(SuperStreamFields objToSerialize) throws Exception { assert objToSerialize.getClass().isRecord(); out.println("serialize : " + objToSerialize); @@ -84,9 +88,9 @@ public void testRecordToPlain(SuperStreamFields objToSerialize) throws Exception assert !objDeserialized.getClass().isRecord(); out.println("deserialized: " + objDeserialized); - assertEquals(objToSerialize.str(), objDeserialized.str()); - assertEquals(objToSerialize.x(), objDeserialized.x()); - assertEquals(objToSerialize.y(), objDeserialized.y()); + assertEquals(objDeserialized.str(), objToSerialize.str()); + Assertions.assertArrayEquals(objDeserialized.x(), objToSerialize.x()); + assertEquals(objDeserialized.y(), objToSerialize.y()); } diff --git a/test/jdk/java/io/pathNames/GeneralSolaris.java b/test/jdk/java/io/pathNames/GeneralSolaris.java index 5b3c3d7f7ae4..6aae15b4468d 100644 --- a/test/jdk/java/io/pathNames/GeneralSolaris.java +++ b/test/jdk/java/io/pathNames/GeneralSolaris.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 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 @@ -24,6 +24,7 @@ /* @test @bug 4035924 4095767 @summary General exhaustive test of solaris pathname handling + @requires (os.family != "windows") @author Mark Reinhold @build General GeneralSolaris @@ -65,10 +66,6 @@ private static void checkPaths() throws Exception { } public static void main(String[] args) throws Exception { - if (File.separatorChar != '/') { - /* This test is only valid on Unix systems */ - return; - } if (args.length > 0) debug = true; initTestData(3); diff --git a/test/jdk/java/io/pathNames/GeneralWin32.java b/test/jdk/java/io/pathNames/GeneralWin32.java index 6ee64fd86f0e..e7594816680a 100644 --- a/test/jdk/java/io/pathNames/GeneralWin32.java +++ b/test/jdk/java/io/pathNames/GeneralWin32.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -24,6 +24,7 @@ /* @test @bug 4032066 4039597 4046914 4054511 4065189 4109131 4875229 6983520 8009258 @summary General exhaustive test of win32 pathname handling + @requires (os.family == "windows") @author Mark Reinhold @build General GeneralWin32 @@ -162,10 +163,6 @@ private static void checkUncPaths(int depth) throws Exception { public static void main(String[] args) throws Exception { - if (File.separatorChar != '\\') { - /* This test is only valid on win32 systems */ - return; - } if (args.length > 0) debug = true; initTestData(3); diff --git a/test/jdk/java/io/pathNames/unix/TrailingSlash.java b/test/jdk/java/io/pathNames/unix/TrailingSlash.java index b787cd0ef9d0..bfab177b2cfd 100644 --- a/test/jdk/java/io/pathNames/unix/TrailingSlash.java +++ b/test/jdk/java/io/pathNames/unix/TrailingSlash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -24,6 +24,7 @@ /* @test * @bug 4427862 * @summary Ensure that trailing slashes are ignored when opening files + * @requires (os.family != "windows") */ import java.io.*; @@ -107,11 +108,6 @@ static void go(String fn, String fns) throws Exception { } public static void main(String[] args) throws Exception { - if (File.separatorChar != '/') { - // This test is only valid on Unix systems - return; - } - go("xyzzy", "xyzzy"); go("xyzzy", "xyzzy/"); go("xyzzy", "xyzzy//"); diff --git a/test/jdk/java/io/pathNames/win32/DriveOnly.java b/test/jdk/java/io/pathNames/win32/DriveOnly.java index 4281200f0c7d..96aba22a408c 100644 --- a/test/jdk/java/io/pathNames/win32/DriveOnly.java +++ b/test/jdk/java/io/pathNames/win32/DriveOnly.java @@ -24,6 +24,7 @@ /* @test @bug 4096648 @summary Make sure that isDirectory and lastModified work on "x:" + @requires (os.family == "windows") */ import java.io.File; @@ -32,7 +33,6 @@ public class DriveOnly { public static void main(String[] args) throws Exception { - if (File.separatorChar != '\\') return; File f = new File("").getCanonicalFile(); while (f.getParent() != null) f = f.getParentFile(); String p = f.getPath().substring(0, 2); diff --git a/test/jdk/java/io/pathNames/win32/DriveRelativePath.java b/test/jdk/java/io/pathNames/win32/DriveRelativePath.java index 43fa2175e092..3f8e225ab3f5 100644 --- a/test/jdk/java/io/pathNames/win32/DriveRelativePath.java +++ b/test/jdk/java/io/pathNames/win32/DriveRelativePath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 1998, 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 @@ -24,6 +24,7 @@ /* @test @bug 4070044 4164823 @summary Check getCanonicalPath's treatment of drive-relative paths (win32) + @requires (os.family == "windows") */ import java.io.*; @@ -37,11 +38,6 @@ static void fail(String s) { public static void main(String[] args) throws IOException { - if (File.separatorChar != '\\') { - /* This test is only valid on win32 systems */ - return; - } - File f = new File("foo"); String c = f.getCanonicalPath(); System.err.println(c); diff --git a/test/jdk/java/io/pathNames/win32/DriveSlash.java b/test/jdk/java/io/pathNames/win32/DriveSlash.java index feb651204d0c..32777ad83d46 100644 --- a/test/jdk/java/io/pathNames/win32/DriveSlash.java +++ b/test/jdk/java/io/pathNames/win32/DriveSlash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -25,6 +25,7 @@ @bug 4065189 @summary Check that win32 pathnames of the form "C:\\" can be listed by the File.list method + @requires (os.family == "windows") @author Mark Reinhold */ @@ -35,9 +36,6 @@ public class DriveSlash { public static void main(String[] args) throws Exception { - /* This test is only valid on win32 systems */ - if (File.separatorChar != '\\') return; - File f = new File("c:\\"); System.err.println(f.getCanonicalPath()); String[] fs = f.list(); diff --git a/test/jdk/java/io/pathNames/win32/RenameDelete.java b/test/jdk/java/io/pathNames/win32/RenameDelete.java index a6cfffade4bd..4b674ddea919 100644 --- a/test/jdk/java/io/pathNames/win32/RenameDelete.java +++ b/test/jdk/java/io/pathNames/win32/RenameDelete.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 1999, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -24,6 +24,7 @@ /* * @test * @bug 4042592 4042593 + @requires (os.family == "windows") * @summary Test operation of rename and delete on win32 */ @@ -40,11 +41,6 @@ public class RenameDelete { public static void main(String[] args) throws Exception { boolean success = false; - if (File.separatorChar != '\\') { - System.err.println("Not a win32 platform -- test inapplicable"); - return; - } - //construct a test file in this location File f1 = new File("."); StringBuffer location = new StringBuffer("\\"); diff --git a/test/jdk/java/io/pathNames/win32/SJIS.java b/test/jdk/java/io/pathNames/win32/SJIS.java index 580f06330a6e..11c69dca8dfa 100644 --- a/test/jdk/java/io/pathNames/win32/SJIS.java +++ b/test/jdk/java/io/pathNames/win32/SJIS.java @@ -25,6 +25,7 @@ @bug 4039597 @summary Check that pathnames containing double-byte characters are not corrupted by win32 path processing + @requires (os.family == "windows") @author Mark Reinhold @library /test/lib */ @@ -52,7 +53,6 @@ public static void main(String[] args) throws Exception { /* This test is only valid on win32 systems that use the SJIS encoding */ - if (File.separatorChar != '\\') return; String enc = System.getProperty("native.encoding"); if ((enc == null) || !enc.equals("MS932")) { throw new SkippedException( diff --git a/test/jdk/java/io/pathNames/win32/bug6344646.java b/test/jdk/java/io/pathNames/win32/bug6344646.java index a89d72fe165b..ecb4bc2bc661 100644 --- a/test/jdk/java/io/pathNames/win32/bug6344646.java +++ b/test/jdk/java/io/pathNames/win32/bug6344646.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -25,6 +25,7 @@ * @bug 6344646 * @summary tests that WinNTFileSystem.hashCode() uses * locale independent case mapping. + * @requires (os.family == "windows") */ import java.io.*; @@ -34,11 +35,6 @@ public class bug6344646 { public static void main(String[] s) { Locale reservedLocale = Locale.getDefault(); try { - /* This test is only valid on win32 systems */ - if (File.separatorChar != '\\') { - return; - } - Locale.setDefault(Locale.of("lt")); File f1 = new File("J\u0301"); File f2 = new File("j\u0301"); diff --git a/test/jdk/java/lang/Character/Latin1CaseConversion.java b/test/jdk/java/lang/Character/Latin1CaseConversion.java index a176bd4b002e..436193c5f168 100644 --- a/test/jdk/java/lang/Character/Latin1CaseConversion.java +++ b/test/jdk/java/lang/Character/Latin1CaseConversion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * 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 +21,16 @@ * questions. */ -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @test * @bug 8302877 * @summary Provides exhaustive verification of Character.toUpperCase and Character.toLowerCase * for all code points in the latin1 range 0-255. - * @run testng Latin1CaseConversion + * @run junit Latin1CaseConversion */ public class Latin1CaseConversion { @@ -44,41 +43,41 @@ public void shouldUpperCaseAndLowerCaseLatin1() { if (c < 0x41) { // Before A assertUnchanged(upper, lower, c); } else if (c <= 0x5A) { // A-Z - assertEquals(upper, c); - assertEquals(lower, c + 32); + assertEquals(c, upper); + assertEquals(c + 32, lower); } else if (c < 0x61) { // Between Z and a assertUnchanged(upper, lower, c); } else if (c <= 0x7A) { // a-z - assertEquals(upper, c - 32); - assertEquals(lower, c); + assertEquals(c - 32, upper); + assertEquals(c, lower); } else if (c < 0xB5) { // Between z and Micro Sign assertUnchanged(upper, lower, c); } else if (c == 0xB5) { // Special case for Micro Sign - assertEquals(upper, 0x39C); - assertEquals(lower, c); + assertEquals(0x39C, upper); + assertEquals(c, lower); } else if (c < 0xC0) { // Between my and A-grave assertUnchanged(upper, lower, c); } else if (c < 0xD7) { // A-grave - O with Diaeresis - assertEquals(upper, c); - assertEquals(lower, c + 32); + assertEquals(c, upper); + assertEquals(c + 32, lower); } else if (c == 0xD7) { // Multiplication assertUnchanged(upper, lower, c); } else if (c <= 0xDE) { // O with slash - Thorn - assertEquals(upper, c); - assertEquals(lower, c + 32); + assertEquals(c, upper); + assertEquals(c + 32, lower); } else if (c == 0xDF) { // Sharp s assertUnchanged(upper, lower, c); } else if (c < 0xF7) { // a-grave - divsion - assertEquals(upper, c - 32); - assertEquals(lower, c); + assertEquals(c - 32, upper); + assertEquals(c, lower); } else if (c == 0xF7) { // Division assertUnchanged(upper, lower, c); } else if (c < 0xFF) { // o with slash - thorn - assertEquals(upper, c - 32); - assertEquals(lower, c); + assertEquals(c - 32, upper); + assertEquals(c, lower); } else if (c == 0XFF) { // Special case for y with Diaeresis - assertEquals(upper, 0x178); - assertEquals(lower, c); + assertEquals(0x178, upper); + assertEquals(c, lower); } else { fail("Uncovered code point: " + Integer.toHexString(c)); } @@ -86,7 +85,7 @@ public void shouldUpperCaseAndLowerCaseLatin1() { } private static void assertUnchanged(int upper, int lower, int c) { - assertEquals(upper, c); - assertEquals(lower, c); + assertEquals(c, upper); + assertEquals(c, lower); } } diff --git a/test/jdk/java/lang/Character/UnicodeBlock/NumberEntities.java b/test/jdk/java/lang/Character/UnicodeBlock/NumberEntities.java index 30382c3cfe39..86b9fe6ea692 100644 --- a/test/jdk/java/lang/Character/UnicodeBlock/NumberEntities.java +++ b/test/jdk/java/lang/Character/UnicodeBlock/NumberEntities.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * 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,17 +28,17 @@ * of Character.UnicodeBlock constants. Also checks the size of * Character.UnicodeScript's "aliases" map. * @modules java.base/java.lang:open - * @run testng NumberEntities + * @run junit NumberEntities */ -import static org.testng.Assert.assertEquals; -import org.testng.annotations.Test; - import java.lang.reflect.Field; import java.util.Map; -@Test +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + public class NumberEntities { + @Test public void test_UnicodeBlock_NumberEntities() throws Throwable { // The number of entries in Character.UnicodeBlock.map. // See src/java.base/share/classes/java/lang/Character.java @@ -46,13 +46,14 @@ public void test_UnicodeBlock_NumberEntities() throws Throwable { Field m = Character.UnicodeBlock.class.getDeclaredField("map"); n.setAccessible(true); m.setAccessible(true); - assertEquals(((Map)m.get(null)).size(), n.getInt(null)); + assertEquals(n.getInt(null), ((Map)m.get(null)).size()); } + @Test public void test_UnicodeScript_aliases() throws Throwable { // The number of entries in Character.UnicodeScript.aliases. // See src/java.base/share/classes/java/lang/Character.java Field aliases = Character.UnicodeScript.class.getDeclaredField("aliases"); aliases.setAccessible(true); - assertEquals(((Map)aliases.get(null)).size(), Character.UnicodeScript.UNKNOWN.ordinal() + 1); + assertEquals(Character.UnicodeScript.UNKNOWN.ordinal() + 1, ((Map)aliases.get(null)).size()); } } diff --git a/test/jdk/java/lang/StringBuilder/HugeCapacity.java b/test/jdk/java/lang/StringBuilder/HugeCapacity.java index a584ce1f07a9..bd6eb51f53bc 100644 --- a/test/jdk/java/lang/StringBuilder/HugeCapacity.java +++ b/test/jdk/java/lang/StringBuilder/HugeCapacity.java @@ -27,8 +27,8 @@ * @summary Capacity should not get close to Integer.MAX_VALUE unless * necessary * @requires (sun.arch.data.model == "64" & os.maxMemory >= 8G) - * @run main/othervm -Xms6G -Xmx6G -XX:+CompactStrings HugeCapacity true - * @run main/othervm -Xms6G -Xmx6G -XX:-CompactStrings HugeCapacity false + * @run main/othervm -Xms8G -Xmx8G -XX:-CompactStrings -Xlog:gc HugeCapacity false + * @run main/othervm -Xms8G -Xmx8G -XX:+CompactStrings -Xlog:gc HugeCapacity true */ public class HugeCapacity { diff --git a/test/jdk/java/lang/Thread/virtual/JfrEvents.java b/test/jdk/java/lang/Thread/virtual/JfrEvents.java index f731702990f0..1cad7fa42028 100644 --- a/test/jdk/java/lang/Thread/virtual/JfrEvents.java +++ b/test/jdk/java/lang/Thread/virtual/JfrEvents.java @@ -27,7 +27,8 @@ * @requires vm.continuations & vm.hasJFR * @modules jdk.jfr java.base/java.lang:+open * @library /test/lib - * @run junit/othervm --enable-native-access=ALL-UNNAMED JfrEvents + * @compile --enable-preview -source ${jdk.version} JfrEvents.java + * @run junit/othervm --enable-preview --enable-native-access=ALL-UNNAMED JfrEvents */ import java.io.IOException; @@ -44,6 +45,7 @@ import java.util.concurrent.locks.LockSupport; import java.util.function.Consumer; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; import jdk.jfr.EventType; @@ -72,12 +74,13 @@ void testVirtualThreadStartAndEnd() throws Exception { // execute 100 tasks, each in their own virtual thread recording.start(); - ThreadFactory factory = Thread.ofVirtual().factory(); - try (var executor = Executors.newThreadPerTaskExecutor(factory)) { - for (int i = 0; i < 100; i++) { - executor.submit(() -> { }); + try { + List threads = IntStream.range(0, 100) + .mapToObj(_ -> Thread.startVirtualThread(() -> { })) + .toList(); + for (Thread t : threads) { + t.join(); } - Thread.sleep(1000); // give time for thread end events to be recorded } finally { recording.stop(); } diff --git a/test/jdk/java/lang/Thread/virtual/stress/Skynet.java b/test/jdk/java/lang/Thread/virtual/stress/Skynet.java index ee45fc827b00..d4678ce39d0a 100644 --- a/test/jdk/java/lang/Thread/virtual/stress/Skynet.java +++ b/test/jdk/java/lang/Thread/virtual/stress/Skynet.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -26,14 +26,14 @@ * @summary Stress test virtual threads with a variation of the Skynet 1M benchmark * @requires vm.continuations * @requires !vm.debug | vm.gc != "Z" - * @run main/othervm/timeout=300 -Xmx1500m Skynet + * @run main/othervm/timeout=400 -Xmx1500m Skynet */ /* * @test id=ZSinglegen * @requires vm.debug == true & vm.continuations * @requires vm.gc.ZSinglegen - * @run main/othervm/timeout=300 -XX:+UnlockDiagnosticVMOptions + * @run main/othervm/timeout=400 -XX:+UnlockDiagnosticVMOptions * -XX:+UseZGC -XX:-ZGenerational * -XX:+ZVerifyOops -XX:ZCollectionInterval=0.01 -Xmx1500m Skynet */ @@ -42,7 +42,7 @@ * @test id=ZGenerational * @requires vm.debug == true & vm.continuations * @requires vm.gc.ZGenerational - * @run main/othervm/timeout=300 -XX:+UnlockDiagnosticVMOptions + * @run main/othervm/timeout=400 -XX:+UnlockDiagnosticVMOptions * -XX:+UseZGC -XX:+ZGenerational * -XX:+ZVerifyOops -XX:ZCollectionInterval=0.01 -Xmx1500m Skynet */ diff --git a/test/jdk/java/lang/instrument/RetransformBigClassTest.java b/test/jdk/java/lang/instrument/RetransformBigClassTest.java new file mode 100644 index 000000000000..c4788217be16 --- /dev/null +++ b/test/jdk/java/lang/instrument/RetransformBigClassTest.java @@ -0,0 +1,161 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * 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 8277444 + * + * @library /test/lib + * @compile SimpleIdentityTransformer.java + * @run shell MakeJAR.sh retransformAgent + * @run main/othervm -javaagent:retransformAgent.jar RetransformBigClassTest + */ + +import jdk.test.lib.compiler.InMemoryJavaCompiler; + +/* + * JvmtiClassFileReconstituter::copy_bytecodes restores bytecodes rewritten + * by the linking process. It is used by RetransformClasses. + * JDK-8277444 is a data race between copy_bytecodes and the linking process. + * This test puts the linking process in one thread and the retransforming process + * in another thread. The test uses Class.forName("BigClass", false, classLoader) + * which does not link the class. When the class is used, the linking process starts. + * In another thread retransforming of the class is happening. + * We generate a class with big methods. A number of methods and their size are + * chosen to make the linking and retransforming processes run concurrently. + * We delay the retransforming process to follow the linking process. + * If there is no synchronization between the processes, a data race will happen. + */ +public class RetransformBigClassTest extends AInstrumentationTestCase { + + private static final Object LOCK = new Object(); + private static final int COUNTER_INC_COUNT = 2000; // A number of 'c+=1;' statements in methods of a class. + private static final int MIN_LINK_TIME_MS = 60; // Large enough so the linking and retransforming processes run in parallel. + private static final int RETRANSFORM_CLASSES_DELAY_MS = 37; // We manage to create a data race when a delay is in the range 0.52x - 0.62x of MIN_LINK_TIME_MS. + + private static Class bigClass; + private static byte[] bigClassBytecode; + + private Thread retransformThread; + + RetransformBigClassTest() { + super("RetransformBigClassTest"); + } + + public static void main(String[] args) throws Throwable { + new RetransformBigClassTest().runTest(); + } + + protected final void doRunTest() throws Throwable { + ClassLoader classLoader = new ClassLoader() { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (name.equals("BigClass")) { + return defineClass(name, bigClassBytecode, 0, bigClassBytecode.length); + } + + return super.findClass(name); + } + }; + synchronized (LOCK) { + bigClass = Class.forName("BigClass", false, classLoader); + LOCK.notify(); + } + // Make a use of the BigClass + assertTrue(bigClass.getConstructor().newInstance().hashCode() != 0); + retransformThread.join(); + } + + private byte[] createClassBytecode(String className, int methodCount) throws Exception { + String methodBody = ""; + for (int j = 0; j < COUNTER_INC_COUNT; j++) { + methodBody += "c+=1;"; + } + + String classSrc = "public class " + className + " { int c;"; + + for (int i = 0; i < methodCount; i++) { + classSrc += "\npublic void m" + i + "(){"; + classSrc += methodBody; + classSrc += "\n}"; + } + classSrc += "\n}"; + + return InMemoryJavaCompiler.compile(className, classSrc); + } + + // We need a number of methods such that the linking time is greater than + // or equal to MIN_LINK_TIME_MS. + // We create a class having 5 methods and trigger the linking process. + // We measure the time taken and use it to calculate the needed number. + private int findMethodCount() throws Exception { + int methodCount = 5; + final String className = "BigClass" + methodCount; + final byte[] bytecode = createClassBytecode(className, methodCount); + ClassLoader classLoader = new ClassLoader() { + @Override + protected Class findClass(String name) throws ClassNotFoundException { + if (name.equals(className)) { + return defineClass(name, bytecode, 0, bytecode.length); + } + + return super.findClass(name); + } + }; + var bigClass = Class.forName(className, false, classLoader); + long startTime = System.nanoTime(); + assertTrue(bigClass.getConstructor().newInstance().hashCode() != 0); + double linkTimeMs = (System.nanoTime() - startTime) / 1000000.0; + System.out.println("Link time for a class with " + methodCount + " methods each having " + COUNTER_INC_COUNT + " counter increments: " + Math.round(linkTimeMs)); + if (linkTimeMs < MIN_LINK_TIME_MS) { + methodCount = (int)Math.round((MIN_LINK_TIME_MS * methodCount) / linkTimeMs); + } + System.out.println("The number of methods to exceed " + MIN_LINK_TIME_MS + " ms linking time: " + methodCount); + return methodCount; + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + + bigClassBytecode = createClassBytecode("BigClass", findMethodCount()); + fInst.addTransformer(new SimpleIdentityTransformer()); + retransformThread = new Thread(() -> { + try { + synchronized (LOCK) { + while (bigClass == null) { + System.out.println("[retransformThread]: Waiting for bigClass"); + LOCK.wait(); + } + } + Thread.sleep(RETRANSFORM_CLASSES_DELAY_MS); + fInst.retransformClasses(bigClass); + } catch (Exception e) { + e.printStackTrace(); + } + }); + retransformThread.start(); + Thread.sleep(100); + } +} diff --git a/test/jdk/java/lang/invoke/MethodHandleProxies/Driver.java b/test/jdk/java/lang/invoke/MethodHandleProxies/Driver.java index 6acd4fb30e1d..0e9c708e8e9f 100644 --- a/test/jdk/java/lang/invoke/MethodHandleProxies/Driver.java +++ b/test/jdk/java/lang/invoke/MethodHandleProxies/Driver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * 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,12 +21,12 @@ * questions. */ -/** +/* * @test * @bug 8280377 * @build m1/* m2/* Unnamed * @run testng/othervm m1/p1.Main - * @run testng/othervm Unnamed + * @run main/othervm Unnamed * @summary Test MethodHandleProxies::asInterfaceInstance with a default * method with varargs */ diff --git a/test/jdk/java/lang/invoke/MethodHandleProxies/Unnamed.java b/test/jdk/java/lang/invoke/MethodHandleProxies/Unnamed.java index f42071f04275..f60f36ca9de7 100644 --- a/test/jdk/java/lang/invoke/MethodHandleProxies/Unnamed.java +++ b/test/jdk/java/lang/invoke/MethodHandleProxies/Unnamed.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String... args) throws Throwable { // verify that the caller has no access to the proxy created on an // inaccessible interface - Method m = intf.getMethod("test", Object[].class); - assertFalse(m.canAccess(null)); + Method m = intf.getMethod("test"); + assertFalse(m.canAccess(t)); } } diff --git a/test/jdk/java/lang/invoke/TestVHInvokerCaching.java b/test/jdk/java/lang/invoke/TestVHInvokerCaching.java index ccd97f82e9b4..0a1ae5914ca0 100644 --- a/test/jdk/java/lang/invoke/TestVHInvokerCaching.java +++ b/test/jdk/java/lang/invoke/TestVHInvokerCaching.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -37,7 +37,7 @@ import java.util.List; import static java.lang.invoke.MethodHandles.lookup; -import static org.testng.Assert.assertSame; +import static org.testng.Assert.*; public class TestVHInvokerCaching { @@ -74,7 +74,7 @@ class Holder { MethodHandles.Lookup lookup = lookup(); - for (Field field : Holder.class.getFields()) { + for (Field field : Holder.class.getDeclaredFields()) { String fieldName = field.getName(); Class fieldType = field.getType(); @@ -82,6 +82,8 @@ class Holder { testHandles.add(lookup.findVarHandle(Holder.class, fieldName, fieldType)); } + assertFalse(testHandles.isEmpty()); + return testHandles.stream().map(vh -> new Object[]{ vh }).toArray(Object[][]::new); } } diff --git a/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest2.java b/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest2.java index de1b22c4075a..b093f086ba44 100644 --- a/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest2.java +++ b/test/jdk/java/lang/management/MemoryMXBean/LowMemoryTest2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2026, Oracle and/or its affiliates. All rights reserved. * 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,18 +35,14 @@ * @test * @bug 4982128 * @summary Test low memory detection of non-heap memory pool - * - * @run main/othervm/timeout=600 -Xnoclassgc -XX:MaxMetaspaceSize=32m - * LowMemoryTest2 - */ - -/* - * @test - * @bug 4982128 - * @summary Test low memory detection of non-heap memory pool - * - * @run main/othervm/timeout=600 -Xnoclassgc -XX:MaxMetaspaceSize=16m - * -XX:CompressedClassSpaceSize=4m LowMemoryTest2 + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm/timeout=600 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * -Xnoclassgc -XX:MaxMetaspaceSize=32m LowMemoryTest2 + * @run main/othervm/timeout=600 -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:. + * -Xnoclassgc -XX:MaxMetaspaceSize=16m + * -XX:CompressedClassSpaceSize=4m LowMemoryTest2 */ import java.lang.management.*; @@ -54,6 +50,8 @@ import javax.management.openmbean.CompositeData; import java.util.*; +import jdk.test.whitebox.WhiteBox; + public class LowMemoryTest2 { private static volatile boolean listenerInvoked = false; @@ -177,7 +175,7 @@ public void run() { // If we don't force a GC we may get an // OutOfMemoryException before the counters are updated. System.out.println("Force GC"); - System.gc(); + WhiteBox.getWhiteBox().fullGC(); } isThresholdCountSet = isAnyThresholdCountSet(pools); } diff --git a/test/jdk/java/lang/module/customfs/ModulesInCustomFileSystem.java b/test/jdk/java/lang/module/customfs/ModulesInCustomFileSystem.java index 801f2e5fca6c..e023a3a5839b 100644 --- a/test/jdk/java/lang/module/customfs/ModulesInCustomFileSystem.java +++ b/test/jdk/java/lang/module/customfs/ModulesInCustomFileSystem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, 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 @@ -28,7 +28,7 @@ * @library /test/lib * @build ModulesInCustomFileSystem m1/* m2/* * jdk.test.lib.util.JarUtils - * @run testng/othervm ModulesInCustomFileSystem + * @run testng/othervm -Djava.io.tmpdir=. ModulesInCustomFileSystem * @summary Test ModuleFinder to find modules in a custom file system */ diff --git a/test/jdk/java/lang/ref/FinalizerHistogramTest.java b/test/jdk/java/lang/ref/FinalizerHistogramTest.java index 66cf76ea7f22..192c229c7b58 100644 --- a/test/jdk/java/lang/ref/FinalizerHistogramTest.java +++ b/test/jdk/java/lang/ref/FinalizerHistogramTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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,8 +21,9 @@ * questions. */ -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; +import jdk.test.whitebox.WhiteBox; + +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.lang.reflect.Method; @@ -32,37 +33,49 @@ * @test * @summary Unit test for FinalizerHistogram * @modules java.base/java.lang.ref:open - * @run main FinalizerHistogramTest + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox + * @run main/othervm + * -Xbootclasspath/a:. + * -XX:+UnlockDiagnosticVMOptions + * -XX:+WhiteBoxAPI + * FinalizerHistogramTest */ public class FinalizerHistogramTest { static ReentrantLock lock = new ReentrantLock(); - static volatile int wasInitialized = 0; - static volatile int wasTrapped = 0; - static final int objectsCount = 1000; + static final AtomicInteger initializedCount = new AtomicInteger(0); + static final int OBJECTS_COUNT = 1000; + + static WhiteBox wb; static class MyObject { public MyObject() { // Make sure object allocation/deallocation is not optimized out - wasInitialized += 1; + initializedCount.incrementAndGet(); } protected void finalize() { // Trap the object in a finalization queue - wasTrapped += 1; lock.lock(); } } - public static void main(String[] argvs) { + public static void main(String[] argvs) throws InterruptedException { try { lock.lock(); - for(int i = 0; i < objectsCount; ++i) { + for(int i = 0; i < OBJECTS_COUNT; ++i) { new MyObject(); } - System.out.println("Objects intialized: " + objectsCount); - System.gc(); - while(wasTrapped < 1); + System.out.println("Objects intialized: " + initializedCount.get()); + wb = WhiteBox.getWhiteBox(); + wb.fullGC(); + boolean refProResult; + do { + refProResult = wb.waitForReferenceProcessing(); + System.out.println("waitForReferenceProcessing returned: " + refProResult); + } while (refProResult); Class klass = Class.forName("java.lang.ref.FinalizerHistogram"); diff --git a/test/jdk/java/net/URL/EarlyOrDelayedParsing.java b/test/jdk/java/net/URL/EarlyOrDelayedParsing.java index 57fa76c23bb8..e286631be6b3 100644 --- a/test/jdk/java/net/URL/EarlyOrDelayedParsing.java +++ b/test/jdk/java/net/URL/EarlyOrDelayedParsing.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -38,6 +38,10 @@ import java.io.IOException; import java.net.ConnectException; import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; @@ -57,6 +61,19 @@ public class EarlyOrDelayedParsing { { String value = System.getProperty("jdk.net.url.delayParsing", "false"); EARLY_PARSING = !value.isEmpty() && !Boolean.parseBoolean(value); + if (!EARLY_PARSING) { + // we will open the connection in that case. + // make sure no proxy is selected + ProxySelector.setDefault(new ProxySelector() { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + } + }); + } } // Some characters that when included at the wrong place diff --git a/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java b/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java index 4079bd81e3e1..265c661b81b6 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPublishers.java @@ -25,15 +25,6 @@ import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import javax.net.ssl.SSLContext; import java.io.IOException; @@ -52,7 +43,6 @@ import java.net.http.HttpResponse.BodyHandlers; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Set; @@ -80,24 +70,31 @@ import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingPublishers implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] - HttpTestServer httpsTestServer; // HTTPS/1.1 - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - String httpURI_fixed; - String httpURI_chunk; - String httpsURI_fixed; - String httpsURI_chunk; - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; + static SSLContext sslContext; + static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] + static HttpTestServer httpsTestServer; // HTTPS/1.1 + static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) + static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + static String httpURI_fixed; + static String httpURI_chunk; + static String httpsURI_fixed; + static String httpsURI_chunk; + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; static final int ITERATION_COUNT = 1; // a shared executor helps reduce the amount of threads created by the test @@ -115,8 +112,34 @@ public static String now() { return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + final static class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -142,34 +165,12 @@ public void execute(Runnable command) { } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -193,7 +194,7 @@ static final void printFailedTests(ITestContext context) { } } - private String[] uris() { + private static String[] uris() { return new String[] { httpURI_fixed, httpURI_chunk, @@ -206,8 +207,7 @@ private String[] uris() { }; } - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; //Object[][] result = new Object[uris.length][]; @@ -238,7 +238,7 @@ public void accept(Where where) { } } - private Object[][] variants(List throwers, Set whereValues) { + private static Object[][] variants(List throwers, Set whereValues) { String[] uris = uris(); Object[][] result = new Object[uris.length * 2 * throwers.size()][]; //Object[][] result = new Object[(uris.length/2) * 2 * 2][]; @@ -257,80 +257,52 @@ private Object[][] variants(List throwers, Set whereValues) { return result; } - @DataProvider(name = "subscribeProvider") - public Object[][] subscribeProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] subscribeProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_SUBSCRIBE, Where.AFTER_SUBSCRIBE)); } - @DataProvider(name = "requestProvider") - public Object[][] requestProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] requestProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_REQUEST, Where.AFTER_REQUEST)); } - @DataProvider(name = "nextRequestProvider") - public Object[][] nextRequestProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] nextRequestProvider() { return variants(List.of( new UncheckedCustomExceptionThrower(), new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_NEXT_REQUEST, Where.AFTER_NEXT_REQUEST)); } - @DataProvider(name = "beforeCancelProviderIO") - public Object[][] beforeCancelProviderIO(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] beforeCancelProviderIO() { return variants(List.of( new UncheckedIOExceptionThrower()), EnumSet.of(Where.BEFORE_CANCEL)); } - @DataProvider(name = "afterCancelProviderIO") - public Object[][] afterCancelProviderIO(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] afterCancelProviderIO() { return variants(List.of( new UncheckedIOExceptionThrower()), EnumSet.of(Where.AFTER_CANCEL)); } - @DataProvider(name = "beforeCancelProviderCustom") - public Object[][] beforeCancelProviderCustom(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] beforeCancelProviderCustom() { return variants(List.of( new UncheckedCustomExceptionThrower()), EnumSet.of(Where.BEFORE_CANCEL)); } - @DataProvider(name = "afterCancelProviderCustom") - public Object[][] afterCancelProvider(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] afterCancelProviderCustom() { return variants(List.of( new UncheckedCustomExceptionThrower()), EnumSet.of(Where.AFTER_CANCEL)); } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); return TRACKER.track(HttpClient.newBuilder() .proxy(HttpClient.Builder.NO_PROXY) @@ -339,11 +311,11 @@ private HttpClient makeNewClient() { .build()); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingPublishers.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -387,7 +359,7 @@ protected void testSanityImpl(String uri, boolean sameClient) CompletableFuture> response = client.sendAsync(req, handler); String body = response.join().body(); - assertEquals(body, Stream.of(BODY.split("\\|")).collect(Collectors.joining())); + assertEquals(Stream.of(BODY.split("\\|")).collect(Collectors.joining()), body); if (!sameClient) { // Wait for the client to be garbage collected. // we use the ReferenceTracker API rather than HttpClient::close here, @@ -431,7 +403,6 @@ private void testThrowing(String name, String uri, boolean sameClient, boolean async, Set whereValues) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, publishers, finisher, thrower, async, whereValues); @@ -721,8 +692,11 @@ public void onError(Throwable throwable) { } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { + System.out.println(now() + "setup"); + System.err.println(now() + "setup"); + sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); @@ -765,8 +739,11 @@ public void setup() throws Exception { https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { + System.out.println(now() + "teardown"); + System.err.println(now() + "teardown"); + String sharedClientName = sharedClient == null ? null : sharedClient.toString(); sharedClient = null; diff --git a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java index b5230d48d104..50200c86b430 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingPushPromises.java @@ -35,18 +35,10 @@ * ReferenceTracker AbstractThrowingPushPromises * jdk.httpclient.test.lib.common.HttpServerAdapters * - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true */ import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterTest; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; import javax.net.ssl.SSLContext; import java.io.BufferedReader; @@ -95,18 +87,29 @@ import static java.lang.String.format; import static java.net.http.HttpClient.Version.HTTP_2; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class AbstractThrowingPushPromises implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; + static SSLContext sslContext; + static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) + static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; static final int ITERATION_COUNT = 1; // a shared executor helps reduce the amount of threads created by the test @@ -124,8 +127,34 @@ public static String now() { return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + static final class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -151,34 +180,13 @@ public void execute(Runnable command) { } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -203,7 +211,7 @@ static final void printFailedTests(ITestContext context) { } } - private String[] uris() { + private static String[] uris() { return new String[] { http2URI_fixed, http2URI_chunk, @@ -212,8 +220,7 @@ private String[] uris() { }; } - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; @@ -242,7 +249,7 @@ public void accept(Where where) { } } - private Object[][] variants(List throwers) { + private static Object[][] variants(List throwers) { String[] uris = uris(); // reduce traces by always using the same client if // stopAfterFirstFailure is requested. @@ -262,25 +269,17 @@ private Object[][] variants(List throwers) { return result; } - @DataProvider(name = "ioVariants") - public Object[][] ioVariants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] ioVariants() { return variants(List.of( new UncheckedIOExceptionThrower())); } - @DataProvider(name = "customVariants") - public Object[][] customVariants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] customVariants() { return variants(List.of( new UncheckedCustomExceptionThrower())); } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); return TRACKER.track(HttpClient.newBuilder() .proxy(HttpClient.Builder.NO_PROXY) @@ -289,11 +288,11 @@ private HttpClient makeNewClient() { .build()); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingPushPromises.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -331,13 +330,13 @@ public void applyPushPromise(HttpRequest initiatingRequest, HttpResponse> response = client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get(); String body = response.body().collect(Collectors.joining("|")); - assertEquals(URI.create(body).getPath(), URI.create(uri).getPath()); + assertEquals(URI.create(uri).getPath(), URI.create(body).getPath()); for (HttpRequest promised : pushPromises.keySet()) { out.printf("%s Received promise: %s%n\tresponse: %s%n", now(), promised, pushPromises.get(promised).get()); String promisedBody = pushPromises.get(promised).get().body() .collect(Collectors.joining("|")); - assertEquals(promisedBody, promised.uri().toASCIIString()); + assertEquals(promised.uri().toASCIIString(), promisedBody); } assertEquals(3, pushPromises.size()); if (!sameClient) { @@ -402,7 +401,6 @@ private void testThrowing(String name, String uri, boolean sameClient, Finisher finisher, Thrower thrower) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, handlers, finisher, thrower); @@ -577,9 +575,9 @@ private final List check(Where w, URI reqURI, default: expectedCount = 3; } - assertEquals(promises.size(), expectedCount, + assertEquals(expectedCount, promises.size(), "bad promise count for " + reqURI + " with " + w); - assertEquals(result, List.of(reqURI.toASCIIString())); + assertEquals(List.of(reqURI.toASCIIString()), result); return result; } @@ -732,8 +730,8 @@ public CompletionStage getBody() { } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); @@ -759,8 +757,8 @@ public void setup() throws Exception { https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { String sharedClientName = sharedClient == null ? null : sharedClient.toString(); sharedClient = null; diff --git a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java index dc7ca3fe9d54..6ae8f3a90f67 100644 --- a/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java +++ b/test/jdk/java/net/httpclient/AbstractThrowingSubscribers.java @@ -22,14 +22,6 @@ */ import jdk.test.lib.net.SimpleSSLContext; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.SkipException; -import org.testng.annotations.AfterTest; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; import javax.net.ssl.SSLContext; import java.io.BufferedReader; @@ -47,7 +39,6 @@ import java.net.http.HttpResponse.BodySubscriber; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -71,24 +62,33 @@ import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.extension.TestWatcher; public abstract class AbstractThrowingSubscribers implements HttpServerAdapters { - SSLContext sslContext; - HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] - HttpTestServer httpsTestServer; // HTTPS/1.1 - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - String httpURI_fixed; - String httpURI_chunk; - String httpsURI_fixed; - String httpsURI_chunk; - String http2URI_fixed; - String http2URI_chunk; - String https2URI_fixed; - String https2URI_chunk; + static SSLContext sslContext; + static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ] + static HttpTestServer httpsTestServer; // HTTPS/1.1 + static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) + static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + static String httpURI_fixed; + static String httpURI_chunk; + static String httpsURI_fixed; + static String httpsURI_chunk; + static String http2URI_fixed; + static String http2URI_chunk; + static String https2URI_fixed; + static String https2URI_chunk; static final int ITERATION_COUNT = 1; static final int REPEAT_RESPONSE = 3; @@ -107,8 +107,34 @@ public static String now() { return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan); } - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; - private volatile HttpClient sharedClient; + static final class TestStopper implements TestWatcher, BeforeEachCallback { + final AtomicReference failed = new AtomicReference<>(); + TestStopper() { } + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + if (stopAfterFirstFailure()) { + String msg = "Aborting due to: " + cause; + failed.compareAndSet(null, msg); + FAILURES.putIfAbsent(context.getDisplayName(), cause); + System.out.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + System.err.printf("%nTEST FAILED: %s%s%n\tAborting due to %s%n%n", + now(), context.getDisplayName(), cause); + } + } + + @Override + public void beforeEach(ExtensionContext context) { + String msg = failed.get(); + Assumptions.assumeTrue(msg == null, msg); + } + } + + @RegisterExtension + static final TestStopper stopper = new TestStopper(); + + static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static volatile HttpClient sharedClient; static class TestExecutor implements Executor { final AtomicLong tasks = new AtomicLong(); @@ -134,34 +160,12 @@ public void execute(Runnable command) { } } - protected boolean stopAfterFirstFailure() { + protected static boolean stopAfterFirstFailure() { return Boolean.getBoolean("jdk.internal.httpclient.debug"); } - final AtomicReference skiptests = new AtomicReference<>(); - void checkSkip() { - var skip = skiptests.get(); - if (skip != null) throw skip; - } - static String name(ITestResult result) { - var params = result.getParameters(); - return result.getName() - + (params == null ? "()" : Arrays.toString(result.getParameters())); - } - - @BeforeMethod - void beforeMethod(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - if (skiptests.get() == null) { - SkipException skip = new SkipException("some tests failed"); - skip.setStackTrace(new StackTraceElement[0]); - skiptests.compareAndSet(null, skip); - } - } - } - - @AfterClass - static final void printFailedTests(ITestContext context) { + @AfterAll + static final void printFailedTests() { out.println("\n========================="); try { // Exceptions should already have been added to FAILURES @@ -186,7 +190,7 @@ static final void printFailedTests(ITestContext context) { } } - private String[] uris() { + private static String[] uris() { return new String[] { httpURI_fixed, httpURI_chunk, @@ -199,10 +203,9 @@ private String[] uris() { }; } - static AtomicLong URICOUNT = new AtomicLong(); + static final AtomicLong URICOUNT = new AtomicLong(); - @DataProvider(name = "sanity") - public Object[][] sanity() { + public static Object[][] sanity() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2][]; int i = 0; @@ -215,11 +218,7 @@ public Object[][] sanity() { return result; } - @DataProvider(name = "variants") - public Object[][] variants(ITestContext context) { - if (stopAfterFirstFailure() && context.getFailedTests().size() > 0) { - return new Object[0][]; - } + public static Object[][] variants() { String[] uris = uris(); Object[][] result = new Object[uris.length * 2 * 2][]; int i = 0; @@ -236,7 +235,7 @@ public Object[][] variants(ITestContext context) { return result; } - private HttpClient makeNewClient() { + private static HttpClient makeNewClient() { clientCount.incrementAndGet(); HttpClient client = HttpClient.newBuilder() .proxy(HttpClient.Builder.NO_PROXY) @@ -246,11 +245,11 @@ private HttpClient makeNewClient() { return TRACKER.track(client); } - HttpClient newHttpClient(boolean share) { + static HttpClient newHttpClient(boolean share) { if (!share) return makeNewClient(); HttpClient shared = sharedClient; if (shared != null) return shared; - synchronized (this) { + synchronized (AbstractThrowingSubscribers.class) { shared = sharedClient; if (shared == null) { shared = sharedClient = makeNewClient(); @@ -307,7 +306,7 @@ protected void testSanityImpl(String uri, boolean sameClient) HttpResponse response = client.send(req, handler); String body = response.body(); Stream.of(body.split("\n")).forEach(u -> - assertEquals(URI.create(u).getPath(), URI.create(uri2).getPath())); + assertEquals(URI.create(uri2).getPath(), URI.create(u).getPath())); if (!sameClient) { // Wait for the client to be garbage collected. // we use the ReferenceTracker API rather than HttpClient::close here, @@ -419,7 +418,6 @@ private void testThrowing(String name, String uri, boolean sameClient, boolean async, EnumSet excludes) throws Exception { - checkSkip(); out.printf("%n%s%s%n", now(), name); try { testThrowing(uri, sameClient, handlers, finisher, thrower, async, excludes); @@ -498,7 +496,6 @@ private void testThrowing(String uri, boolean sameClient, if (error != null) throw error; System.out.println(now() + "operation finished normally: " + tracker.getName()); System.err.println(now() + "operation finished normally: " + tracker.getName()); - } } } @@ -758,8 +755,11 @@ public CompletionStage getBody() { } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { + System.out.println(now() + "setup"); + System.err.println(now() + "setup"); + sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); @@ -802,8 +802,11 @@ public void setup() throws Exception { https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + public static void teardown() throws Exception { + System.out.println(now() + "teardown"); + System.err.println(now() + "teardown"); + String sharedClientName = sharedClient == null ? null : sharedClient.toString(); sharedClient = null; diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java index 796c0b8df024..2c1aa2fd9b48 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersCustomAfterCancel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersCustomAfterCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersCustomAfterCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersCustomAfterCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "afterCancelProviderCustom") + @ParameterizedTest + @MethodSource("afterCancelProviderCustom") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java index 06343d222b8e..ba7341854647 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersCustomBeforeCancel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersCustomBeforeCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersCustomBeforeCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersCustomBeforeCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "beforeCancelProviderCustom") + @ParameterizedTest + @MethodSource("beforeCancelProviderCustom") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java index 7ed649b25463..a5e819942b44 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersIOAfterCancel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersIOAfterCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersIOAfterCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersIOAfterCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "afterCancelProviderIO") + @ParameterizedTest + @MethodSource("afterCancelProviderIO") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java b/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java index 3be2eb061cc4..e68f83052bde 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersIOBeforeCancel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersIOBeforeCancel * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersIOBeforeCancel */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersIOBeforeCancel extends AbstractThrowingPublishers { - @Test(dataProvider = "beforeCancelProviderIO") + @ParameterizedTest + @MethodSource("beforeCancelProviderIO") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java b/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java index eb07b359fc96..62d06fd60191 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInNextRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInNextRequest * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInNextRequest */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInNextRequest extends AbstractThrowingPublishers { - @Test(dataProvider = "nextRequestProvider") + @ParameterizedTest + @MethodSource("nextRequestProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java b/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java index ef05e4e0da6f..f863f3598edf 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInRequest * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInRequest */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInRequest extends AbstractThrowingPublishers { - @Test(dataProvider = "requestProvider") + @ParameterizedTest + @MethodSource("requestProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java b/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java index f14c51670247..ce1ad89dc056 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersInSubscribe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,18 +29,20 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersInSubscribe * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersInSubscribe */ -import org.testng.annotations.Test; import java.util.Set; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersInSubscribe extends AbstractThrowingPublishers { - @Test(dataProvider = "subscribeProvider") + @ParameterizedTest + @MethodSource("subscribeProvider") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower, Set whereValues) throws Exception diff --git a/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java b/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java index 305490833104..eee2f9ab7fb7 100644 --- a/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingPublishersSanity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,16 +29,18 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPublishers ThrowingPublishersSanity * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.enableAllMethodRetry=true * ThrowingPublishersSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPublishersSanity extends AbstractThrowingPublishers { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri,sameClient); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java index 0b66a8e913ec..797507ac7ada 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamCustom.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsInputStreamCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsInputStreamCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java index 89cf1162bc34..309f60c0f22f 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsInputStreamIO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsInputStreamIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsInputStreamIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsInputStreamIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java index d1fb7d342587..77c87151e194 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesCustom.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsLinesCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsLinesCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java index 88afaf3dbd55..69deeec533a9 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsLinesIO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsLinesIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsLinesIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsLinesIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java index c40af0ab0b06..de38cf4f7826 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringCustom.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsStringCustom * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringCustom + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringCustom */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsStringCustom extends AbstractThrowingPushPromises { - @Test(dataProvider = "customVariants") + @ParameterizedTest + @MethodSource("customVariants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java index 6485e82af8f5..ec4d682d73ff 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesAsStringIO.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesAsStringIO * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringIO + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesAsStringIO */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesAsStringIO extends AbstractThrowingPushPromises { - @Test(dataProvider = "ioVariants") + @ParameterizedTest + @MethodSource("ioVariants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java b/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java index 7fdb6dcb19db..92f2ab3726dd 100644 --- a/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingPushPromisesSanity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -30,14 +30,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker AbstractThrowingPushPromises ThrowingPushPromisesSanity * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesSanity + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingPushPromisesSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingPushPromisesSanity extends AbstractThrowingPushPromises { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri, sameClient); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java index 35ac1fd3f9c3..a4c0fc72004b 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsInputStream AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStream + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStream */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsInputStream extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsInputStream(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java index db25ebaca3e8..aec4641917cd 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsInputStreamAsync.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsInputStreamAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStreamAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsInputStreamAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsInputStreamAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsInputStreamAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsInputStreamAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java index f303ef12b54b..ba594166b725 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLines.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsLines AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLines + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLines */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLines extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsLines(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java index 2e1fc942a736..a76ff8824630 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsLinesAsync.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsLinesAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLinesAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsLinesAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsLinesAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsLinesAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsLinesAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java index 56e444f09c2b..ba5506750964 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsString.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsString AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsString + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsString */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsString extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsString(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java b/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java index 563fe39bd69b..304d98e69392 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersAsStringAsync.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersAsStringAsync AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsStringAsync + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersAsStringAsync */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersAsStringAsync extends AbstractThrowingSubscribers { - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") public void testThrowingAsStringAsync(String uri, boolean sameClient, Thrower thrower) throws Exception { super.testThrowingAsStringAsyncImpl(uri, sameClient, thrower); diff --git a/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java b/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java index c480d55e1479..296e9151c9ee 100644 --- a/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java +++ b/test/jdk/java/net/httpclient/ThrowingSubscribersSanity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -29,14 +29,16 @@ * @build jdk.test.lib.net.SimpleSSLContext * ReferenceTracker ThrowingSubscribersSanity AbstractThrowingSubscribers * jdk.httpclient.test.lib.common.HttpServerAdapters - * @run testng/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersSanity + * @run junit/othervm -Djdk.internal.httpclient.debug=true ThrowingSubscribersSanity */ -import org.testng.annotations.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class ThrowingSubscribersSanity extends AbstractThrowingSubscribers { - @Test(dataProvider = "sanity") + @ParameterizedTest + @MethodSource("sanity") public void testSanity(String uri, boolean sameClient) throws Exception { super.testSanityImpl(uri, sameClient); diff --git a/test/jdk/java/net/httpclient/http2/BadHeadersTest.java b/test/jdk/java/net/httpclient/http2/BadHeadersTest.java index 062b4c89e09b..12270d41818a 100644 --- a/test/jdk/java/net/httpclient/http2/BadHeadersTest.java +++ b/test/jdk/java/net/httpclient/http2/BadHeadersTest.java @@ -26,7 +26,7 @@ * @bug 8303965 * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext - * @run testng/othervm -Djdk.internal.httpclient.debug=true BadHeadersTest + * @run junit/othervm -Djdk.internal.httpclient.debug=true BadHeadersTest */ import jdk.internal.net.http.common.HttpHeadersBuilder; @@ -35,10 +35,10 @@ import jdk.internal.net.http.frame.HeadersFrame; import jdk.internal.net.http.frame.Http2Frame; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import java.io.IOException; @@ -57,6 +57,7 @@ import java.util.Map.Entry; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; + import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2TestExchangeImpl; @@ -65,8 +66,9 @@ import jdk.httpclient.test.lib.http2.Http2TestServerConnection; import static java.util.List.of; import static java.util.Map.entry; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; // Code copied from ContinuationFrameTest public class BadHeadersTest { @@ -79,11 +81,11 @@ public class BadHeadersTest { of(entry("hello", "world!"), entry(":status", "200")) // Pseudo header is not the first one ); - SSLContext sslContext; - Http2TestServer http2TestServer; // HTTP/2 ( h2c ) - Http2TestServer https2TestServer; // HTTP/2 ( h2 ) - String http2URI; - String https2URI; + private static SSLContext sslContext; + private static Http2TestServer http2TestServer; // HTTP/2 ( h2c ) + private static Http2TestServer https2TestServer; // HTTP/2 ( h2 ) + private static String http2URI; + private static String https2URI; /** * A function that returns a list of 1) a HEADERS frame ( with an empty @@ -121,8 +123,7 @@ public class BadHeadersTest { return frames; }; - @DataProvider(name = "variants") - public Object[][] variants() { + static Object[][] variants() { return new Object[][] { { http2URI, false, oneContinuation }, { https2URI, false, oneContinuation }, @@ -136,8 +137,8 @@ public Object[][] variants() { }; } - - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") void test(String uri, boolean sameClient, BiFunction,List> headerFramesSupplier) @@ -166,7 +167,8 @@ void test(String uri, } } - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") void testAsync(String uri, boolean sameClient, BiFunction,List> headerFramesSupplier) @@ -204,8 +206,7 @@ void testAsync(String uri, // sync with implementation. static void assertDetailMessage(Throwable throwable, int iterationIndex) { try { - assertTrue(throwable instanceof IOException, - "Expected IOException, got, " + throwable); + assertInstanceOf(IOException.class, throwable, "Expected IOException, got " + throwable); assertTrue(throwable.getMessage().contains("malformed response"), "Expected \"malformed response\" in: " + throwable.getMessage()); @@ -226,8 +227,8 @@ static void assertDetailMessage(Throwable throwable, int iterationIndex) { } } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); @@ -251,8 +252,8 @@ public void setup() throws Exception { https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + static void teardown() throws Exception { http2TestServer.stop(); https2TestServer.stop(); } diff --git a/test/jdk/java/net/httpclient/http2/BasicTest.java b/test/jdk/java/net/httpclient/http2/BasicTest.java index 9d54c8c39e0b..0c64be84926c 100644 --- a/test/jdk/java/net/httpclient/http2/BasicTest.java +++ b/test/jdk/java/net/httpclient/http2/BasicTest.java @@ -32,7 +32,7 @@ * jdk.test.lib.Asserts * jdk.test.lib.Utils * jdk.test.lib.net.SimpleSSLContext - * @run testng/othervm -Djdk.httpclient.HttpClient.log=ssl,requests,responses,errors BasicTest + * @run junit/othervm -Djdk.httpclient.HttpClient.log=ssl,requests,responses,errors BasicTest */ import java.io.IOException; @@ -53,14 +53,13 @@ import jdk.httpclient.test.lib.http2.Http2TestExchange; import jdk.httpclient.test.lib.http2.Http2EchoHandler; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; import static java.net.http.HttpClient.Version.HTTP_2; import static jdk.test.lib.Asserts.assertFileContentsEqual; import static jdk.test.lib.Utils.createTempFile; import static jdk.test.lib.Utils.createTempFileOfSize; -@Test public class BasicTest { private static final String TEMP_FILE_PREFIX = @@ -127,7 +126,7 @@ public void handle(Http2TestExchange exchange) throws IOException { } @Test - public static void test() throws Exception { + void test() throws Exception { try { initialize(); warmup(false); diff --git a/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java b/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java index 30cc9122d9dc..1eaf331c2610 100644 --- a/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java +++ b/test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java @@ -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 @@ -27,7 +27,7 @@ * @summary checks connection flow control * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext - * @run testng/othervm -Djdk.internal.httpclient.debug=true + * @run junit/othervm -Djdk.internal.httpclient.debug=true * -Djdk.httpclient.connectionWindowSize=65535 * -Djdk.httpclient.windowsize=16384 * ConnectionFlowControlTest @@ -43,23 +43,13 @@ import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; -import java.net.http.HttpResponse.BodyHandler; import java.net.http.HttpResponse.BodyHandlers; -import java.net.http.HttpResponse.BodySubscriber; -import java.net.http.HttpResponse.ResponseInfo; -import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; -import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; -import java.util.concurrent.Flow.Subscription; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiFunction; import java.util.function.Consumer; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; @@ -72,44 +62,34 @@ import jdk.httpclient.test.lib.http2.Http2TestServer; import jdk.httpclient.test.lib.http2.Http2TestServerConnection; import jdk.internal.net.http.common.HttpHeadersBuilder; -import jdk.internal.net.http.frame.ContinuationFrame; -import jdk.internal.net.http.frame.HeaderFrame; -import jdk.internal.net.http.frame.HeadersFrame; -import jdk.internal.net.http.frame.Http2Frame; import jdk.internal.net.http.frame.SettingsFrame; import jdk.test.lib.Utils; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import static java.util.List.of; -import static java.util.Map.entry; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ConnectionFlowControlTest { - SSLContext sslContext; - HttpTestServer http2TestServer; // HTTP/2 ( h2c ) - HttpTestServer https2TestServer; // HTTP/2 ( h2 ) - String http2URI; - String https2URI; - final AtomicInteger reqid = new AtomicInteger(); + private static SSLContext sslContext; + private static HttpTestServer http2TestServer; // HTTP/2 ( h2c ) + private static HttpTestServer https2TestServer; // HTTP/2 ( h2 ) + private static String http2URI; + private static String https2URI; + private final AtomicInteger reqid = new AtomicInteger(); - - @DataProvider(name = "variants") - public Object[][] variants() { + static Object[][] variants() { return new Object[][] { { http2URI }, { https2URI }, }; } - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") void test(String uri) throws Exception { System.out.printf("%ntesting %s%n", uri); ConcurrentHashMap> responseSent = new ConcurrentHashMap<>(); @@ -148,7 +128,7 @@ void test(String uri) throws Exception { if (i < max - 1) { // the connection window might be exceeded at i == max - 2, which // means that the last request could go on a new connection. - assertEquals(ckey, label, "Unexpected key for " + query); + assertEquals(label, ckey, "Unexpected key for " + query); } } catch (AssertionError ass) { // since we won't pull all responses, the client @@ -174,7 +154,7 @@ void test(String uri) throws Exception { if (i < max - 1) { // the connection window might be exceeded at i == max - 2, which // means that the last request could go on a new connection. - assertEquals(ckey, label, "Unexpected key for " + query); + assertEquals(label, ckey, "Unexpected key for " + query); } int wait = uri.startsWith("https://") ? 500 : 250; try (InputStream is = response.body()) { @@ -227,7 +207,7 @@ void test(String uri) throws Exception { var response = client.send(request, BodyHandlers.ofString()); if (label != null) { String ckey = response.headers().firstValue("X-Connection-Key").get(); - assertNotEquals(ckey, label); + assertNotEquals(label, ckey); System.out.printf("last request %s sent on different connection as expected:" + "\n\tlast: %s\n\tprevious: %s%n", query, ckey, label); } @@ -258,33 +238,33 @@ static void assertDetailMessage(Throwable throwable, int iterationIndex) { } } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); - var http2TestServer = new Http2TestServer("localhost", false, 0); - http2TestServer.addHandler(new Http2TestHandler(), "/http2/"); - this.http2TestServer = HttpTestServer.of(http2TestServer); - http2URI = "http://" + this.http2TestServer.serverAuthority() + "/http2/x"; + var http2TestServerLocal = new Http2TestServer("localhost", false, 0); + http2TestServerLocal.addHandler(new Http2TestHandler(), "/http2/"); + http2TestServer = HttpTestServer.of(http2TestServerLocal); + http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/x"; - var https2TestServer = new Http2TestServer("localhost", true, sslContext); - https2TestServer.addHandler(new Http2TestHandler(), "/https2/"); - this.https2TestServer = HttpTestServer.of(https2TestServer); - https2URI = "https://" + this.https2TestServer.serverAuthority() + "/https2/x"; + var https2TestServerLocal = new Http2TestServer("localhost", true, sslContext); + https2TestServerLocal.addHandler(new Http2TestHandler(), "/https2/"); + https2TestServer = HttpTestServer.of(https2TestServerLocal); + https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/x"; // Override the default exchange supplier with a custom one to enable // particular test scenarios - http2TestServer.setExchangeSupplier(FCHttp2TestExchange::new); - https2TestServer.setExchangeSupplier(FCHttp2TestExchange::new); + http2TestServerLocal.setExchangeSupplier(FCHttp2TestExchange::new); + https2TestServerLocal.setExchangeSupplier(FCHttp2TestExchange::new); - this.http2TestServer.start(); - this.https2TestServer.start(); + http2TestServer.start(); + https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + static void teardown() throws Exception { http2TestServer.stop(); https2TestServer.stop(); } @@ -364,6 +344,5 @@ public void responseSent(String query) { System.out.println("Server: response sent for " + query); responseSentCB.accept(query); } - } } diff --git a/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java b/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java index 04ce8f4f4a41..22b7f414126d 100644 --- a/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java +++ b/test/jdk/java/net/httpclient/http2/ContinuationFrameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2023, 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 @@ -27,7 +27,7 @@ * @library /test/lib /test/jdk/java/net/httpclient/lib * @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext * @compile ../ReferenceTracker.java - * @run testng/othervm ContinuationFrameTest + * @run junit/othervm ContinuationFrameTest */ import java.io.IOException; @@ -59,25 +59,24 @@ import jdk.httpclient.test.lib.http2.Http2TestServerConnection; import jdk.test.lib.net.SimpleSSLContext; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import static java.lang.System.out; import static java.net.http.HttpClient.Version.HTTP_2; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ContinuationFrameTest { - SSLContext sslContext; - Http2TestServer http2TestServer; // HTTP/2 ( h2c ) - Http2TestServer https2TestServer; // HTTP/2 ( h2 ) - String http2URI; - String https2URI; - String noBodyhttp2URI; - String noBodyhttps2URI; - final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; + private static SSLContext sslContext; + private static Http2TestServer http2TestServer; // HTTP/2 ( h2c ) + private static Http2TestServer https2TestServer; // HTTP/2 ( h2 ) + private static String http2URI; + private static String https2URI; + private static String noBodyhttp2URI; + private static String noBodyhttps2URI; + private final static ReferenceTracker TRACKER = ReferenceTracker.INSTANCE; /** * A function that returns a list of 1) a HEADERS frame ( with an empty @@ -132,8 +131,7 @@ public class ContinuationFrameTest { return frames; }; - @DataProvider(name = "variants") - public Object[][] variants() { + static Object[][] variants() { return new Object[][] { { http2URI, false, oneContinuation }, { https2URI, false, oneContinuation }, @@ -154,7 +152,8 @@ public Object[][] variants() { static final int ITERATION_COUNT = 20; - @Test(dataProvider = "variants") + @ParameterizedTest + @MethodSource("variants") void test(String uri, boolean sameClient, BiFunction,List> headerFramesSupplier) @@ -184,22 +183,20 @@ void test(String uri, if(uri.contains("nobody")) { out.println("Got response: " + resp); - assertTrue(resp.statusCode() == 204, - "Expected 204, got:" + resp.statusCode()); - assertEquals(resp.version(), HTTP_2); + assertEquals(204, resp.statusCode(), "Expected 204, got:" + resp.statusCode()); + assertEquals(HTTP_2, resp.version()); continue; } out.println("Got response: " + resp); out.println("Got body: " + resp.body()); - assertTrue(resp.statusCode() == 200, - "Expected 200, got:" + resp.statusCode()); - assertEquals(resp.body(), "Hello there!"); - assertEquals(resp.version(), HTTP_2); + assertEquals(200, resp.statusCode(), "Expected 200, got:" + resp.statusCode()); + assertEquals("Hello there!", resp.body()); + assertEquals(HTTP_2, resp.version()); } } - @BeforeTest - public void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { sslContext = new SimpleSSLContext().get(); if (sslContext == null) throw new AssertionError("Unexpected null sslContext"); @@ -227,8 +224,8 @@ public void setup() throws Exception { https2TestServer.start(); } - @AfterTest - public void teardown() throws Exception { + @AfterAll + static void teardown() throws Exception { AssertionError fail = TRACKER.check(500); try { http2TestServer.stop(); diff --git a/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java b/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java index 176634d69077..5df14bff9d28 100644 --- a/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java +++ b/test/jdk/java/net/httpclient/websocket/DummyWebSocketServer.java @@ -265,7 +265,14 @@ URI getURI() { if (!started.get()) { throw new IllegalStateException("Not yet started"); } - return URI.create("ws://localhost:" + address.getPort()); + String ip = address.getAddress().isAnyLocalAddress() + ? InetAddress.getLoopbackAddress().getHostAddress() + : address.getAddress().getHostAddress(); + if (ip.indexOf(':') >= 0) { + ip = String.format("[%s]", ip); + } + + return URI.create("ws://" + ip + ":" + address.getPort()); } private boolean readRequest(SocketChannel channel, StringBuilder request) diff --git a/test/jdk/java/net/httpclient/whitebox/RawChannelTestDriver.java b/test/jdk/java/net/httpclient/whitebox/RawChannelTestDriver.java index 77b1c3db8a53..6ca6fe47b59c 100644 --- a/test/jdk/java/net/httpclient/whitebox/RawChannelTestDriver.java +++ b/test/jdk/java/net/httpclient/whitebox/RawChannelTestDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -25,7 +25,12 @@ * @test * @bug 8151299 8164704 * @modules java.net.http/jdk.internal.net.http - * @run testng java.net.http/jdk.internal.net.http.RawChannelTest + * @run testng/othervm java.net.http/jdk.internal.net.http.RawChannelTest */ +// use +// @run testng/othervm -Dseed=6434511950803022575 +// java.net.http/jdk.internal.net.http.RawChannelTest +// to reproduce a failure with a particular seed (e.g. 6434511950803022575) +// if this test is observed failing with that seed //-Djdk.internal.httpclient.websocket.debug=true diff --git a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java index 6619eff008a0..01aafd916dd4 100644 --- a/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java +++ b/test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/RawChannelTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -23,6 +23,7 @@ package jdk.internal.net.http; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -43,8 +44,9 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.util.concurrent.atomic.AtomicReference; + import jdk.internal.net.http.websocket.RawChannel; -import jdk.internal.net.http.websocket.WebSocketRequest; import org.testng.annotations.Test; import static java.net.http.HttpResponse.BodyHandlers.discarding; import static java.util.concurrent.TimeUnit.SECONDS; @@ -57,6 +59,20 @@ */ public class RawChannelTest { + // can't use jdk.test.lib when injected in java.net.httpclient + // Seed can be specified on the @run line with -Dseed= + private static class RandomFactory { + private static long getSeed() { + long seed = Long.getLong("seed", new Random().nextLong()); + System.out.println("Seed from RandomFactory = "+seed+"L"); + return seed; + } + public static Random getRandom() { + return new Random(getSeed()); + } + } + + private static final Random RANDOM = RandomFactory.getRandom(); private final AtomicLong clientWritten = new AtomicLong(); private final AtomicLong serverWritten = new AtomicLong(); private final AtomicLong clientRead = new AtomicLong(); @@ -90,7 +106,8 @@ public void test() throws Exception { server.setReuseAddress(false); server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0)); int port = server.getLocalPort(); - new TestServer(server).start(); + TestServer testServer = new TestServer(server); + testServer.start(); final RawChannel chan = channelOf(port); print("RawChannel is %s", String.valueOf(chan)); @@ -129,6 +146,7 @@ public void handle() { } catch (IOException e) { outputCompleted.completeExceptionally(e); e.printStackTrace(); + closeChannel(chan); } return; } @@ -145,6 +163,9 @@ public void handle() { chan.registerEvent(this); writeStall.countDown(); // signal send buffer is full } catch (IOException e) { + print("OP_WRITE failed: " + e); + outputCompleted.completeExceptionally(e); + closeChannel(chan); throw new UncheckedIOException(e); } } @@ -168,6 +189,7 @@ public void handle() { read = chan.read(); } catch (IOException e) { inputCompleted.completeExceptionally(e); + closeChannel(chan); e.printStackTrace(); } if (read == null) { @@ -179,7 +201,10 @@ public void handle() { try { chan.registerEvent(this); } catch (IOException e) { - e.printStackTrace(); + print("OP_READ failed to register event: " + e); + inputCompleted.completeExceptionally(e); + closeChannel(chan); + throw new UncheckedIOException(e); } readStall.countDown(); break; @@ -191,21 +216,33 @@ public void handle() { print("OP_READ read %s bytes (%s total)", total, clientRead.get()); } }); + CompletableFuture.allOf(outputCompleted,inputCompleted) .whenComplete((r,t) -> { - try { - print("closing channel"); - chan.close(); - } catch (IOException x) { - x.printStackTrace(); - } + closeChannel(chan); }); exit.await(); // All done, we need to compare results: assertEquals(clientRead.get(), serverWritten.get()); assertEquals(serverRead.get(), clientWritten.get()); + Throwable serverError = testServer.failed.get(); + if (serverError != null) { + throw new AssertionError("TestServer failed: " + + serverError, serverError); + } } } + private static void closeChannel(RawChannel chan) { + print("closing channel"); + try { + chan.close(); + } catch (IOException x) { + print("Failed to close channel: " + x); + x.printStackTrace(); + } + } + + private static RawChannel channelOf(int port) throws Exception { URI uri = URI.create("http://localhost:" + port + "/"); print("raw channel to %s", uri.toString()); @@ -238,11 +275,24 @@ private static RawChannel channelOf(int port) throws Exception { private class TestServer extends Thread { // Powered by Slowpokes private final ServerSocket server; + private final AtomicReference failed = new AtomicReference<>(); TestServer(ServerSocket server) throws IOException { this.server = server; } + private void fail(Closeable s, String actor, Throwable t) { + failed.compareAndSet(null, t); + print("Server %s got exception: %s", actor, t); + t.printStackTrace(); + try { + s.close(); + } catch (Exception x) { + print("Server %s failed to close socket: %s", actor, t); + } + + } + @Override public void run() { try (Socket s = server.accept()) { @@ -253,21 +303,23 @@ public void run() { Thread reader = new Thread(() -> { try { + print("Server reader started"); long n = readSlowly(is); print("Server read %s bytes", n); s.shutdownInput(); } catch (Exception e) { - e.printStackTrace(); + fail(s, "reader", e); } }); Thread writer = new Thread(() -> { try { + print("Server writer started"); long n = writeSlowly(os); print("Server written %s bytes", n); s.shutdownOutput(); } catch (Exception e) { - e.printStackTrace(); + fail(s, "writer", e); } }); @@ -277,7 +329,7 @@ public void run() { reader.join(); writer.join(); } catch (Exception e) { - e.printStackTrace(); + fail(server,"acceptor", e); } finally { exit.countDown(); } @@ -366,6 +418,8 @@ private static void print(String format, Object... args) { } private static byte[] byteArrayOfSize(int bound) { - return new byte[new Random().nextInt(1 + bound)]; + // bound must be > 1; No need to check it, + // nextInt will throw IllegalArgumentException if needed + return new byte[RANDOM.nextInt(1, bound + 1)]; } } diff --git a/test/jdk/java/nio/Buffer/LimitDirectMemory.java b/test/jdk/java/nio/Buffer/LimitDirectMemory.java index 2116a20748dd..353044bc454a 100644 --- a/test/jdk/java/nio/Buffer/LimitDirectMemory.java +++ b/test/jdk/java/nio/Buffer/LimitDirectMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -25,7 +25,6 @@ * @test * @bug 4627316 6743526 * @summary Test option to limit direct memory allocation - * @requires (os.arch == "x86_64") | (os.arch == "amd64") | (os.arch == "aarch64") * @library /test/lib * * @summary Test: memory is properly limited using multiple buffers diff --git a/test/jdk/java/nio/Buffer/LimitDirectMemoryNegativeTest.java b/test/jdk/java/nio/Buffer/LimitDirectMemoryNegativeTest.java index 0d6666cc2e39..9b0fc9fec0d8 100644 --- a/test/jdk/java/nio/Buffer/LimitDirectMemoryNegativeTest.java +++ b/test/jdk/java/nio/Buffer/LimitDirectMemoryNegativeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, 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 @@ -26,7 +26,6 @@ * @bug 4627316 6743526 * @summary Test option to limit direct memory allocation, * various bad values fail to launch the VM - * @requires (os.arch == "x86_64") | (os.arch == "amd64") * @library /test/lib * @build jdk.test.lib.Utils * jdk.test.lib.Asserts diff --git a/test/jdk/java/nio/channels/AsynchronousSocketChannel/CompletionHandlerRelease.java b/test/jdk/java/nio/channels/AsynchronousSocketChannel/CompletionHandlerRelease.java index 7abbf064b403..962d7728a551 100644 --- a/test/jdk/java/nio/channels/AsynchronousSocketChannel/CompletionHandlerRelease.java +++ b/test/jdk/java/nio/channels/AsynchronousSocketChannel/CompletionHandlerRelease.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. * 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,7 @@ /* @test * @bug 8202252 - * @run testng CompletionHandlerRelease + * @run junit CompletionHandlerRelease * @summary Verify that reference to CompletionHandler is cleared after use */ @@ -44,10 +44,12 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; public class CompletionHandlerRelease { @Test @@ -132,16 +134,16 @@ public void testRead() throws Exception { } } - private AsynchronousChannelGroup GROUP; + private static AsynchronousChannelGroup GROUP; - @BeforeTest - void setup() throws IOException { + @BeforeAll + static void setup() throws IOException { GROUP = AsynchronousChannelGroup.withFixedThreadPool(2, Executors.defaultThreadFactory()); } - @AfterTest - void cleanup() throws IOException { + @AfterAll + static void cleanup() throws IOException { GROUP.shutdownNow(); } @@ -199,13 +201,13 @@ public void failed(Throwable exc, A attachment) { } } - private void waitForRefToClear(Reference ref, ReferenceQueue queue) + private static void waitForRefToClear(Reference ref, ReferenceQueue queue) throws InterruptedException { Reference r; while ((r = queue.remove(20)) == null) { System.gc(); } - assertEquals(r, ref); + assertSame(ref, r); assertNull(r.get()); } } diff --git a/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java b/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java index f50d1345b4db..130e32ac3791 100644 --- a/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java +++ b/test/jdk/java/nio/channels/spi/SelectorProvider/inheritedChannel/InheritedChannelTest.java @@ -40,7 +40,6 @@ * @key intermittent */ -import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -99,7 +98,7 @@ public Object[][] testCases() { }; } - @Test(dataProvider = "testCases", timeOut=30000) + @Test(dataProvider = "testCases") public void test(String desc, List opts) throws Throwable { String pathVar = Platform.sharedLibraryPathVariableName(); System.out.println(pathVar + "=" + libraryPath); diff --git a/test/jdk/java/nio/file/spi/fs.policy b/test/jdk/java/nio/file/spi/fs.policy index 15032c70ba8d..0dcfe8b2789a 100644 --- a/test/jdk/java/nio/file/spi/fs.policy +++ b/test/jdk/java/nio/file/spi/fs.policy @@ -1,3 +1,3 @@ grant codeBase "file:${test.classes}${/}-" { - permission java.io.FilePermission "${java.io.tmpdir}${/}-", "write"; + permission java.io.FilePermission "${user.dir}${/}-", "write"; }; diff --git a/test/jdk/java/nio/file/spi/m/p/Main.java b/test/jdk/java/nio/file/spi/m/p/Main.java index 4704c6790216..9f80d08347c4 100644 --- a/test/jdk/java/nio/file/spi/m/p/Main.java +++ b/test/jdk/java/nio/file/spi/m/p/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * 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 static void main(String[] args) throws Exception { throw new RuntimeException("FileSystemProvider not overridden"); // exercise the file system - Path dir = Files.createTempDirectory("tmp"); + Path dir = Files.createTempDirectory(Path.of(""), "tmp"); if (dir.getFileSystem() != fs) throw new RuntimeException("'dir' not in default file system"); System.out.println("created: " + dir); diff --git a/test/jdk/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java b/test/jdk/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java index 4de6598a0f46..f40502601d27 100644 --- a/test/jdk/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java +++ b/test/jdk/java/rmi/transport/checkLeaseInfoLeak/CheckLeaseLeak.java @@ -59,10 +59,13 @@ import java.lang.reflect.*; import java.rmi.registry.*; import sun.rmi.transport.*; +import java.util.concurrent.CountDownLatch; public class CheckLeaseLeak extends UnicastRemoteObject implements LeaseLeak { public CheckLeaseLeak() throws RemoteException { } - public void ping () throws RemoteException { } + public void ping () throws RemoteException { + remoteCallsComplete.countDown(); + } /** * Id to fake the DGC_ID, so we can later get a reference to the @@ -74,6 +77,9 @@ public void ping () throws RemoteException { } private final static int numberPingCalls = 0; private final static int CHECK_INTERVAL = 400; private final static int LEASE_VALUE = 20; + private static final int NO_OF_CLIENTS = ITERATIONS; + private static final int GOOD_LUCK_FACTOR = 2; + private static CountDownLatch remoteCallsComplete = new CountDownLatch(NO_OF_CLIENTS); public static void main (String[] args) { CheckLeaseLeak leakServer = null; @@ -113,8 +119,14 @@ public static void main (String[] args) { jvm.destroy(); } } + try { + remoteCallsComplete.await(); + System.out.println("remoteCallsComplete . . . "); + } catch (InterruptedException intEx) { + System.out.println("remoteCallsComplete.await interrupted . . . "); + } + Thread.sleep(NO_OF_CLIENTS * LEASE_VALUE * GOOD_LUCK_FACTOR); numLeft = getDGCLeaseTableSize(); - Thread.sleep(3000); } catch(Exception e) { TestLibrary.bomb("CheckLeaseLeak Error: ", e); @@ -125,8 +137,8 @@ public static void main (String[] args) { } } - /* numLeft should be 4 - if 11 there is a problem. */ - if (numLeft > 4) { + /* numLeft should not be greater than 2 - if 11 there is a problem. */ + if (numLeft > 2) { TestLibrary.bomb("Too many objects in DGCImpl.leaseTable: "+ numLeft); } else { @@ -204,8 +216,9 @@ private static int getDGCLeaseTableSize () { * objects if the LeaseInfo memory leak is not fixed. */ leaseTable = (Map) f.get(dgcImpl[0]); - - numLeaseInfosLeft = leaseTable.size(); + synchronized (leaseTable) { + numLeaseInfosLeft = leaseTable.size(); + } } catch(Exception e) { TestLibrary.bomb(e); diff --git a/test/jdk/java/security/KeyStore/DisabledKnownType.java b/test/jdk/java/security/KeyStore/DisabledKnownType.java new file mode 100644 index 000000000000..70b7228f4c2e --- /dev/null +++ b/test/jdk/java/security/KeyStore/DisabledKnownType.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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 8373690 + * @summary verify that the exception message indicates the keystore type + * when the type is disabled instead of being unrecognized + * @run main/othervm -Djdk.crypto.disabledAlgorithms=KeyStore.PKCS12 DisabledKnownType + */ + +import java.security.KeyStore; +import java.security.KeyStoreException; + +public class DisabledKnownType { + public static void main(String[] args) throws Exception { + String cacertsPath = System.getProperty("java.home") + + "/lib/security/cacerts"; + try { + KeyStore ks = KeyStore.getInstance(new java.io.File(cacertsPath), + "changeit".toCharArray()); + throw new RuntimeException("Expected KeyStoreException not thrown"); + } catch (KeyStoreException kse) { + if (kse.getMessage().contains("PKCS12")) { + System.out.println("Passed: expected ex thrown: " + kse); + } else { + // pass it up + throw kse; + } + } + } +} + diff --git a/test/jdk/java/security/Provider/NewInstance.java b/test/jdk/java/security/Provider/NewInstance.java index ad69f468925c..547b9111682b 100644 --- a/test/jdk/java/security/Provider/NewInstance.java +++ b/test/jdk/java/security/Provider/NewInstance.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -26,21 +26,34 @@ * @bug 8039853 * @summary Provider.Service.newInstance() does not work with current JDK JGSS Mechanisms + * @library /test/lib */ -import java.security.*; -import java.util.*; + +import jtreg.SkippedException; + +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; public class NewInstance { public static void main(String[] args) throws Exception { - for (Provider p : Security.getProviders()) { + + System.out.println("Removing SunPCSC provider from the list (A smartcard might not be installed)."); + final List providers = Arrays.stream(Security.getProviders()) + .filter(provider -> !provider.getName().equals("SunPCSC")) + .collect(Collectors.toList()); + + for (Provider p : providers) { System.out.println("---------"); System.out.println(p.getName() + ":" + p.getInfo()); - if (p.getName().equals("SunPCSC")) { - System.out.println("A smartcard might not be installed. Skip test."); - continue; - } Set set = p.getServices(); Iterator i = set.iterator(); diff --git a/test/jdk/java/security/cert/CertStore/NoLDAP.java b/test/jdk/java/security/cert/CertStore/NoLDAP.java index 868411e63c45..812a978931d9 100644 --- a/test/jdk/java/security/cert/CertStore/NoLDAP.java +++ b/test/jdk/java/security/cert/CertStore/NoLDAP.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -25,20 +25,23 @@ * @bug 8004502 * @summary Sanity check that NoSuchAlgorithmException is thrown when requesting * a CertStore of type "LDAP" and LDAP is not available. + * @library /test/lib */ import java.security.NoSuchAlgorithmException; import java.security.cert.CertStore; import java.security.cert.LDAPCertStoreParameters; +import jtreg.SkippedException; public class NoLDAP { public static void main(String[] args) throws Exception { try { Class.forName("javax.naming.ldap.LdapName"); - System.out.println("LDAP is present, test skipped"); - return; - } catch (ClassNotFoundException ignore) { } + throw new SkippedException("LDAP is present"); + } catch (ClassNotFoundException ignore) { + System.err.println("Expected: class not found exception " + ignore.getMessage()); + } try { CertStore.getInstance("LDAP", new LDAPCertStoreParameters()); diff --git a/test/jdk/java/text/Collator/RuleBasedCollatorTest.java b/test/jdk/java/text/Collator/RuleBasedCollatorTest.java index 429768b6bf1b..cd1e8ca69c00 100644 --- a/test/jdk/java/text/Collator/RuleBasedCollatorTest.java +++ b/test/jdk/java/text/Collator/RuleBasedCollatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -26,40 +26,45 @@ * @bug 4406815 8222969 8266784 * @summary RuleBasedCollatorTest uses very limited but selected test data * to test basic functionalities provided by RuleBasedCollator. - * @run testng/othervm RuleBasedCollatorTest + * @run junit/othervm RuleBasedCollatorTest */ +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.CollationElementIterator; import java.text.CollationKey; -import java.text.RuleBasedCollator; import java.text.Collator; import java.text.ParseException; +import java.text.RuleBasedCollator; import java.util.Arrays; import java.util.Locale; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import org.testng.SkipException; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class RuleBasedCollatorTest { - static RuleBasedCollator USC; - static String US_RULES; + private static RuleBasedCollator USC; + private static String US_RULES; - @BeforeClass - public void setup() { + @BeforeAll + void setup() { Collator c = Collator.getInstance(Locale.US); - if (!(c instanceof RuleBasedCollator)) { - throw new SkipException("skip tests."); - } + assumeFalse(!(c instanceof RuleBasedCollator), "skip tests."); USC = (RuleBasedCollator) c; US_RULES = USC.getRules(); } - @DataProvider(name = "rulesData") Object[][] rulesData() { //Basic Tailor String BASIC_TAILOR_RULES = "< b=c<\u00e6;A,a"; @@ -91,15 +96,15 @@ Object[][] rulesData() { }; } - @Test(dataProvider = "rulesData") - public void testRules(String rules, String[] testData, String[] expected) + @ParameterizedTest + @MethodSource("rulesData") + void testRules(String rules, String[] testData, String[] expected) throws ParseException { Arrays.sort(testData, new RuleBasedCollator(rules)); - assertEquals(testData, expected); + assertArrayEquals(expected, testData); } - @DataProvider(name = "FrenchSecondarySort") Object[][] FrenchSecondarySort() { return new Object[][] { { "\u0061\u00e1\u0061", "\u00e1\u0061\u0061", 1 }, @@ -111,8 +116,9 @@ Object[][] FrenchSecondarySort() { { "a", "\u1ea1", -1 } }; } - @Test(dataProvider = "FrenchSecondarySort") - public void testFrenchSecondarySort(String sData, String tData, + @ParameterizedTest + @MethodSource("FrenchSecondarySort") + void testFrenchSecondarySort(String sData, String tData, int expected) throws ParseException { String french_rule = "@"; String rules = US_RULES + french_rule; @@ -121,7 +127,6 @@ public void testFrenchSecondarySort(String sData, String tData, assertEquals(expected, result); } - @DataProvider(name = "ThaiLaoVowelConsonantSwapping") Object[][] ThaiLaoVowelConsonantSwapping() { return new Object[][] {{"\u0e44\u0e01", "\u0e40\u0e2e", -1},//swap {"\u0e2e\u0e40", "\u0e01\u0e44", 1},//no swap @@ -129,8 +134,9 @@ Object[][] ThaiLaoVowelConsonantSwapping() { }; } - @Test(dataProvider = "ThaiLaoVowelConsonantSwapping") - public void testThaiLaoVowelConsonantSwapping(String sData, String tData, + @ParameterizedTest + @MethodSource("ThaiLaoVowelConsonantSwapping") + void testThaiLaoVowelConsonantSwapping(String sData, String tData, int expected) throws ParseException { String thai_rule = "& Z < \u0e01 < \u0e2e <\u0e40 < \u0e44!"; String rules = US_RULES + thai_rule; @@ -140,16 +146,15 @@ public void testThaiLaoVowelConsonantSwapping(String sData, String tData, } @Test - public void testIgnorableCharacter() throws ParseException { + void testIgnorableCharacter() throws ParseException { String rule = "=f new RuleBasedCollator(rule)); } - @Test(expectedExceptions = NullPointerException.class) - public void testNullParseException() throws ParseException{ - new RuleBasedCollator(null); + @Test + void testNullParseException() { + assertThrows(NullPointerException.class, () -> new RuleBasedCollator(null)); } } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/CompactFormatAndParseHelper.java b/test/jdk/java/text/Format/CompactNumberFormat/CompactFormatAndParseHelper.java index 3f3f1932e51e..4d410f97b5d9 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/CompactFormatAndParseHelper.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/CompactFormatAndParseHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, 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 @@ -24,14 +24,15 @@ import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; -import static org.testng.Assert.assertEquals; + +import static org.junit.jupiter.api.Assertions.assertEquals; class CompactFormatAndParseHelper { static void testFormat(NumberFormat cnf, Object number, String expected) { String result = cnf.format(number); - assertEquals(result, expected, "Incorrect formatting of the number '" + assertEquals(expected, result, "Incorrect formatting of the number '" + number + "'"); } @@ -46,11 +47,11 @@ static void testParse(NumberFormat cnf, String parseString, } if (returnType != null) { - assertEquals(number.getClass(), returnType, + assertEquals(returnType, number.getClass(), "Incorrect return type for string '" + parseString + "'"); } - assertEquals(number, expected, "Incorrect parsing of the string '" + assertEquals(expected, number, "Incorrect parsing of the string '" + parseString + "'"); } } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestCNFRounding.java b/test/jdk/java/text/Format/CompactNumberFormat/TestCNFRounding.java index b4dddfa1df77..0ba9587a3443 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestCNFRounding.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestCNFRounding.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -20,21 +20,28 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 * @summary Checks the rounding of formatted number in compact number formatting - * @run testng/othervm TestCNFRounding + * @run junit/othervm TestCNFRounding */ +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.RoundingMode; import java.text.NumberFormat; import java.util.List; import java.util.Locale; -import static org.testng.Assert.*; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestCNFRounding { private static final List MODES = List.of( @@ -46,7 +53,6 @@ public class TestCNFRounding { RoundingMode.CEILING, RoundingMode.FLOOR); - @DataProvider(name = "roundingData") Object[][] roundingData() { return new Object[][]{ // Number, half_even, half_up, half_down, up, down, ceiling, floor @@ -70,7 +76,6 @@ Object[][] roundingData() { {-4500, new String[]{"-4K", "-5K", "-4K", "-5K", "-4K", "-4K", "-5K"}},}; } - @DataProvider(name = "roundingFract") Object[][] roundingFract() { return new Object[][]{ // Number, half_even, half_up, half_down, up, down, ceiling, floor @@ -94,7 +99,6 @@ Object[][] roundingFract() { {-4500, new String[]{"-4.5K", "-4.5K", "-4.5K", "-4.5K", "-4.5K", "-4.5K", "-4.5K"}},}; } - @DataProvider(name = "rounding2Fract") Object[][] rounding2Fract() { return new Object[][]{ // Number, half_even, half_up, half_down @@ -118,37 +122,42 @@ Object[][] rounding2Fract() { {4686, new String[]{"4.69K", "4.69K", "4.69K"}},}; } - @Test(expectedExceptions = NullPointerException.class) - public void testNullMode() { - NumberFormat fmt = NumberFormat - .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); - fmt.setRoundingMode(null); + @Test + void testNullMode() { + assertThrows(NullPointerException.class, () -> { + NumberFormat fmt = NumberFormat + .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); + fmt.setRoundingMode(null); + }); } @Test - public void testDefaultRoundingMode() { + void testDefaultRoundingMode() { NumberFormat fmt = NumberFormat .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); - assertEquals(fmt.getRoundingMode(), RoundingMode.HALF_EVEN, + assertEquals(RoundingMode.HALF_EVEN, fmt.getRoundingMode(), "Default RoundingMode should be " + RoundingMode.HALF_EVEN); } - @Test(dataProvider = "roundingData") - public void testRounding(Object number, String[] expected) { + @ParameterizedTest + @MethodSource("roundingData") + void testRounding(Object number, String[] expected) { for (int index = 0; index < MODES.size(); index++) { testRoundingMode(number, expected[index], 0, MODES.get(index)); } } - @Test(dataProvider = "roundingFract") - public void testRoundingFract(Object number, String[] expected) { + @ParameterizedTest + @MethodSource("roundingFract") + void testRoundingFract(Object number, String[] expected) { for (int index = 0; index < MODES.size(); index++) { testRoundingMode(number, expected[index], 1, MODES.get(index)); } } - @Test(dataProvider = "rounding2Fract") - public void testRounding2Fract(Object number, String[] expected) { + @ParameterizedTest + @MethodSource("rounding2Fract") + void testRounding2Fract(Object number, String[] expected) { List rModes = List.of(RoundingMode.HALF_EVEN, RoundingMode.HALF_UP, RoundingMode.HALF_DOWN); for (int index = 0; index < rModes.size(); index++) { @@ -161,12 +170,12 @@ private void testRoundingMode(Object number, String expected, NumberFormat fmt = NumberFormat .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); fmt.setRoundingMode(rounding); - assertEquals(fmt.getRoundingMode(), rounding, + assertEquals(rounding, fmt.getRoundingMode(), "RoundingMode set is not returned by getRoundingMode"); fmt.setMinimumFractionDigits(fraction); String result = fmt.format(number); - assertEquals(result, expected, "Incorrect formatting of number " + assertEquals(expected, result, "Incorrect formatting of number " + number + " using rounding mode: " + rounding); } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java index 82577c26fc1a..03f0e9c2faeb 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactNumber.java @@ -25,8 +25,14 @@ * @bug 8177552 8217721 8222756 8295372 * @summary Checks the functioning of compact number format * @modules jdk.localedata - * @run testng/othervm TestCompactNumber + * @run junit/othervm TestCompactNumber */ + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.BigDecimal; import java.math.BigInteger; import java.text.FieldPosition; @@ -36,10 +42,11 @@ import java.text.ParsePosition; import java.util.Locale; import java.util.stream.Stream; -import static org.testng.Assert.*; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestCompactNumber { private static final NumberFormat FORMAT_DZ_LONG = NumberFormat @@ -96,7 +103,6 @@ public class TestCompactNumber { FORMAT_PT_LONG_FD4.setMaximumFractionDigits(4); } - @DataProvider(name = "format") Object[][] compactFormatData() { return new Object[][]{ // compact number format instance, number to format, formatted output @@ -362,7 +368,6 @@ Object[][] compactFormatData() { }; } - @DataProvider(name = "parse") Object[][] compactParseData() { return new Object[][]{ // compact number format instance, string to parse, parsed number, return type @@ -469,7 +474,6 @@ Object[][] compactParseData() { }; } - @DataProvider(name = "exceptionParse") Object[][] exceptionParseData() { return new Object[][]{ // compact number instance, string to parse, null (no o/p; must throw exception) @@ -487,7 +491,6 @@ Object[][] exceptionParseData() { {FORMAT_SE_SHORT, "-8\u00a0mn", null},}; } - @DataProvider(name = "invalidParse") Object[][] invalidParseData() { return new Object[][]{ // compact number instance, string to parse, parsed number @@ -517,7 +520,6 @@ Object[][] invalidParseData() { }; } - @DataProvider(name = "fieldPosition") Object[][] formatFieldPositionData() { return new Object[][]{ //compact number instance, number to format, field, start position, end position, formatted string @@ -563,7 +565,6 @@ Object[][] formatFieldPositionData() { {FORMAT_SE_SHORT, new BigDecimal("-48982865901234567890.98"), NumberFormat.Field.INTEGER, 1, 9, "\u221248982866\u00a0bn"},}; } - @DataProvider(name = "varParsePosition") Object[][] varParsePosition() { return new Object[][]{ // compact number instance, parse string, parsed number, @@ -591,73 +592,82 @@ Object[][] varParsePosition() { } @Test - public void testInstanceCreation() { + void testInstanceCreation() { Stream.of(NumberFormat.getAvailableLocales()).forEach(l -> NumberFormat .getCompactNumberInstance(l, NumberFormat.Style.SHORT).format(10000)); Stream.of(NumberFormat.getAvailableLocales()).forEach(l -> NumberFormat .getCompactNumberInstance(l, NumberFormat.Style.LONG).format(10000)); } - @Test(expectedExceptions = IllegalArgumentException.class) - public void testFormatWithNullParam() { - FORMAT_EN_US_SHORT.format(null); + @Test + void testFormatWithNullParam() { + assertThrows(IllegalArgumentException.class, () -> { + FORMAT_EN_US_SHORT.format(null); + }); } - @Test(dataProvider = "format") - public void testFormat(NumberFormat cnf, Object number, + @ParameterizedTest + @MethodSource("compactFormatData") + void testFormat(NumberFormat cnf, Object number, String expected) { CompactFormatAndParseHelper.testFormat(cnf, number, expected); } - @Test(dataProvider = "parse") - public void testParse(NumberFormat cnf, String parseString, + @ParameterizedTest + @MethodSource("compactParseData") + void testParse(NumberFormat cnf, String parseString, Number expected, Class returnType) throws ParseException { CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, returnType); } - @Test(dataProvider = "parse") - public void testParsePosition(NumberFormat cnf, String parseString, + @ParameterizedTest + @MethodSource("compactParseData") + void testParsePosition(NumberFormat cnf, String parseString, Number expected, Class returnType) throws ParseException { ParsePosition pos = new ParsePosition(0); CompactFormatAndParseHelper.testParse(cnf, parseString, expected, pos, returnType); - assertEquals(pos.getIndex(), parseString.length()); - assertEquals(pos.getErrorIndex(), -1); + assertEquals(parseString.length(), pos.getIndex()); + assertEquals(-1, pos.getErrorIndex()); } - @Test(dataProvider = "varParsePosition") - public void testVarParsePosition(NumberFormat cnf, String parseString, + @ParameterizedTest + @MethodSource("varParsePosition") + void testVarParsePosition(NumberFormat cnf, String parseString, Number expected, int startPosition, int indexPosition, int errPosition) throws ParseException { ParsePosition pos = new ParsePosition(startPosition); CompactFormatAndParseHelper.testParse(cnf, parseString, expected, pos, null); - assertEquals(pos.getIndex(), indexPosition); - assertEquals(pos.getErrorIndex(), errPosition); + assertEquals(indexPosition, pos.getIndex()); + assertEquals(errPosition, pos.getErrorIndex()); } - @Test(dataProvider = "exceptionParse", expectedExceptions = ParseException.class) - public void throwsParseException(NumberFormat cnf, String parseString, - Number expected) throws ParseException { - CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, null); + @ParameterizedTest + @MethodSource("exceptionParseData") + void throwsParseException(NumberFormat cnf, String parseString, + Number expected) { + assertThrows(ParseException.class, () -> CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, null)); } - @Test(dataProvider = "invalidParse") - public void testInvalidParse(NumberFormat cnf, String parseString, + @ParameterizedTest + @MethodSource("invalidParseData") + void testInvalidParse(NumberFormat cnf, String parseString, Number expected) throws ParseException { CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, null); } - @Test(dataProvider = "fieldPosition") - public void testFormatWithFieldPosition(NumberFormat nf, + @ParameterizedTest + @MethodSource("formatFieldPositionData") + void testFormatWithFieldPosition(NumberFormat nf, Object number, Format.Field field, int posStartExpected, int posEndExpected, String expected) { FieldPosition pos = new FieldPosition(field); StringBuffer buf = new StringBuffer(); StringBuffer result = nf.format(number, buf, pos); - assertEquals(result.toString(), expected, "Incorrect formatting of the number '" + assertEquals(expected, result.toString(), "Incorrect formatting of the number '" + number + "'"); - assertEquals(pos.getBeginIndex(), posStartExpected, "Incorrect start position" + assertEquals(posStartExpected, pos.getBeginIndex(), "Incorrect start position" + " while formatting the number '" + number + "', for the field " + field); - assertEquals(pos.getEndIndex(), posEndExpected, "Incorrect end position" + assertEquals(posEndExpected, pos.getEndIndex(), "Incorrect end position" + " while formatting the number '" + number + "', for the field " + field); } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java index 8476b568ba01..1f8f1041e9e1 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestCompactPatternsValidity.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -25,9 +25,13 @@ * @bug 8177552 8217254 8251499 8281317 * @summary Checks the validity of compact number patterns specified through * CompactNumberFormat constructor - * @run testng/othervm TestCompactPatternsValidity + * @run junit/othervm TestCompactPatternsValidity */ +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.BigDecimal; import java.math.BigInteger; import java.text.CompactNumberFormat; @@ -35,9 +39,10 @@ import java.text.ParseException; import java.util.List; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestCompactPatternsValidity { // Max range 10^4 @@ -74,7 +79,6 @@ public class TestCompactPatternsValidity { private static final String[] COMPACT_PATTERN14 = new String[]{"", "", "", "{one:Kun other:0' 'Kun}"}; // from Somali in CLDR 38 - @DataProvider(name = "invalidPatterns") Object[][] invalidCompactPatterns() { return new Object[][] { // compact patterns @@ -90,7 +94,6 @@ Object[][] invalidCompactPatterns() { }; } - @DataProvider(name = "validPatternsFormat") Object[][] validPatternsFormat() { return new Object[][] { // compact patterns, numbers, expected output @@ -116,7 +119,6 @@ Object[][] validPatternsFormat() { }; } - @DataProvider(name = "validPatternsParse") Object[][] validPatternsParse() { return new Object[][] { // compact patterns, parse string, expected output @@ -136,7 +138,6 @@ Object[][] validPatternsParse() { }; } - @DataProvider(name = "validPatternsFormatWithPluralRules") Object[][] validPatternsFormatWithPluralRules() { return new Object[][] { // compact patterns, plural rules, numbers, expected output @@ -144,7 +145,6 @@ Object[][] validPatternsFormatWithPluralRules() { }; } - @DataProvider(name = "validPatternsParseWithPluralRules") Object[][] validPatternsParseWithPluralRules() { return new Object[][] { // compact patterns, plural rules, parse string, expected output @@ -152,15 +152,18 @@ Object[][] validPatternsParseWithPluralRules() { }; } - @Test(dataProvider = "invalidPatterns", - expectedExceptions = IllegalArgumentException.class) - public void testInvalidCompactPatterns(String[] compactPatterns) { - new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols - .getInstance(Locale.US), compactPatterns); + @ParameterizedTest + @MethodSource("invalidCompactPatterns") + void testInvalidCompactPatterns(String[] compactPatterns) { + assertThrows(IllegalArgumentException.class, () -> { + new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols + .getInstance(Locale.US), compactPatterns); + }); } - @Test(dataProvider = "validPatternsFormat") - public void testValidPatternsFormat(String[] compactPatterns, + @ParameterizedTest + @MethodSource("validPatternsFormat") + void testValidPatternsFormat(String[] compactPatterns, List numbers, List expected) { CompactNumberFormat fmt = new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols.getInstance(Locale.US), compactPatterns); @@ -170,8 +173,9 @@ public void testValidPatternsFormat(String[] compactPatterns, } } - @Test(dataProvider = "validPatternsParse") - public void testValidPatternsParse(String[] compactPatterns, + @ParameterizedTest + @MethodSource("validPatternsParse") + void testValidPatternsParse(String[] compactPatterns, List parseString, List numbers) throws ParseException { CompactNumberFormat fmt = new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols.getInstance(Locale.US), compactPatterns); @@ -181,8 +185,9 @@ public void testValidPatternsParse(String[] compactPatterns, } } - @Test(dataProvider = "validPatternsFormatWithPluralRules") - public void testValidPatternsFormatWithPluralRules(String[] compactPatterns, String pluralRules, + @ParameterizedTest + @MethodSource("validPatternsFormatWithPluralRules") + void testValidPatternsFormatWithPluralRules(String[] compactPatterns, String pluralRules, List numbers, List expected) { CompactNumberFormat fmt = new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols.getInstance(Locale.US), compactPatterns, pluralRules); @@ -192,8 +197,9 @@ public void testValidPatternsFormatWithPluralRules(String[] compactPatterns, Str } } - @Test(dataProvider = "validPatternsParseWithPluralRules") - public void testValidPatternsParsewithPluralRules(String[] compactPatterns, String pluralRules, + @ParameterizedTest + @MethodSource("validPatternsParseWithPluralRules") + void testValidPatternsParsewithPluralRules(String[] compactPatterns, String pluralRules, List parseString, List numbers) throws ParseException { CompactNumberFormat fmt = new CompactNumberFormat("#,##0.0#", DecimalFormatSymbols.getInstance(Locale.US), compactPatterns, pluralRules); diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestEquality.java b/test/jdk/java/text/Format/CompactNumberFormat/TestEquality.java index b5d0ae860ed9..2c889656ce0f 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestEquality.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestEquality.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -20,25 +20,26 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 8222756 * @summary Checks the equals and hashCode method of CompactNumberFormat * @modules jdk.localedata - * @run testng/othervm TestEquality - * + * @run junit/othervm TestEquality */ +import org.junit.jupiter.api.Test; + import java.text.CompactNumberFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; -import org.testng.annotations.Test; public class TestEquality { @Test - public void testEquality() { + void testEquality() { CompactNumberFormat cnf1 = (CompactNumberFormat) NumberFormat .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); @@ -148,7 +149,7 @@ private void checkEquals(CompactNumberFormat cnf1, CompactNumberFormat cnf2, } @Test - public void testHashCode() { + void testHashCode() { NumberFormat cnf1 = NumberFormat .getCompactNumberInstance(Locale.JAPAN, NumberFormat.Style.SHORT); NumberFormat cnf2 = NumberFormat @@ -163,7 +164,7 @@ public void testHashCode() { // Test the property of equals and hashCode i.e. two equal object must // always have the same hashCode @Test - public void testEqualsAndHashCode() { + void testEqualsAndHashCode() { NumberFormat cnf1 = NumberFormat .getCompactNumberInstance(Locale.of("hi", "IN"), NumberFormat.Style.SHORT); cnf1.setMinimumIntegerDigits(5); diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestFormatToCharacterIterator.java b/test/jdk/java/text/Format/CompactNumberFormat/TestFormatToCharacterIterator.java index fb18fa256ab8..beb6c38aca88 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestFormatToCharacterIterator.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestFormatToCharacterIterator.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -20,14 +20,20 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 * @summary Checks the functioning of * CompactNumberFormat.formatToCharacterIterator method * @modules jdk.localedata - * @run testng/othervm TestFormatToCharacterIterator + * @run junit/othervm TestFormatToCharacterIterator */ + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.BigDecimal; import java.math.BigInteger; import java.text.AttributedCharacterIterator; @@ -36,10 +42,10 @@ import java.text.NumberFormat; import java.util.Locale; import java.util.Set; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestFormatToCharacterIterator { private static final NumberFormat FORMAT_DZ = NumberFormat @@ -54,7 +60,6 @@ public class TestFormatToCharacterIterator { .getCompactNumberInstance(Locale.ENGLISH, NumberFormat.Style.LONG); - @DataProvider(name = "fieldPositions") Object[][] compactFieldPositionData() { return new Object[][]{ // compact format instance, number, resulted string, attributes/fields, attribute positions @@ -149,22 +154,23 @@ Object[][] compactFieldPositionData() { }; } - @Test(dataProvider = "fieldPositions") - public void testFormatToCharacterIterator(NumberFormat fmt, Object number, + @ParameterizedTest + @MethodSource("compactFieldPositionData") + void testFormatToCharacterIterator(NumberFormat fmt, Object number, String expected, Format.Field[] expectedFields, int[] positions) { AttributedCharacterIterator iterator = fmt.formatToCharacterIterator(number); - assertEquals(getText(iterator), expected, "Incorrect formatting of the number '" + assertEquals(expected, getText(iterator), "Incorrect formatting of the number '" + number + "'"); iterator.first(); // Check start and end index of the formatted string - assertEquals(iterator.getBeginIndex(), 0, "Incorrect start index: " + assertEquals(0, iterator.getBeginIndex(), "Incorrect start index: " + iterator.getBeginIndex() + " of the formatted string: " + expected); - assertEquals(iterator.getEndIndex(), expected.length(), "Incorrect end index: " + assertEquals(expected.length(), iterator.getEndIndex(), "Incorrect end index: " + iterator.getEndIndex() + " of the formatted string: " + expected); // Check the attributes returned by the formatToCharacterIterator - assertEquals(iterator.getAllAttributeKeys(), Set.of(expectedFields), + assertEquals(Set.of(expectedFields), iterator.getAllAttributeKeys(), "Attributes do not match while formatting number: " + number); // Check the begin and end index for attributes @@ -173,10 +179,10 @@ public void testFormatToCharacterIterator(NumberFormat fmt, Object number, do { int start = iterator.getRunStart(); int end = iterator.getRunLimit(); - assertEquals(start, positions[currentPosition], + assertEquals(positions[currentPosition], start, "Incorrect start position for the attribute(s): " + iterator.getAttributes().keySet()); - assertEquals(end, positions[currentPosition + 1], + assertEquals(positions[currentPosition + 1], end, "Incorrect end position for the attribute(s): " + iterator.getAttributes().keySet()); currentPosition = currentPosition + 2; diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestMutatingInstance.java b/test/jdk/java/text/Format/CompactNumberFormat/TestMutatingInstance.java index 47b176692fd1..4cf5ce12f161 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestMutatingInstance.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestMutatingInstance.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -20,6 +20,7 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 @@ -27,8 +28,14 @@ * formatting parameters. For example, min fraction digits, grouping * size etc. * @modules jdk.localedata - * @run testng/othervm TestMutatingInstance + * @run junit/othervm TestMutatingInstance */ + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.BigDecimal; import java.math.BigInteger; import java.text.CompactNumberFormat; @@ -36,10 +43,8 @@ import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestMutatingInstance { private static final NumberFormat FORMAT_FRACTION = NumberFormat @@ -61,8 +66,8 @@ public class TestMutatingInstance { "#,##0.0#", DecimalFormatSymbols.getInstance(Locale.US), new String[]{"", "", "", "", "00K", "", "", "", "", "", "", "", "", "", ""}); - @BeforeTest - public void mutateInstances() { + @BeforeAll + void mutateInstances() { FORMAT_FRACTION.setMinimumFractionDigits(2); FORMAT_GROUPING.setGroupingSize(3); FORMAT_GROUPING.setGroupingUsed(true); @@ -75,7 +80,6 @@ public void mutateInstances() { FORMAT_NO_PATTERNS.setMinimumFractionDigits(2); } - @DataProvider(name = "format") Object[][] compactFormatData() { return new Object[][]{ {FORMAT_FRACTION, 1900, "1.90 thousand"}, @@ -95,7 +99,6 @@ Object[][] compactFormatData() { {FORMAT_NO_PATTERNS, new BigDecimal(12346567890987654.32), "12,346,567,890,987,654"},}; } - @DataProvider(name = "parse") Object[][] compactParseData() { return new Object[][]{ {FORMAT_FRACTION, "190 thousand", 190000L}, @@ -106,14 +109,16 @@ Object[][] compactParseData() { {FORMAT_PARSEINTONLY, "12.345 thousand", 12000L},}; } - @Test(dataProvider = "format") - public void formatCompactNumber(NumberFormat nf, + @ParameterizedTest + @MethodSource("compactFormatData") + void formatCompactNumber(NumberFormat nf, Object number, String expected) { CompactFormatAndParseHelper.testFormat(nf, number, expected); } - @Test(dataProvider = "parse") - public void parseCompactNumber(NumberFormat nf, + @ParameterizedTest + @MethodSource("compactParseData") + void parseCompactNumber(NumberFormat nf, String parseString, Number expected) throws ParseException { CompactFormatAndParseHelper.testParse(nf, parseString, expected, null, null); } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestParseBigDecimal.java b/test/jdk/java/text/Format/CompactNumberFormat/TestParseBigDecimal.java index 1a3c429470a6..e8cc11f68769 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestParseBigDecimal.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestParseBigDecimal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -20,17 +20,19 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 * @summary Checks CNF.parse() when parseBigDecimal is set to true * @modules jdk.localedata - * @run testng/othervm TestParseBigDecimal + * @run junit/othervm TestParseBigDecimal */ -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.math.BigDecimal; import java.text.CompactNumberFormat; @@ -38,6 +40,7 @@ import java.text.ParseException; import java.util.Locale; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestParseBigDecimal { private static final CompactNumberFormat FORMAT_DZ_LONG = (CompactNumberFormat) NumberFormat @@ -64,8 +67,8 @@ public class TestParseBigDecimal { private static final CompactNumberFormat FORMAT_SE_SHORT = (CompactNumberFormat) NumberFormat .getCompactNumberInstance(Locale.of("se"), NumberFormat.Style.SHORT); - @BeforeTest - public void mutateInstances() { + @BeforeAll + void mutateInstances() { FORMAT_DZ_LONG.setParseBigDecimal(true); FORMAT_EN_US_SHORT.setParseBigDecimal(true); FORMAT_EN_LONG.setParseBigDecimal(true); @@ -76,7 +79,6 @@ public void mutateInstances() { FORMAT_SE_SHORT.setParseBigDecimal(true); } - @DataProvider(name = "parse") Object[][] compactParseData() { return new Object[][]{ // compact number format instance, string to parse, parsed number @@ -165,8 +167,9 @@ Object[][] compactParseData() { {FORMAT_SE_SHORT, "\u221212345679,89\u00a0bn", new BigDecimal("-12345679890000000000.00")},}; } - @Test(dataProvider = "parse") - public void testParse(NumberFormat cnf, String parseString, + @ParameterizedTest + @MethodSource("compactParseData") + void testParse(NumberFormat cnf, String parseString, Number expected) throws ParseException { CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, BigDecimal.class); } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestPlurals.java b/test/jdk/java/text/Format/CompactNumberFormat/TestPlurals.java index bbaaa701d234..b8beb6135dd9 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestPlurals.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestPlurals.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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,21 +20,27 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8222756 * @summary Tests plurals support in CompactNumberFormat - * @run testng/othervm TestPlurals + * @run junit/othervm TestPlurals */ +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.CompactNumberFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; -import static org.testng.Assert.*; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestPlurals { private final static DecimalFormatSymbols DFS = DecimalFormatSymbols.getInstance(Locale.ROOT); @@ -45,7 +51,6 @@ public class TestPlurals { private final static String RULE_3 = "one:n%2=0andn/3=2;"; - @DataProvider Object[][] pluralRules() { return new Object[][]{ // rules, number, expected @@ -78,7 +83,6 @@ Object[][] pluralRules() { }; } - @DataProvider Object[][] invalidRules() { return new Object [][] { {"one:a = 1"}, @@ -92,27 +96,34 @@ Object[][] invalidRules() { }; } - @Test(expectedExceptions = NullPointerException.class) - public void testNullPluralRules() { - String[] pattern = {""}; - new CompactNumberFormat("#", DFS, PATTERN, null); + @Test + void testNullPluralRules() { + assertThrows(NullPointerException.class, () -> { + String[] pattern = {""}; + new CompactNumberFormat("#", DFS, PATTERN, null); + }); } - @Test(dataProvider = "pluralRules") - public void testPluralRules(String rules, Number n, String expected) { + @ParameterizedTest + @MethodSource("pluralRules") + void testPluralRules(String rules, Number n, String expected) { var cnp = new CompactNumberFormat("#", DFS, PATTERN, rules); - assertEquals(cnp.format(n), expected); + assertEquals(expected, cnp.format(n)); } - @Test(dataProvider = "invalidRules", expectedExceptions = IllegalArgumentException.class) - public void testInvalidRules(String rules) { - new CompactNumberFormat("#", DFS, PATTERN, rules); + @ParameterizedTest + @MethodSource("invalidRules") + void testInvalidRules(String rules) { + assertThrows(IllegalArgumentException.class, + () -> new CompactNumberFormat("#", DFS, PATTERN, rules)); } - @Test(expectedExceptions = IllegalArgumentException.class) - public void testLimitExceedingRules() { - String andCond = " and n = 1"; - String invalid = "one: n = 1" + andCond.repeat(2_048 / andCond.length()); - new CompactNumberFormat("#", DFS, PATTERN, invalid); + @Test + void testLimitExceedingRules() { + assertThrows(IllegalArgumentException.class, () -> { + String andCond = " and n = 1"; + String invalid = "one: n = 1" + andCond.repeat(2_048 / andCond.length()); + new CompactNumberFormat("#", DFS, PATTERN, invalid); + }); } } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestSpecialValues.java b/test/jdk/java/text/Format/CompactNumberFormat/TestSpecialValues.java index e8ac2489fafc..9bd0ef738309 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestSpecialValues.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestSpecialValues.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -20,25 +20,29 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 * @summary Checks the formatting and parsing of special values * @modules jdk.localedata - * @run testng/othervm TestSpecialValues + * @run junit/othervm TestSpecialValues */ + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestSpecialValues { private static final NumberFormat FORMAT = NumberFormat .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); - @DataProvider(name = "formatSpecialValues") Object[][] formatSpecialValues() { return new Object[][]{ // number , formatted ouput @@ -53,7 +57,6 @@ Object[][] formatSpecialValues() { {Long.MAX_VALUE, "9223372T"},}; } - @DataProvider(name = "parseSpecialValues") Object[][] parseSpecialValues() { return new Object[][]{ // parse string, parsed number @@ -65,13 +68,15 @@ Object[][] parseSpecialValues() { {"-\u221E", Double.NEGATIVE_INFINITY},}; } - @Test(dataProvider = "formatSpecialValues") - public void testFormatSpecialValues(Object number, String expected) { + @ParameterizedTest + @MethodSource("formatSpecialValues") + void testFormatSpecialValues(Object number, String expected) { CompactFormatAndParseHelper.testFormat(FORMAT, number, expected); } - @Test(dataProvider = "parseSpecialValues") - public void testParseSpecialValues(String parseString, Number expected) + @ParameterizedTest + @MethodSource("parseSpecialValues") + void testParseSpecialValues(String parseString, Number expected) throws ParseException { CompactFormatAndParseHelper.testParse(FORMAT, parseString, expected, null, null); } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestUExtensionOverride.java b/test/jdk/java/text/Format/CompactNumberFormat/TestUExtensionOverride.java index 099e6978b0b0..f77908d84c46 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestUExtensionOverride.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestUExtensionOverride.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, 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 @@ -20,23 +20,27 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 8221432 * @summary Checks the behaviour of Unicode BCP 47 U Extension with * compact number format * @modules jdk.localedata - * @run testng/othervm TestUExtensionOverride + * @run junit/othervm TestUExtensionOverride */ + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestUExtensionOverride { - @DataProvider(name = "compactFormatData") Object[][] compactFormatData() { return new Object[][]{ // locale, number, formatted string @@ -61,7 +65,6 @@ Object[][] compactFormatData() { "\u0967\u0968\u00a0k"},}; } - @DataProvider(name = "compactParseData") Object[][] compactParseData() { return new Object[][]{ // locale, parse string, parsed number @@ -87,16 +90,18 @@ Object[][] compactParseData() { "\u0967\u0968\u00a0k", 12000L},}; } - @Test(dataProvider = "compactFormatData") - public void testFormat(Locale locale, double num, + @ParameterizedTest + @MethodSource("compactFormatData") + void testFormat(Locale locale, double num, String expected) { NumberFormat cnf = NumberFormat.getCompactNumberInstance(locale, NumberFormat.Style.SHORT); CompactFormatAndParseHelper.testFormat(cnf, num, expected); } - @Test(dataProvider = "compactParseData") - public void testParse(Locale locale, String parseString, + @ParameterizedTest + @MethodSource("compactParseData") + void testParse(Locale locale, String parseString, Number expected) throws ParseException { NumberFormat cnf = NumberFormat.getCompactNumberInstance(locale, NumberFormat.Style.SHORT); diff --git a/test/jdk/java/text/Format/CompactNumberFormat/TestWithCompatProvider.java b/test/jdk/java/text/Format/CompactNumberFormat/TestWithCompatProvider.java index 510d3d9062f4..884a973226a7 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/TestWithCompatProvider.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/TestWithCompatProvider.java @@ -28,16 +28,19 @@ * as a provider should always use the default patterns added in the * FormatData.java resource bundle * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=COMPAT TestWithCompatProvider + * @run junit/othervm -Djava.locale.providers=COMPAT TestWithCompatProvider */ +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestWithCompatProvider { private static final NumberFormat FORMAT_DZ_SHORT = NumberFormat @@ -46,7 +49,6 @@ public class TestWithCompatProvider { private static final NumberFormat FORMAT_EN_US_SHORT = NumberFormat .getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT); - @DataProvider(name = "format") Object[][] compactFormatData() { return new Object[][]{ {FORMAT_DZ_SHORT, 1000.09, "1K"}, @@ -61,7 +63,6 @@ Object[][] compactFormatData() { {FORMAT_EN_US_SHORT, new BigDecimal("12345678901234567890.89"), "12345679T"},}; } - @DataProvider(name = "parse") Object[][] compactParseData() { return new Object[][]{ {FORMAT_DZ_SHORT, "1K", 1000L}, @@ -72,13 +73,15 @@ Object[][] compactParseData() { {FORMAT_EN_US_SHORT, "12345679T", 1.2345679E19},}; } - @Test(dataProvider = "format") + @ParameterizedTest + @MethodSource("compactFormatData") public void testFormat(NumberFormat cnf, Object number, String expected) { CompactFormatAndParseHelper.testFormat(cnf, number, expected); } - @Test(dataProvider = "parse") + @ParameterizedTest + @MethodSource("compactParseData") public void testParse(NumberFormat cnf, String parseString, Number expected) throws ParseException { CompactFormatAndParseHelper.testParse(cnf, parseString, expected, null, null); diff --git a/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestDeserializeCNF.java b/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestDeserializeCNF.java index 0b4710f0086c..563ae307762c 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestDeserializeCNF.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestDeserializeCNF.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -28,11 +28,12 @@ * @summary Checks deserialization of compact number format * @library /java/text/testlib * @build TestDeserializeCNF HexDumpReader - * @run testng/othervm TestDeserializeCNF + * @run junit/othervm TestDeserializeCNF */ -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.IOException; import java.io.InputStream; @@ -41,8 +42,10 @@ import java.text.CompactNumberFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestDeserializeCNF { // This object is serialized in cnf1.ser.txt with HALF_UP @@ -60,8 +63,8 @@ public class TestDeserializeCNF { private static final String FILE_COMPACT_FORMAT1 = "cnf1.ser.txt"; private static final String FILE_COMPACT_FORMAT2 = "cnf2.ser.txt"; - @BeforeTest - public void mutateInstances() { + @BeforeAll + void mutateInstances() { COMPACT_FORMAT1.setRoundingMode(RoundingMode.HALF_UP); COMPACT_FORMAT1.setGroupingSize(3); COMPACT_FORMAT1.setParseBigDecimal(true); @@ -71,18 +74,18 @@ public void mutateInstances() { } @Test - public void testDeserialization() throws IOException, ClassNotFoundException { + void testDeserialization() throws IOException, ClassNotFoundException { try (InputStream istream1 = HexDumpReader.getStreamFromHexDump(FILE_COMPACT_FORMAT1); ObjectInputStream ois1 = new ObjectInputStream(istream1); InputStream istream2 = HexDumpReader.getStreamFromHexDump(FILE_COMPACT_FORMAT2); ObjectInputStream ois2 = new ObjectInputStream(istream2);) { CompactNumberFormat obj1 = (CompactNumberFormat) ois1.readObject(); - assertEquals(obj1, COMPACT_FORMAT1, "Deserialized instance is not" + assertEquals(COMPACT_FORMAT1, obj1, "Deserialized instance is not" + " equal to the instance serialized in " + FILE_COMPACT_FORMAT1); CompactNumberFormat obj2 = (CompactNumberFormat) ois2.readObject(); - assertEquals(obj2, COMPACT_FORMAT2, "Deserialized instance is not" + assertEquals(COMPACT_FORMAT2, obj2, "Deserialized instance is not" + " equal to the instance serialized in " + FILE_COMPACT_FORMAT2); } } diff --git a/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestSerialization.java b/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestSerialization.java index 55f950bd6745..f2039deb2322 100644 --- a/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestSerialization.java +++ b/test/jdk/java/text/Format/CompactNumberFormat/serialization/TestSerialization.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -20,16 +20,18 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8177552 * @modules jdk.localedata * @summary Checks the serialization feature of CompactNumberFormat - * @run testng/othervm TestSerialization + * @run junit/othervm TestSerialization */ -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -40,8 +42,10 @@ import java.text.CompactNumberFormat; import java.text.NumberFormat; import java.util.Locale; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class TestSerialization { private static final NumberFormat FORMAT_HI = NumberFormat.getCompactNumberInstance( @@ -57,8 +61,8 @@ public class TestSerialization { private static final NumberFormat FORMAT_KO_KR = NumberFormat.getCompactNumberInstance( Locale.KOREA, NumberFormat.Style.SHORT); - @BeforeTest - public void mutateInstances() { + @BeforeAll + void mutateInstances() { FORMAT_HI.setMinimumFractionDigits(2); FORMAT_HI.setMinimumIntegerDigits(5); @@ -80,7 +84,7 @@ public void mutateInstances() { } @Test - public void testSerialization() throws IOException, ClassNotFoundException { + void testSerialization() throws IOException, ClassNotFoundException { // Serialize serialize("cdf.ser", FORMAT_HI, FORMAT_EN_US, FORMAT_JA_JP, FORMAT_FR_FR, FORMAT_DE_DE, FORMAT_KO_KR); // Deserialize @@ -103,13 +107,13 @@ private static void deserialize(String fileName, NumberFormat... formats) new FileInputStream(fileName))) { for (NumberFormat fmt : formats) { NumberFormat obj = (NumberFormat) os.readObject(); - assertEquals(fmt, obj, "Serialized and deserialized" + assertEquals(obj, fmt, "Serialized and deserialized" + " objects do not match"); long number = 123456789789L; String expected = fmt.format(number); String actual = obj.format(number); - assertEquals(actual, expected, "Serialized and deserialized" + assertEquals(expected, actual, "Serialized and deserialized" + " objects are expected to return same formatted" + " output for number: " + number); } diff --git a/test/jdk/java/text/Format/DateFormat/Bug8193444.java b/test/jdk/java/text/Format/DateFormat/Bug8193444.java index 6c5007bc851e..b2fac85dd8a0 100644 --- a/test/jdk/java/text/Format/DateFormat/Bug8193444.java +++ b/test/jdk/java/text/Format/DateFormat/Bug8193444.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -20,29 +20,32 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 8193444 * @summary Checks SimpleDateFormat.format/parse for the AIOOB exception when * formatting/parsing dates through a pattern string that contains a * sequence of 256 or more non-ASCII unicode characters. - * @run testng/othervm Bug8193444 + * @run junit/othervm Bug8193444 */ -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class Bug8193444 { private static final String NON_ASCII_CHAR = "\u263A"; - @DataProvider(name = "dateFormat") Object[][] dateFormatData() { return new Object[][]{ // short_length (between 0 and 254) @@ -53,8 +56,9 @@ Object[][] dateFormatData() { {257},}; } - @Test(dataProvider = "dateFormat") - public void testDateFormatAndParse(int length) + @ParameterizedTest + @MethodSource("dateFormatData") + void testDateFormatAndParse(int length) throws ParseException { String pattern = NON_ASCII_CHAR.repeat(length); @@ -66,7 +70,7 @@ public void testDateFormatAndParse(int length) // Since the tested format patterns do not contain any character // representing date/time field, those characters are not interpreted, // they are simply copied into the output string during formatting - assertEquals(result, pattern, "Failed to format the date using" + assertEquals(pattern, result, "Failed to format the date using" + " pattern of length: " + length); // The format pattern used by this SimpleDateFormat diff --git a/test/jdk/java/text/Format/DateFormat/CaseInsensitiveParseTest.java b/test/jdk/java/text/Format/DateFormat/CaseInsensitiveParseTest.java index 2331e36b2f9e..51473710dbbb 100644 --- a/test/jdk/java/text/Format/DateFormat/CaseInsensitiveParseTest.java +++ b/test/jdk/java/text/Format/DateFormat/CaseInsensitiveParseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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,14 +21,18 @@ * questions. */ -/** +/* * @test * @bug 8248434 * @modules jdk.localedata - * @run testng/othervm CaseInsensitiveParseTest * @summary Checks format/parse round trip in case-insensitive manner. + * @run junit/othervm CaseInsensitiveParseTest */ +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -37,36 +41,36 @@ import java.util.Locale; import java.util.stream.Stream; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CaseInsensitiveParseTest { private final static String PATTERN = "GGGG/yyyy/MMMM/dddd/hhhh/mmmm/ss/aaaa"; private final static Date EPOCH = new Date(0L); - @DataProvider - private Object[][] locales() { + Object[][] locales() { return (Object[][])Arrays.stream(DateFormat.getAvailableLocales()) .map(Stream::of) .map(Stream::toArray) .toArray(Object[][]::new); } - @Test(dataProvider = "locales") - public void testUpperCase(Locale loc) throws ParseException { + @ParameterizedTest + @MethodSource("locales") + void testUpperCase(Locale loc) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN, loc); String formatted = sdf.format(EPOCH); - assertEquals(sdf.parse(formatted.toUpperCase(Locale.ROOT)), EPOCH, + assertEquals(EPOCH, sdf.parse(formatted.toUpperCase(Locale.ROOT)), "roundtrip failed for string '" + formatted + "', locale: " + loc); } - @Test(dataProvider = "locales") - public void testLowerCase(Locale loc) throws ParseException { + @ParameterizedTest + @MethodSource("locales") + void testLowerCase(Locale loc) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(PATTERN, loc); String formatted = sdf.format(EPOCH); - assertEquals(sdf.parse(formatted.toLowerCase(Locale.ROOT)), EPOCH, + assertEquals(EPOCH, sdf.parse(formatted.toLowerCase(Locale.ROOT)), "roundtrip failed for string '" + formatted + "', locale: " + loc); } } diff --git a/test/jdk/java/text/Format/DateFormat/LocaleDateFormats.java b/test/jdk/java/text/Format/DateFormat/LocaleDateFormats.java index 6e58cef5c4b4..a02dc4ecac67 100644 --- a/test/jdk/java/text/Format/DateFormat/LocaleDateFormats.java +++ b/test/jdk/java/text/Format/DateFormat/LocaleDateFormats.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, 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,34 +21,38 @@ * questions. */ -/** +/* * @test * @bug 8080774 * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=JRE,CLDR LocaleDateFormats * @summary This file contains tests for JRE locales date formats + * @run junit/othervm -Djava.locale.providers=JRE,CLDR LocaleDateFormats */ +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.DateFormat; import java.util.Calendar; import java.util.Locale; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class LocaleDateFormats { - @Test(dataProvider = "dateFormats") - public void testDateFormat(Locale loc, int style, int year, int month, int date, String expectedString) { + @ParameterizedTest + @MethodSource("dateFormats") + void testDateFormat(Locale loc, int style, int year, int month, int date, String expectedString) { Calendar cal = Calendar.getInstance(loc); cal.set(year, month-1, date); // Create date formatter based on requested style and test locale DateFormat df = DateFormat.getDateInstance(style, loc); // Test the date format - assertEquals(df.format(cal.getTime()), expectedString); + assertEquals(expectedString, df.format(cal.getTime())); } - @DataProvider(name = "dateFormats" ) private Object[][] dateFormats() { return new Object[][] { //8080774 diff --git a/test/jdk/java/text/Format/DateFormat/SimpleDateFormatPatternTest.java b/test/jdk/java/text/Format/DateFormat/SimpleDateFormatPatternTest.java index bcf0022b092f..e8ff262e0abd 100644 --- a/test/jdk/java/text/Format/DateFormat/SimpleDateFormatPatternTest.java +++ b/test/jdk/java/text/Format/DateFormat/SimpleDateFormatPatternTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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,21 +21,25 @@ * questions. */ -/** +/* * @test * @bug 4326988 6990146 8231213 * @summary test SimpleDateFormat, check its pattern in the constructor - * @run testng/othervm SimpleDateFormatPatternTest + * @run junit/othervm SimpleDateFormatPatternTest */ -import java.lang.IllegalArgumentException; + +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SimpleDateFormatPatternTest { private static String[] validPat = { "yyyy-MM-dd h.mm.ss.a z", @@ -136,90 +140,104 @@ private static Object[][] createPatternObj(String[] pattern){ return objArray; } - @DataProvider(name = "dfAllLocalesObj") Object[][] dfAllLocalesObj() { return dfAllLocalesObj; } - @DataProvider(name = "invalidPatternObj") Object[][] invalidPatternObj() { return invalidPatObj; } - @DataProvider(name = "validPatternObj") Object[][] validPatternObj() { return validPatObj; } //check Constructors for invalid pattern - @Test(dataProvider = "invalidPatternObj", - expectedExceptions = IllegalArgumentException.class) - public void testIllegalArgumentException1(String pattern, Locale loc) + @ParameterizedTest + @MethodSource("invalidPatternObj") + void testIllegalArgumentException1(String pattern, Locale loc) throws IllegalArgumentException { - Locale.setDefault(loc); - new SimpleDateFormat(pattern); + assertThrows(IllegalArgumentException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(pattern); + }); } - @Test(dataProvider = "invalidPatternObj", - expectedExceptions = IllegalArgumentException.class) - public void testIllegalArgumentException2(String pattern, Locale loc) + @ParameterizedTest + @MethodSource("invalidPatternObj") + void testIllegalArgumentException2(String pattern, Locale loc) throws IllegalArgumentException { - Locale.setDefault(loc); - new SimpleDateFormat(pattern, new DateFormatSymbols()); + assertThrows(IllegalArgumentException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(pattern, new DateFormatSymbols()); + }); } - @Test(dataProvider = "invalidPatternObj", - expectedExceptions = IllegalArgumentException.class) - public void testIllegalArgumentException3 (String pattern, Locale loc) + @ParameterizedTest + @MethodSource("invalidPatternObj") + void testIllegalArgumentException3 (String pattern, Locale loc) throws IllegalArgumentException { - Locale.setDefault(loc); - new SimpleDateFormat(pattern, Locale.getDefault()); + assertThrows(IllegalArgumentException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(pattern, Locale.getDefault()); + }); } - @Test(dataProvider = "invalidPatternObj", - expectedExceptions = IllegalArgumentException.class) - public void testIllegalArgumentException4(String pattern, Locale loc) + @ParameterizedTest + @MethodSource("invalidPatternObj") + void testIllegalArgumentException4(String pattern, Locale loc) throws IllegalArgumentException { - Locale.setDefault(loc); - new SimpleDateFormat().applyPattern(pattern); + assertThrows(IllegalArgumentException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat().applyPattern(pattern); + }); } //check Constructors for null pattern - @Test(dataProvider = "dfAllLocalesObj", - expectedExceptions = NullPointerException.class) - public void testNullPointerException1(Locale loc) + @ParameterizedTest + @MethodSource("dfAllLocalesObj") + void testNullPointerException1(Locale loc) throws NullPointerException { - Locale.setDefault(loc); - new SimpleDateFormat(null); + assertThrows(NullPointerException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(null); + }); } - @Test(dataProvider = "dfAllLocalesObj", - expectedExceptions = NullPointerException.class) - public void testNullPointerException2(Locale loc) + @ParameterizedTest + @MethodSource("dfAllLocalesObj") + void testNullPointerException2(Locale loc) throws NullPointerException { - Locale.setDefault(loc); - new SimpleDateFormat(null, new DateFormatSymbols()); + assertThrows(NullPointerException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(null, new DateFormatSymbols()); + }); } - @Test(dataProvider = "dfAllLocalesObj", - expectedExceptions = NullPointerException.class) - public void testNullPointerException3(Locale loc) + @ParameterizedTest + @MethodSource("dfAllLocalesObj") + void testNullPointerException3(Locale loc) throws NullPointerException { - Locale.setDefault(loc); - new SimpleDateFormat(null, Locale.getDefault()); + assertThrows(NullPointerException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat(null, Locale.getDefault()); + }); } - @Test(dataProvider = "dfAllLocalesObj", - expectedExceptions = NullPointerException.class) - public void testNullPointerException4(Locale loc) + @ParameterizedTest + @MethodSource("dfAllLocalesObj") + void testNullPointerException4(Locale loc) throws NullPointerException { - Locale.setDefault(loc); - new SimpleDateFormat().applyPattern(null); + assertThrows(NullPointerException.class, () -> { + Locale.setDefault(loc); + new SimpleDateFormat().applyPattern(null); + }); } - @Test(dataProvider = "validPatternObj") + @ParameterizedTest //check Constructors for valid pattern - public void testValidPattern(String pattern, Locale loc) { + @MethodSource("validPatternObj") + void testValidPattern(String pattern, Locale loc) { Locale.setDefault(loc); new SimpleDateFormat(pattern); new SimpleDateFormat(pattern, new DateFormatSymbols()); diff --git a/test/jdk/java/text/Format/DecimalFormat/SetGroupingSizeTest.java b/test/jdk/java/text/Format/DecimalFormat/SetGroupingSizeTest.java index 07982b453c90..950443412902 100644 --- a/test/jdk/java/text/Format/DecimalFormat/SetGroupingSizeTest.java +++ b/test/jdk/java/text/Format/DecimalFormat/SetGroupingSizeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -26,28 +26,27 @@ * @bug 8212749 * @summary test whether input value check for * DecimalFormat.setGroupingSize(int) works correctly. - * @run testng/othervm SetGroupingSizeTest + * @run junit/othervm SetGroupingSizeTest */ +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.text.DecimalFormat; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -@Test public class SetGroupingSizeTest { - @DataProvider - public static Object[][] validGroupingSizes() { + static Object[][] validGroupingSizes() { return new Object[][] { { 0 }, { Byte.MAX_VALUE }, }; } - @DataProvider - public static Object[][] invalidGroupingSizes() { + static Object[][] invalidGroupingSizes() { return new Object[][] { { Byte.MIN_VALUE - 1 }, { Byte.MIN_VALUE }, @@ -58,17 +57,20 @@ public static Object[][] invalidGroupingSizes() { }; } - @Test(dataProvider = "validGroupingSizes") - public void test_validGroupingSize(int newVal) { + @ParameterizedTest + @MethodSource("validGroupingSizes") + void test_validGroupingSize(int newVal) { DecimalFormat df = new DecimalFormat(); df.setGroupingSize(newVal); - assertEquals(df.getGroupingSize(), newVal); + assertEquals(newVal, df.getGroupingSize()); } - @Test(dataProvider = "invalidGroupingSizes", - expectedExceptions = IllegalArgumentException.class) - public void test_invalidGroupingSize(int newVal) { - DecimalFormat df = new DecimalFormat(); - df.setGroupingSize(newVal); + @ParameterizedTest + @MethodSource("invalidGroupingSizes") + void test_invalidGroupingSize(int newVal) { + assertThrows(IllegalArgumentException.class, () -> { + DecimalFormat df = new DecimalFormat(); + df.setGroupingSize(newVal); + }); } } diff --git a/test/jdk/java/text/Format/NumberFormat/Bug4944439.java b/test/jdk/java/text/Format/NumberFormat/Bug4944439.java index 561052e9a95d..a13a36733e2f 100644 --- a/test/jdk/java/text/Format/NumberFormat/Bug4944439.java +++ b/test/jdk/java/text/Format/NumberFormat/Bug4944439.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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,22 +23,19 @@ /* * @test - * @bug 4944439 + * @bug 4944439 8372609 * @summary Confirm that numbers where all digits after the decimal separator are 0 * and which are between Long.MIN_VALUE and Long.MAX_VALUE are returned * as Long(not double). * @run junit Bug4944439 */ -import java.text.DecimalFormat; +import java.text.NumberFormat; import java.util.ArrayList; import java.util.Locale; import java.util.stream.Stream; -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.assertDoesNotThrow; @@ -47,21 +44,7 @@ public class Bug4944439 { - // Save JVM default locale - private static final Locale savedLocale = Locale.getDefault(); - private static final DecimalFormat df = new DecimalFormat(); - - // Set JVM default locale to US for testing - @BeforeAll - static void initAll() { - Locale.setDefault(Locale.US); - } - - // Restore JVM default locale - @AfterAll - static void tearDownAll() { - Locale.setDefault(savedLocale); - } + private static final NumberFormat df = NumberFormat.getInstance(Locale.US); // Check return type and value returned by DecimalFormat.parse() for longs @ParameterizedTest diff --git a/test/jdk/java/text/Format/NumberFormat/DFSMinusPerCentMill.java b/test/jdk/java/text/Format/NumberFormat/DFSMinusPerCentMill.java index a36eaf5f14fe..418802261ff4 100644 --- a/test/jdk/java/text/Format/NumberFormat/DFSMinusPerCentMill.java +++ b/test/jdk/java/text/Format/NumberFormat/DFSMinusPerCentMill.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 8220309 8230284 * @library /java/text/testlib @@ -29,17 +29,26 @@ * This test assumes CLDR has numbering systems for "arab" and * "arabext", and their minus/percent representations include * BiDi formatting control characters. - * @run testng/othervm DFSMinusPerCentMill + * @run junit/othervm DFSMinusPerCentMill */ -import java.io.*; -import java.util.*; -import java.text.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.util.Locale; -import static org.testng.Assert.*; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class DFSMinusPerCentMill { private enum Type { NUMBER, PERCENT, CURRENCY, INTEGER, COMPACT, PERMILL @@ -49,7 +58,6 @@ private enum Type { private static final Locale US_ARABEXT = Locale.forLanguageTag("en-US-u-nu-arabext"); private static final double SRC_NUM = -1234.56; - @DataProvider Object[][] formatData() { return new Object[][] { // Locale, FormatStyle, expected format, expected single char symbol @@ -69,7 +77,6 @@ Object[][] formatData() { }; } - @DataProvider Object[][] charSymbols() { return new Object[][]{ // Locale, percent, per mille, minus sign @@ -78,8 +85,9 @@ Object[][] charSymbols() { }; } - @Test(dataProvider="formatData") - public void testFormatData(Locale l, Type style, String expected) { + @ParameterizedTest + @MethodSource("formatData") + void testFormatData(Locale l, Type style, String expected) { NumberFormat nf = null; switch (style) { case NUMBER: @@ -102,19 +110,20 @@ public void testFormatData(Locale l, Type style, String expected) { break; } - assertEquals(nf.format(SRC_NUM), expected); + assertEquals(expected, nf.format(SRC_NUM)); } - @Test(dataProvider="charSymbols") - public void testCharSymbols(Locale l, char percent, char permill, char minus) { + @ParameterizedTest + @MethodSource("charSymbols") + void testCharSymbols(Locale l, char percent, char permill, char minus) { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(l); - assertEquals(dfs.getPercent(), percent); - assertEquals(dfs.getPerMill(), permill); - assertEquals(dfs.getMinusSign(), minus); + assertEquals(percent, dfs.getPercent()); + assertEquals(permill, dfs.getPerMill()); + assertEquals(minus, dfs.getMinusSign()); } @Test - public void testSerialization() throws Exception { + void testSerialization() throws Exception { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(dfs); @@ -122,7 +131,7 @@ public void testSerialization() throws Exception { new ByteArrayInputStream(bos.toByteArray()) ).readObject(); - assertEquals(dfs, dfsSerialized); + assertEquals(dfsSerialized, dfs); // set minus/percent/permille dfs.setMinusSign('a'); @@ -134,6 +143,6 @@ public void testSerialization() throws Exception { new ByteArrayInputStream(bos.toByteArray()) ).readObject(); - assertEquals(dfs, dfsSerialized); + assertEquals(dfsSerialized, dfs); } } diff --git a/test/jdk/java/text/Normalizer/SquareEraCharacterTest.java b/test/jdk/java/text/Normalizer/SquareEraCharacterTest.java index 7367badd811e..9b669880fe9b 100644 --- a/test/jdk/java/text/Normalizer/SquareEraCharacterTest.java +++ b/test/jdk/java/text/Normalizer/SquareEraCharacterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -25,20 +25,20 @@ * @test * @bug 8221431 * @summary Tests decomposition of Japanese square era characters. - * @run testng/othervm SquareEraCharacterTest + * @run junit/othervm SquareEraCharacterTest */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.text.Normalizer; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SquareEraCharacterTest { - @DataProvider Object[][] squareEras() { return new Object[][] { @@ -51,12 +51,10 @@ Object[][] squareEras() { }; } - @Test(dataProvider="squareEras") - public void test_normalize(char squareChar, String expected) { - - assertEquals( - Normalizer.normalize(Character.toString(squareChar), Normalizer.Form.NFKD), - expected, + @ParameterizedTest + @MethodSource("squareEras") + void test_normalize(char squareChar, String expected) { + assertEquals(expected, Normalizer.normalize(Character.toString(squareChar), Normalizer.Form.NFKD), "decomposing " + Character.getName(squareChar) + "."); } } diff --git a/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java b/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java index d5293a296bb1..61a32c67bb23 100644 --- a/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java +++ b/test/jdk/java/util/Calendar/CalendarDisplayNamesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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,21 +21,21 @@ * questions. */ -import org.testng.Assert; -import org.testng.annotations.Test; import java.util.Calendar; import java.util.Locale; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * @test * @bug 8262108 * @summary Verify the results returned by Calendar.getDisplayNames() API * @comment Locale providers: COMPAT,SPI - * @run testng/othervm -Djava.locale.providers=COMPAT,SPI CalendarDisplayNamesTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI CalendarDisplayNamesTest * @comment Locale providers: CLDR - * @run testng/othervm -Djava.locale.providers=CLDR CalendarDisplayNamesTest + * @run junit/othervm -Djava.locale.providers=CLDR CalendarDisplayNamesTest */ public class CalendarDisplayNamesTest { @@ -55,7 +55,7 @@ public void testAM_PMDisplayNameValues() { continue; } for (final Integer fieldValue : names.values()) { - Assert.assertTrue(fieldValue == Calendar.AM || fieldValue == Calendar.PM, + Assertions.assertTrue(fieldValue == Calendar.AM || fieldValue == Calendar.PM, "Invalid field value " + fieldValue + " for calendar field AM_PM, in locale " + locale + " with style " + style); } diff --git a/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java b/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java index 6a909a23a18a..ca726afc29b7 100644 --- a/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java +++ b/test/jdk/java/util/Calendar/JapaneseLenientEraTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, 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 @@ -25,7 +25,7 @@ * @test * @bug 8206120 * @summary Test whether lenient era is accepted in JapaneseImperialCalendar - * @run testng/othervm JapaneseLenientEraTest + * @run junit/othervm JapaneseLenientEraTest */ import java.text.DateFormat; @@ -34,15 +34,15 @@ import java.util.Date; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class JapaneseLenientEraTest { - @DataProvider(name="lenientEra") - Object[][] names() { + Object[][] lenientEra() { return new Object[][] { // lenient era/year, strict era/year { "Meiji 123", "Heisei 2" }, @@ -51,7 +51,8 @@ Object[][] names() { }; } - @Test(dataProvider="lenientEra") + @ParameterizedTest + @MethodSource("lenientEra") public void testLenientEra(String lenient, String strict) throws Exception { Calendar c = new Calendar.Builder() .setCalendarType("japanese") @@ -61,6 +62,6 @@ public void testLenientEra(String lenient, String strict) throws Exception { Date lenDate = df.parse(lenient + "-01-01"); df.setLenient(false); Date strDate = df.parse(strict + "-01-01"); - assertEquals(lenDate, strDate); + assertEquals(strDate, lenDate); } } diff --git a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java index 5383d0d12405..e8c0863157a5 100644 --- a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java +++ b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java @@ -27,7 +27,7 @@ * @summary Test for jdk.calendar.japanese.supplemental.era support * @library /test/lib * @build SupplementalJapaneseEraTest - * @run testng/othervm SupplementalJapaneseEraTestRun + * @run junit/othervm SupplementalJapaneseEraTestRun */ import java.util.Calendar; @@ -45,11 +45,12 @@ import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Utils; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SupplementalJapaneseEraTestRun { - @DataProvider(name = "validprop") Object[][] validPropertyData() { return new Object[][] { //Tests with valid property values @@ -58,7 +59,6 @@ Object[][] validPropertyData() { }; } - @DataProvider(name = "invalidprop") Object[][] invalidPropertyData() { return new Object[][] { //Tests with invalid property values @@ -76,7 +76,8 @@ Object[][] invalidPropertyData() { }; } - @Test(dataProvider = "validprop") + @ParameterizedTest + @MethodSource("validPropertyData") public void ValidPropertyValuesTest(String prop) throws Throwable { //get the start time of the fictional next era @@ -84,7 +85,8 @@ public void ValidPropertyValuesTest(String prop) testRun(prop + startTime, List.of("-t")); } - @Test(dataProvider = "invalidprop") + @ParameterizedTest + @MethodSource("invalidPropertyData") public void InvalidPropertyValuesTest(String prop) throws Throwable { //get the start time of the fictional next era diff --git a/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java b/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java index 12f5a96d3fb5..07cc7a412b6a 100644 --- a/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java +++ b/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java @@ -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 8344589 8348328 + * 8327631 8332424 8334418 8344589 8348328 8362428 * @summary Checks the IANA language subtag registry data update - * (LSR Revision: 2025-05-15) with Locale and Locale.LanguageRange + * (LSR Revision: 2025-08-25) with Locale and Locale.LanguageRange * class methods. * @run main LanguageSubtagRegistryTest */ diff --git a/test/jdk/java/util/Locale/LocaleMatchingTest.java b/test/jdk/java/util/Locale/LocaleMatchingTest.java index 975e4567e18b..4509968b4e48 100644 --- a/test/jdk/java/util/Locale/LocaleMatchingTest.java +++ b/test/jdk/java/util/Locale/LocaleMatchingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -25,9 +25,13 @@ * @test * @bug 7069824 8042360 8032842 8175539 8210443 8242010 8276302 * @summary Verify implementation for Locale matching. - * @run testng/othervm LocaleMatchingTest + * @run junit/othervm LocaleMatchingTest */ +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -40,15 +44,14 @@ 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; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; public class LocaleMatchingTest { - @DataProvider(name = "LRConstructorData") - Object[][] LRConstructorData() { + static Object[][] LRConstructorData() { return new Object[][] { // Range, Weight {"elvish", MAX_WEIGHT}, @@ -62,8 +65,7 @@ Object[][] LRConstructorData() { }; } - @DataProvider(name = "LRConstructorNPEData") - Object[][] LRConstructorNPEData() { + static Object[][] LRConstructorNPEData() { return new Object[][] { // Range, Weight {null, MAX_WEIGHT}, @@ -71,8 +73,7 @@ Object[][] LRConstructorNPEData() { }; } - @DataProvider(name = "LRConstructorIAEData") - Object[][] LRConstructorIAEData() { + static Object[][] LRConstructorIAEData() { return new Object[][] { // Range, Weight {"ja", -0.8}, @@ -93,8 +94,7 @@ Object[][] LRConstructorIAEData() { }; } - @DataProvider(name = "LRParseData") - Object[][] LRParseData() { + static Object[][] LRParseData() { return new Object[][] { // Ranges, Expected result {"Accept-Language: fr-FX, de-DE;q=0.5, fr-tp-x-FOO;q=0.1, " @@ -139,8 +139,7 @@ Object[][] LRParseData() { }; } - @DataProvider(name = "LRParseIAEData") - Object[][] LRParseIAEData() { + static Object[][] LRParseIAEData() { return new Object[][] { // Ranges {""}, @@ -148,8 +147,7 @@ Object[][] LRParseIAEData() { }; } - @DataProvider(name = "LRMapEquivalentsData") - Object[][] LRMapEquivalentsData() { + static 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"), @@ -181,8 +179,7 @@ Object[][] LRMapEquivalentsData() { }; } - @DataProvider(name = "LFilterData") - Object[][] LFilterData() { + static 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", @@ -203,8 +200,7 @@ Object[][] LFilterData() { }; } - @DataProvider(name = "LFilterNPEData") - Object[][] LFilterNPEData() { + static Object[][] LFilterNPEData() { return new Object[][] { // Range, LanguageTags, FilteringMode {"en;q=0.2, ja-*-JP, fr-JP", null, REJECT_EXTENDED_RANGES}, @@ -212,8 +208,7 @@ Object[][] LFilterNPEData() { }; } - @DataProvider(name = "LFilterTagsData") - Object[][] LFilterTagsData() { + static Object[][] LFilterTagsData() { return new Object[][] { // Range, LanguageTags, FilteringMode, Expected language tags {"fr-FR, fr-BG;q=0.8, *;q=0.5, en;q=0", "en-US, fr-FR, fr-CA, fr-BG", @@ -274,8 +269,7 @@ Object[][] LFilterTagsData() { }; } - @DataProvider(name = "LLookupData") - Object[][] LLookupData() { + static 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"}, @@ -284,8 +278,7 @@ Object[][] LLookupData() { }; } - @DataProvider(name = "LLookupTagData") - Object[][] LLookupTagData() { + static Object[][] LLookupTagData() { return new Object[][] { // Range, LanguageTags, Expected language tag {"en, *", "es, de, ja-JP", null}, @@ -298,117 +291,135 @@ Object[][] LLookupTagData() { } @Test - public void testLRConstants() { - assertEquals(MIN_WEIGHT, 0.0, " MIN_WEIGHT should be 0.0 but got " + void testLRConstants() { + assertEquals(0.0, MIN_WEIGHT, " MIN_WEIGHT should be 0.0 but got " + MIN_WEIGHT); - assertEquals(MAX_WEIGHT, 1.0, " MAX_WEIGHT should be 1.0 but got " + assertEquals(1.0, MAX_WEIGHT, " MAX_WEIGHT should be 1.0 but got " + MAX_WEIGHT); } - @Test(dataProvider = "LRConstructorData") - public void testLRConstructors(String range, double weight) { + @MethodSource("LRConstructorData") + @ParameterizedTest + 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), + assertEquals(range.toLowerCase(Locale.ROOT), lr.getRange(), " LR.getRange() returned unexpected value. Expected: " + range.toLowerCase(Locale.ROOT) + ", got: " + lr.getRange()); - assertEquals(lr.getWeight(), weight, + assertEquals(weight, lr.getWeight(), " LR.getWeight() returned unexpected value. Expected: " + weight + ", got: " + lr.getWeight()); } - @Test(dataProvider = "LRConstructorNPEData", expectedExceptions = NullPointerException.class) - public void testLRConstructorNPE(String range, double weight) { + @MethodSource("LRConstructorNPEData") + @ParameterizedTest + void testLRConstructorNPE(String range, double weight) { if (weight == MAX_WEIGHT) { - new LanguageRange(range); + assertThrows(NullPointerException.class, () -> new LanguageRange(range)); } else { - new LanguageRange(range, weight); + assertThrows(NullPointerException.class, () -> new LanguageRange(range, weight)); } } - @Test(dataProvider = "LRConstructorIAEData", expectedExceptions = IllegalArgumentException.class) - public void testLRConstructorIAE(String range, double weight) { + @MethodSource("LRConstructorIAEData") + @ParameterizedTest + void testLRConstructorIAE(String range, double weight) { if (weight == MAX_WEIGHT) { - new LanguageRange(range); + assertThrows(IllegalArgumentException.class, () -> new LanguageRange(range)); } else { - new LanguageRange(range, weight); + assertThrows(IllegalArgumentException.class, () -> new LanguageRange(range, weight)); } } @Test - public void testLREquals() { + 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."); + assertEquals(lr2, lr1, " LR(ja, 1.0).equals(LR(ja)) should return true."); + assertNotEquals(lr3, lr1, " LR(ja, 1.0).equals(LR(ja, 0.1)) should return false."); + assertNotEquals(lr4, lr1, " 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."); + 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, + @MethodSource("LRParseData") + @ParameterizedTest + void testLRParse(String ranges, List expected) { + assertEquals(expected, LanguageRange.parse(ranges), " LR.parse(" + ranges + ") test failed."); } - @Test(expectedExceptions = NullPointerException.class) - public void testLRParseNPE() { - LanguageRange.parse(null); + @Test + void testLRParseNPE() { + assertThrows(NullPointerException.class, () -> LanguageRange.parse(null)); } - @Test(dataProvider = "LRParseIAEData", expectedExceptions = IllegalArgumentException.class) - public void testLRParseIAE(String ranges) { - LanguageRange.parse(ranges); + @MethodSource("LRParseIAEData") + @ParameterizedTest + void testLRParseIAE(String ranges) { + assertThrows(IllegalArgumentException.class, () -> LanguageRange.parse(ranges)); } - @Test(dataProvider = "LRMapEquivalentsData") - public void testLRMapEquivalents(List priorityList, + @MethodSource("LRMapEquivalentsData") + @ParameterizedTest + void testLRMapEquivalents(List priorityList, Map> map, List expected) { - assertEquals(LanguageRange.mapEquivalents(priorityList, map), expected, + assertEquals(expected, LanguageRange.mapEquivalents(priorityList, map), " LR.mapEquivalents() test failed."); } - @Test(expectedExceptions = NullPointerException.class) - public void testLRMapEquivalentsNPE() { - LanguageRange.mapEquivalents(null, Map.of("ja", List.of("ja", "ja-Hira"))); + @Test + void testLRMapEquivalentsNPE() { + assertThrows(NullPointerException.class, + () -> 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) { + @MethodSource("LFilterData") + @ParameterizedTest + 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 + ")", + assertEquals(expectedLocales, actualLocales, 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)); + @MethodSource("LFilterNPEData") + @ParameterizedTest + void testLFilterNPE(String ranges, String tags, FilteringMode mode) { + if (ranges == null) { + // Ranges are null + assertThrows(NullPointerException.class, () -> LanguageRange.parse(ranges)); + } else { + // Tags are null + List priorityList = LanguageRange.parse(ranges); + List tagList = generateLocales(tags); + assertThrows(NullPointerException.class, + () -> showLocales(Locale.filter(priorityList, tagList, mode))); + } } - @Test(expectedExceptions = IllegalArgumentException.class) - public void testLFilterIAE() { + @Test + 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)); + assertThrows(IllegalArgumentException.class, + () -> showLocales(Locale.filter(priorityList, tagList, REJECT_EXTENDED_RANGES))); } - @Test(dataProvider = "LFilterTagsData") - public void testLFilterTags(String ranges, String tags, FilteringMode mode, String expectedTags) { + @MethodSource("LFilterTagsData") + @ParameterizedTest + void testLFilterTags(String ranges, String tags, FilteringMode mode, String expectedTags) { List priorityList = LanguageRange.parse(ranges); List tagList = generateLanguageTags(tags); String actualTags; @@ -417,36 +428,39 @@ public void testLFilterTags(String ranges, String tags, FilteringMode mode, Stri } else { actualTags = showLanguageTags(Locale.filterTags(priorityList, tagList, mode)); } - assertEquals(actualTags, expectedTags, + assertEquals(expectedTags, actualTags, showErrorMessage(" L.FilterTags(" + (mode != null ? mode : "") + ")", ranges, tags, expectedTags, actualTags)); } - @Test(expectedExceptions = IllegalArgumentException.class) - public void testLFilterTagsIAE() { + @Test + void testLFilterTagsIAE() { String ranges = "de-*-DE"; String tags = "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"; List priorityList = LanguageRange.parse(ranges); - showLanguageTags(Locale.filterTags(priorityList, generateLanguageTags(tags), REJECT_EXTENDED_RANGES)); + assertThrows(IllegalArgumentException.class, + () -> showLanguageTags(Locale.filterTags(priorityList, generateLanguageTags(tags), REJECT_EXTENDED_RANGES))); } - @Test(dataProvider = "LLookupData") - public void testLLookup(String ranges, String tags, String expectedLocale) { + @MethodSource("LLookupData") + @ParameterizedTest + 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()", + assertEquals(expectedLocale, actualLocale, showErrorMessage(" L.Lookup()", ranges, tags, expectedLocale, actualLocale)); } - @Test(dataProvider = "LLookupTagData") - public void testLLookupTag(String ranges, String tags, String expectedTag) { + @MethodSource("LLookupTagData") + @ParameterizedTest + 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()", + assertEquals(expectedTag, actualTag, showErrorMessage(" L.LookupTag()", ranges, tags, expectedTag, actualTag)); } diff --git a/test/jdk/java/util/Locale/RequiredAvailableLocalesTest.java b/test/jdk/java/util/Locale/RequiredAvailableLocalesTest.java index 2fcba9b9366b..7d229913a844 100644 --- a/test/jdk/java/util/Locale/RequiredAvailableLocalesTest.java +++ b/test/jdk/java/util/Locale/RequiredAvailableLocalesTest.java @@ -20,34 +20,42 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** + +/* * @test * @bug 8276186 * @summary Checks whether getAvailableLocales() returns at least Locale.ROOT and * Locale.US instances. - * @run testng/othervm -Djava.locale.providers=COMPAT RequiredAvailableLocalesTest - * @run testng/othervm -Djava.locale.providers=CLDR RequiredAvailableLocalesTest + * @run junit/othervm -Djava.locale.providers=COMPAT RequiredAvailableLocalesTest + * @run junit/othervm -Djava.locale.providers=CLDR RequiredAvailableLocalesTest */ import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; -import java.text.*; +import java.text.BreakIterator; +import java.text.Collator; +import java.text.DateFormat; +import java.text.DateFormatSymbols; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; import java.time.format.DecimalStyle; -import java.util.*; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Locale; +import java.util.Set; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -@Test public class RequiredAvailableLocalesTest { private static final Set REQUIRED_LOCALES = Set.of(Locale.ROOT, Locale.US); private static final MethodType ARRAY_RETURN_TYPE = MethodType.methodType(Locale.class.arrayType()); private static final MethodType SET_RETURN_TYPE = MethodType.methodType(Set.class); - @DataProvider - public Object[][] availableLocalesClasses() { + static Object[][] availableLocalesClasses() { return new Object[][] { {BreakIterator.class, ARRAY_RETURN_TYPE}, {Calendar.class, ARRAY_RETURN_TYPE}, @@ -61,8 +69,9 @@ public Object[][] availableLocalesClasses() { }; } - @Test (dataProvider = "availableLocalesClasses") - public void checkRequiredLocales(Class c, MethodType mt) throws Throwable { + @MethodSource("availableLocalesClasses") + @ParameterizedTest + void checkRequiredLocales(Class c, MethodType mt) throws Throwable { var ret = MethodHandles.lookup().findStatic(c, "getAvailableLocales", mt).invoke(); if (ret instanceof Locale[] a) { diff --git a/test/jdk/java/util/Locale/TestOf.java b/test/jdk/java/util/Locale/TestOf.java index c923da832bf0..3e0e5e742075 100644 --- a/test/jdk/java/util/Locale/TestOf.java +++ b/test/jdk/java/util/Locale/TestOf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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,29 +20,30 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** + +/* * @test * @bug 8282819 * @summary Unit tests for Locale.of() method. Those tests check the equality * of obtained objects with ones that are gotten from other means with both * well-formed and ill-formed arguments. Also checks the possible NPEs * for error cases. - * @run testng TestOf + * @run junit TestOf */ -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertThrows; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Locale; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; @SuppressWarnings("deprecation") -@Test public class TestOf { - @DataProvider - public Object[][] data_1Arg() { + static Object[][] data_1Arg() { return new Object[][]{ // well-formed {Locale.ENGLISH, "en"}, @@ -55,8 +56,7 @@ public Object[][] data_1Arg() { }; } - @DataProvider - public Object[][] data_2Args() { + static Object[][] data_2Args() { return new Object[][]{ // well-formed {Locale.US, "en", "US"}, @@ -69,8 +69,7 @@ public Object[][] data_2Args() { }; } - @DataProvider - public Object[][] data_3Args() { + static Object[][] data_3Args() { return new Object[][]{ // well-formed {Locale.forLanguageTag("en-US-POSIX"), "en", "US", "POSIX"}, @@ -87,23 +86,26 @@ public Object[][] data_3Args() { }; } - @Test (dataProvider = "data_1Arg") - public void test_1Arg(Locale expected, String lang) { - assertEquals(Locale.of(lang), expected); + @MethodSource("data_1Arg") + @ParameterizedTest + void test_1Arg(Locale expected, String lang) { + assertEquals(expected, Locale.of(lang)); } - @Test (dataProvider = "data_2Args") - public void test_2Args(Locale expected, String lang, String ctry) { - assertEquals(Locale.of(lang, ctry), expected); + @MethodSource("data_2Args") + @ParameterizedTest + void test_2Args(Locale expected, String lang, String ctry) { + assertEquals(expected, Locale.of(lang, ctry)); } - @Test (dataProvider = "data_3Args") - public void test_3Args(Locale expected, String lang, String ctry, String vrnt) { - assertEquals(Locale.of(lang, ctry, vrnt), expected); + @MethodSource("data_3Args") + @ParameterizedTest + void test_3Args(Locale expected, String lang, String ctry, String vrnt) { + assertEquals(expected, Locale.of(lang, ctry, vrnt)); } @Test - public void test_NPE() { + void test_NPE() { assertThrows(NullPointerException.class, () -> Locale.of(null)); assertThrows(NullPointerException.class, () -> Locale.of("", null)); assertThrows(NullPointerException.class, () -> Locale.of("", "", null)); diff --git a/test/jdk/java/util/Locale/bcp47u/CalendarTests.java b/test/jdk/java/util/Locale/bcp47u/CalendarTests.java index 92cfc6581c5f..f04c4a4b1ff4 100644 --- a/test/jdk/java/util/Locale/bcp47u/CalendarTests.java +++ b/test/jdk/java/util/Locale/bcp47u/CalendarTests.java @@ -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 @@ -28,25 +28,24 @@ * @summary Tests Calendar class deals with Unicode extensions * correctly. * @modules jdk.localedata - * @run testng/othervm CalendarTests + * @run junit/othervm CalendarTests */ -import static org.testng.Assert.assertEquals; - import java.text.DateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Calendar with BCP47 U extensions */ -@Test public class CalendarTests { private static TimeZone defaultTZ; @@ -64,19 +63,18 @@ public class CalendarTests { private static final Locale FW_FRI = Locale.forLanguageTag("en-US-u-fw-fri"); private static final Locale FW_SAT = Locale.forLanguageTag("en-US-u-fw-sat"); - @BeforeTest - public void beforeTest() { + @BeforeAll + static void beforeTest() { defaultTZ = TimeZone.getDefault(); TimeZone.setDefault(AMLA); } - @AfterTest - public void afterTest() { + @AfterAll + static void afterTest() { TimeZone.setDefault(defaultTZ); } - @DataProvider(name="tz") - Object[][] tz() { + static Object[][] tz() { return new Object[][] { // Locale, Expected Zone, {JPTYO, ASIATOKYO}, @@ -87,8 +85,7 @@ Object[][] tz() { }; } - @DataProvider(name="firstDayOfWeek") - Object[][] firstDayOfWeek () { + static Object[][] firstDayOfWeek () { return new Object[][] { // Locale, Expected DayOfWeek, {Locale.US, Calendar.SUNDAY}, @@ -114,8 +111,7 @@ Object[][] firstDayOfWeek () { }; } - @DataProvider(name="minDaysInFirstWeek") - Object[][] minDaysInFrstWeek () { + static Object[][] minDaysInFirstWeek () { return new Object[][] { // Locale, Expected minDay, {Locale.US, 1}, @@ -126,33 +122,36 @@ Object[][] minDaysInFrstWeek () { }; } - @Test(dataProvider="tz") - public void test_tz(Locale locale, TimeZone zoneExpected) { + @MethodSource("tz") + @ParameterizedTest + void test_tz(Locale locale, TimeZone zoneExpected) { DateFormat df = DateFormat.getTimeInstance(DateFormat.FULL, locale); - assertEquals(df.getTimeZone(), zoneExpected); + assertEquals(zoneExpected, df.getTimeZone()); Calendar c = Calendar.getInstance(locale); - assertEquals(c.getTimeZone(), zoneExpected); + assertEquals(zoneExpected, c.getTimeZone()); c = new Calendar.Builder().setLocale(locale).build(); - assertEquals(c.getTimeZone(), zoneExpected); + assertEquals(zoneExpected, c.getTimeZone()); } - @Test(dataProvider="firstDayOfWeek") - public void test_firstDayOfWeek(Locale locale, int dowExpected) { + @MethodSource("firstDayOfWeek") + @ParameterizedTest + void test_firstDayOfWeek(Locale locale, int dowExpected) { Calendar c = Calendar.getInstance(locale); - assertEquals(c.getFirstDayOfWeek(), dowExpected); + assertEquals(dowExpected, c.getFirstDayOfWeek()); c = new Calendar.Builder().setLocale(locale).build(); - assertEquals(c.getFirstDayOfWeek(), dowExpected); + assertEquals(dowExpected, c.getFirstDayOfWeek()); } - @Test(dataProvider="minDaysInFirstWeek") - public void test_minDaysInFirstWeek(Locale locale, int minDaysExpected) { + @MethodSource("minDaysInFirstWeek") + @ParameterizedTest + void test_minDaysInFirstWeek(Locale locale, int minDaysExpected) { Calendar c = Calendar.getInstance(locale); - assertEquals(c.getMinimalDaysInFirstWeek(), minDaysExpected); + assertEquals(minDaysExpected, c.getMinimalDaysInFirstWeek()); c = new Calendar.Builder().setLocale(locale).build(); - assertEquals(c.getMinimalDaysInFirstWeek(), minDaysExpected); + assertEquals(minDaysExpected, c.getMinimalDaysInFirstWeek()); } } diff --git a/test/jdk/java/util/Locale/bcp47u/CurrencyFormatTests.java b/test/jdk/java/util/Locale/bcp47u/CurrencyFormatTests.java index d3e14fb0d5a6..1ca251b6add5 100644 --- a/test/jdk/java/util/Locale/bcp47u/CurrencyFormatTests.java +++ b/test/jdk/java/util/Locale/bcp47u/CurrencyFormatTests.java @@ -27,26 +27,24 @@ * @bug 8215181 8230284 8231273 8284840 * @summary Tests the "u-cf" extension * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=CLDR CurrencyFormatTests + * @run junit/othervm -Djava.locale.providers=CLDR CurrencyFormatTests */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.text.NumberFormat; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test NumberFormat with BCP47 u-cf extensions. Note that this test depends * on the particular CLDR release. Results may vary on other CLDR releases. */ -@Test public class CurrencyFormatTests { - @DataProvider(name="getInstanceData") - Object[][] getInstanceData() { + static Object[][] getInstanceData() { return new Object[][] { // Locale, amount, expected // US dollar @@ -97,8 +95,9 @@ Object[][] getInstanceData() { }; } - @Test(dataProvider="getInstanceData") - public void test_getInstance(Locale locale, int amount, String expected) { - assertEquals(NumberFormat.getCurrencyInstance(locale).format(amount), expected); + @MethodSource("getInstanceData") + @ParameterizedTest + void test_getInstance(Locale locale, int amount, String expected) { + assertEquals(expected, NumberFormat.getCurrencyInstance(locale).format(amount)); } } diff --git a/test/jdk/java/util/Locale/bcp47u/CurrencyTests.java b/test/jdk/java/util/Locale/bcp47u/CurrencyTests.java index d807a0e4da3c..a89aed4b0c55 100644 --- a/test/jdk/java/util/Locale/bcp47u/CurrencyTests.java +++ b/test/jdk/java/util/Locale/bcp47u/CurrencyTests.java @@ -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 @@ -28,28 +28,26 @@ * @summary Tests Currency class instantiates correctly with Unicode * extensions * @modules jdk.localedata - * @run testng/othervm CurrencyTests + * @run junit/othervm CurrencyTests */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Currency; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Currency with BCP47 U extensions */ -@Test public class CurrencyTests { private static final Currency USD = Currency.getInstance("USD"); private static final Currency CAD = Currency.getInstance("CAD"); private static final Currency JPY = Currency.getInstance("JPY"); - @DataProvider(name="getInstanceData") - Object[][] getInstanceData() { + static Object[][] getInstanceData() { return new Object[][] { // Locale, Expected Currency // "cu" @@ -76,8 +74,7 @@ Object[][] getInstanceData() { }; } - @DataProvider(name="getSymbolData") - Object[][] getSymbolData() { + static Object[][] getSymbolData() { return new Object[][] { // Currency, DisplayLocale, expected Symbol {USD, Locale.forLanguageTag("en-US-u-rg-jpzzzz"), "$"}, @@ -94,13 +91,15 @@ Object[][] getSymbolData() { }; } - @Test(dataProvider="getInstanceData") - public void test_getInstance(Locale locale, Currency currencyExpected) { - assertEquals(Currency.getInstance(locale), currencyExpected); + @MethodSource("getInstanceData") + @ParameterizedTest + void test_getInstance(Locale locale, Currency currencyExpected) { + assertEquals(currencyExpected, Currency.getInstance(locale)); } - @Test(dataProvider="getSymbolData") - public void test_getSymbol(Currency c, Locale locale, String expected) { - assertEquals(c.getSymbol(locale), expected); + @MethodSource("getSymbolData") + @ParameterizedTest + void test_getSymbol(Currency c, Locale locale, String expected) { + assertEquals(expected, c.getSymbol(locale)); } } diff --git a/test/jdk/java/util/Locale/bcp47u/DisplayNameTests.java b/test/jdk/java/util/Locale/bcp47u/DisplayNameTests.java index 11c4272f1609..bf35fe152a77 100644 --- a/test/jdk/java/util/Locale/bcp47u/DisplayNameTests.java +++ b/test/jdk/java/util/Locale/bcp47u/DisplayNameTests.java @@ -27,21 +27,20 @@ * @bug 8176841 8202537 * @summary Tests the display names for BCP 47 U extensions * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=CLDR DisplayNameTests + * @run junit/othervm -Djava.locale.providers=CLDR DisplayNameTests */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Locale.getDisplayName() with BCP47 U extensions. Note that the * result may change depending on the CLDR releases. */ -@Test public class DisplayNameTests { private static final Locale loc1 = Locale.forLanguageTag("en-Latn-US-u" + "-ca-japanese" + @@ -75,8 +74,7 @@ public class DisplayNameTests { .build(); private static final Locale loc6 = Locale.forLanguageTag( "zh-CN-u-ca-dddd-nu-ddd-cu-ddd-fw-moq-tz-unknown-rg-twzz"); - @DataProvider(name="locales") - Object[][] tz() { + static Object[][] locales() { return new Object[][] { // Locale for display, Test Locale, Expected output, {Locale.US, loc1, @@ -101,9 +99,10 @@ Object[][] tz() { }; } - @Test(dataProvider="locales") - public void test_locales(Locale inLocale, Locale testLocale, String expected) { + @MethodSource("locales") + @ParameterizedTest + void test_locales(Locale inLocale, Locale testLocale, String expected) { String result = testLocale.getDisplayName(inLocale); - assertEquals(result, expected); + assertEquals(expected, result); } } diff --git a/test/jdk/java/util/Locale/bcp47u/FormatTests.java b/test/jdk/java/util/Locale/bcp47u/FormatTests.java index c23c1cb81807..977010ee27f5 100644 --- a/test/jdk/java/util/Locale/bcp47u/FormatTests.java +++ b/test/jdk/java/util/Locale/bcp47u/FormatTests.java @@ -28,10 +28,13 @@ * @summary Tests *Format class deals with Unicode extensions * correctly. * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=CLDR FormatTests + * @run junit/othervm -Djava.locale.providers=CLDR FormatTests */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.text.DateFormat; import java.text.NumberFormat; @@ -40,15 +43,11 @@ import java.util.Locale; import java.util.TimeZone; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test *Format classes with BCP47 U extensions */ -@Test public class FormatTests { private static TimeZone defaultTZ; @@ -80,19 +79,18 @@ public class FormatTests { .build() .getTime(); - @BeforeTest - public void beforeTest() { + @BeforeAll + static void beforeTest() { defaultTZ = TimeZone.getDefault(); TimeZone.setDefault(AMLA); } - @AfterTest - public void afterTest() { + @AfterAll + static void afterTest() { TimeZone.setDefault(defaultTZ); } - @DataProvider(name="dateFormatData") - Object[][] dateFormatData() { + static Object[][] dateFormatData() { return new Object[][] { // Locale, Expected calendar, Expected timezone, Expected formatted string @@ -116,8 +114,7 @@ Object[][] dateFormatData() { }; } - @DataProvider(name="numberFormatData") - Object[][] numberFormatData() { + static Object[][] numberFormatData() { return new Object[][] { // Locale, number, expected format @@ -136,33 +133,35 @@ Object[][] numberFormatData() { }; } - @Test(dataProvider="dateFormatData") - public void test_DateFormat(Locale locale, String calClass, TimeZone tz, + @MethodSource("dateFormatData") + @ParameterizedTest + void test_DateFormat(Locale locale, String calClass, TimeZone tz, String formatExpected) throws Exception { DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locale); if (calClass != null) { try { Class expected = Class.forName(calClass); - assertEquals(df.getCalendar().getClass(), expected); + assertEquals(expected, df.getCalendar().getClass()); } catch (Exception e) { throw e; } } if (tz != null) { - assertEquals(df.getTimeZone(), tz); + assertEquals(tz, df.getTimeZone()); } String formatted = df.format(testDate); - assertEquals(formatted, formatExpected); - assertEquals(df.parse(formatted), testDate); + assertEquals(formatExpected, formatted); + assertEquals(testDate, df.parse(formatted)); } - @Test(dataProvider="numberFormatData") - public void test_NumberFormat(Locale locale, double num, + @MethodSource("numberFormatData") + @ParameterizedTest + void test_NumberFormat(Locale locale, double num, String formatExpected) throws Exception { NumberFormat nf = NumberFormat.getNumberInstance(locale); nf.setMaximumFractionDigits(4); String formatted = nf.format(num); - assertEquals(nf.format(num), formatExpected); - assertEquals(nf.parse(formatted), num); + assertEquals(formatExpected, nf.format(num)); + assertEquals(num, nf.parse(formatted)); } } diff --git a/test/jdk/java/util/Locale/bcp47u/SymbolsTests.java b/test/jdk/java/util/Locale/bcp47u/SymbolsTests.java index 2a8e8bf8e1eb..9baf61b24040 100644 --- a/test/jdk/java/util/Locale/bcp47u/SymbolsTests.java +++ b/test/jdk/java/util/Locale/bcp47u/SymbolsTests.java @@ -28,30 +28,28 @@ * @summary Tests *FormatSymbols class deals with Unicode extensions * correctly. * @modules jdk.localedata - * @run testng/othervm -Djava.locale.providers=CLDR SymbolsTests + * @run junit/othervm -Djava.locale.providers=CLDR SymbolsTests */ -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import java.text.DateFormatSymbols; import java.text.DecimalFormatSymbols; import java.util.Locale; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test *FormatSymbols classes with BCP47 U extensions */ -@Test public class SymbolsTests { private static final Locale RG_GB = Locale.forLanguageTag("en-US-u-rg-gbzzzz"); private static final Locale RG_IE = Locale.forLanguageTag("en-US-u-rg-iezzzz"); private static final Locale RG_AT = Locale.forLanguageTag("en-US-u-rg-atzzzz"); - @DataProvider(name="dateFormatSymbolsData") - Object[][] dateFormatSymbolsData() { + static Object[][] dateFormatSymbolsData() { return new Object[][] { // Locale, expected AM string, expected PM string @@ -61,8 +59,7 @@ Object[][] dateFormatSymbolsData() { }; } - @DataProvider(name="decimalFormatSymbolsData") - Object[][] decimalFormatSymbolsData() { + static Object[][] decimalFormatSymbolsData() { return new Object[][] { // Locale, expected decimal separator, expected grouping separator @@ -74,18 +71,20 @@ Object[][] decimalFormatSymbolsData() { }; } - @Test(dataProvider="dateFormatSymbolsData") - public void test_DateFormatSymbols(Locale locale, String amExpected, String pmExpected) { + @MethodSource("dateFormatSymbolsData") + @ParameterizedTest + void test_DateFormatSymbols(Locale locale, String amExpected, String pmExpected) { DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale); String[] ampm = dfs.getAmPmStrings(); - assertEquals(ampm[0], amExpected); - assertEquals(ampm[1], pmExpected); + assertEquals(amExpected, ampm[0]); + assertEquals(pmExpected, ampm[1]); } - @Test(dataProvider="decimalFormatSymbolsData") - public void test_DecimalFormatSymbols(Locale locale, char decimal, char grouping) { + @MethodSource("decimalFormatSymbolsData") + @ParameterizedTest + void test_DecimalFormatSymbols(Locale locale, char decimal, char grouping) { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale); - assertEquals(dfs.getDecimalSeparator(), decimal); - assertEquals(dfs.getGroupingSeparator(), grouping); + assertEquals(decimal, dfs.getDecimalSeparator()); + assertEquals(grouping, dfs.getGroupingSeparator()); } } diff --git a/test/jdk/java/util/Locale/bcp47u/SystemPropertyTests.java b/test/jdk/java/util/Locale/bcp47u/SystemPropertyTests.java index 905fc9a79c8e..3c34d74337d9 100644 --- a/test/jdk/java/util/Locale/bcp47u/SystemPropertyTests.java +++ b/test/jdk/java/util/Locale/bcp47u/SystemPropertyTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -28,30 +28,26 @@ * @summary Tests the system properties * @modules jdk.localedata * @build DefaultLocaleTest - * @run testng/othervm SystemPropertyTests + * @run junit/othervm SystemPropertyTests */ -import static jdk.test.lib.process.ProcessTools.executeTestJava; -import static org.testng.Assert.assertTrue; - -import java.util.Locale; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import static jdk.test.lib.process.ProcessTools.executeTestJava; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Locale.getDefault() reflects the system property. Note that the * result may change depending on the CLDR releases. */ -@Test public class SystemPropertyTests { private static String LANGPROP = "-Duser.language=en"; private static String SCPTPROP = "-Duser.script="; private static String CTRYPROP = "-Duser.country=US"; - @DataProvider(name="data") - Object[][] data() { + static Object[][] data() { return new Object[][] { // system property, expected default, expected format, expected display {"-Duser.extensions=u-ca-japanese", @@ -86,8 +82,9 @@ Object[][] data() { }; } - @Test(dataProvider="data") - public void runTest(String extprop, String defLoc, + @MethodSource("data") + @ParameterizedTest + void runTest(String extprop, String defLoc, String defFmtLoc, String defDspLoc) throws Exception { int exitValue = executeTestJava(LANGPROP, SCPTPROP, CTRYPROP, extprop, "DefaultLocaleTest", defLoc, defFmtLoc, defDspLoc) @@ -95,6 +92,6 @@ public void runTest(String extprop, String defLoc, .errorTo(System.out) .getExitValue(); - assertTrue(exitValue == 0); + assertEquals(0, exitValue); } } diff --git a/test/jdk/java/util/Properties/CompatibilityTest.java b/test/jdk/java/util/Properties/CompatibilityTest.java index 29c7be6fbcd2..839680806c14 100644 --- a/test/jdk/java/util/Properties/CompatibilityTest.java +++ b/test/jdk/java/util/Properties/CompatibilityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -24,19 +24,19 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Properties; -import org.testng.Assert; - -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test * @bug 8252354 - * @run testng CompatibilityTest + * @run junit CompatibilityTest * @summary Verify compatibility. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CompatibilityTest { - @DataProvider(name = "entries") public Object[][] getEntries() throws IOException { return new Object[][]{ {8, 238923}, @@ -53,9 +53,10 @@ public Object[][] getEntries() throws IOException { * @param value the value * @throws IOException */ - @Test(dataProvider = "entries") + @ParameterizedTest + @MethodSource("getEntries") void testThrows(Object key, Object value) throws IOException { - Assert.assertThrows(ClassCastException.class, () -> storeToXML(key, value)); + Assertions.assertThrows(ClassCastException.class, () -> storeToXML(key, value)); } void storeToXML(Object key, Object value) throws IOException { diff --git a/test/jdk/java/util/Properties/EncodingTest.java b/test/jdk/java/util/Properties/EncodingTest.java index d97730a37c7b..069d16155f0c 100644 --- a/test/jdk/java/util/Properties/EncodingTest.java +++ b/test/jdk/java/util/Properties/EncodingTest.java @@ -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 @@ -27,19 +27,20 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Properties; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @test * @bug 8183743 * @summary Test to verify the new overload method with Charset functions the * same as the existing method that takes a charset name. - * @run testng EncodingTest + * @run junit EncodingTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class EncodingTest { - @DataProvider(name = "parameters") public Object[][] getParameters() throws IOException { return new Object[][]{ {StandardCharsets.UTF_8.name(), null}, @@ -51,7 +52,8 @@ public Object[][] getParameters() throws IOException { * encoding name or a charset can be read with Properties#loadFromXML that * returns the same Properties object. */ - @Test(dataProvider = "parameters") + @ParameterizedTest + @MethodSource("getParameters") void testLoadAndStore(String encoding, Charset charset) throws IOException { Properties props = new Properties(); props.put("k0", "\u6C34"); @@ -74,6 +76,6 @@ void testLoadAndStore(String encoding, Charset charset) throws IOException { } } - Assert.assertEquals(props, p); + Assertions.assertEquals(p, props); } } diff --git a/test/jdk/java/util/Properties/InitialCapacity.java b/test/jdk/java/util/Properties/InitialCapacity.java index 81e5421bbef8..d684c37adf46 100644 --- a/test/jdk/java/util/Properties/InitialCapacity.java +++ b/test/jdk/java/util/Properties/InitialCapacity.java @@ -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 @@ -22,18 +22,22 @@ */ import java.util.Properties; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /* * @test * @bug 8189319 * @summary Test that Properties(int initialCapacity) throws exceptions (or doesn't) as expected - * @run testng InitialCapacity + * @run junit InitialCapacity */ public class InitialCapacity { - @Test(expectedExceptions = IllegalArgumentException.class) - public void negativeInitCap() { Properties p = new Properties(-1); } + @Test + public void negativeInitCap() { Assertions.assertThrows(IllegalArgumentException.class, () -> { + Properties p = new Properties(-1); + }); +} @Test public void positiveInitCap() { Properties p = new Properties(10); } diff --git a/test/jdk/java/util/Properties/PropertiesEntrySetTest.java b/test/jdk/java/util/Properties/PropertiesEntrySetTest.java index d7d58be44dda..f3262f734e30 100644 --- a/test/jdk/java/util/Properties/PropertiesEntrySetTest.java +++ b/test/jdk/java/util/Properties/PropertiesEntrySetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -26,17 +26,17 @@ * @bug 8245694 * @summary tests the entrySet() method of Properties class * @author Yu Li - * @run testng PropertiesEntrySetTest + * @run junit PropertiesEntrySetTest */ -import org.testng.annotations.Test; import java.util.Properties; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class PropertiesEntrySetTest { @@ -99,13 +99,13 @@ public void testEquals() { public void testToString() { Properties a = new Properties(); var aEntrySet = a.entrySet(); - assertEquals(aEntrySet.toString(), "[]"); + assertEquals("[]", aEntrySet.toString()); a.setProperty("p1", "1"); - assertEquals(aEntrySet.toString(), "[p1=1]"); + assertEquals("[p1=1]", aEntrySet.toString()); a.setProperty("p2", "2"); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); assertTrue(aEntrySet.toString().trim().startsWith("[")); assertTrue(aEntrySet.toString().contains("p1=1")); assertTrue(aEntrySet.toString().contains("p2=2")); @@ -115,18 +115,18 @@ public void testToString() { b.setProperty("p2", "2"); b.setProperty("p1", "1"); var bEntrySet = b.entrySet(); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p1=1")); assertTrue(bEntrySet.toString().contains("p2=2")); assertTrue(bEntrySet.toString().trim().endsWith("]")); b.setProperty("p0", "0"); - assertEquals(bEntrySet.size(), 3); + assertEquals(3, bEntrySet.size()); assertTrue(bEntrySet.toString().contains("p0=0")); b.remove("p1"); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertFalse(bEntrySet.toString().contains("p1=1")); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p0=0")); @@ -134,7 +134,7 @@ public void testToString() { assertTrue(bEntrySet.toString().trim().endsWith("]")); b.remove("p0", "0"); - assertEquals(bEntrySet.size(), 1); + assertEquals(1, bEntrySet.size()); assertFalse(bEntrySet.toString().contains("p0=0")); assertTrue(bEntrySet.toString().trim().startsWith("[")); assertTrue(bEntrySet.toString().contains("p2=2")); @@ -151,13 +151,13 @@ public void testEntrySetWithoutException() { a.setProperty("p1", "1"); a.setProperty("p2", "2"); var aEntrySet = a.entrySet(); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); var i = aEntrySet.iterator(); var e1 = i.next(); i.remove(); assertFalse(aEntrySet.contains(e1)); - assertEquals(aEntrySet.size(), 1); + assertEquals(1, aEntrySet.size()); var e2 = i.next(); aEntrySet.remove(e2); @@ -172,14 +172,14 @@ public void testEntrySetWithoutException() { var bEntrySet = b.entrySet(); assertFalse(bEntrySet.containsAll(aEntrySet)); - assertEquals(bEntrySet.size(), 2); + assertEquals(2, bEntrySet.size()); assertTrue(bEntrySet.removeAll(aEntrySet)); - assertEquals(bEntrySet.size(), 1); + assertEquals(1, bEntrySet.size()); assertTrue(bEntrySet.retainAll(aEntrySet)); assertTrue(bEntrySet.isEmpty()); - assertEquals(aEntrySet.size(), 2); + assertEquals(2, aEntrySet.size()); aEntrySet.clear(); assertTrue(aEntrySet.isEmpty()); diff --git a/test/jdk/java/util/Properties/PropertiesStoreTest.java b/test/jdk/java/util/Properties/PropertiesStoreTest.java index b5a5b5a45aa0..88c24698a144 100644 --- a/test/jdk/java/util/Properties/PropertiesStoreTest.java +++ b/test/jdk/java/util/Properties/PropertiesStoreTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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,9 +21,6 @@ * questions. */ -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.IOException; @@ -45,13 +42,18 @@ import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /* * @test * @summary tests the order in which the Properties.store() method writes out the properties * @bug 8231640 8282023 - * @run testng/othervm PropertiesStoreTest + * @run junit/othervm PropertiesStoreTest */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class PropertiesStoreTest { private static final String DATE_FORMAT_PATTERN = "EEE MMM dd HH:mm:ss zzz uuuu"; @@ -60,7 +62,6 @@ public class PropertiesStoreTest { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT_PATTERN, Locale.US); private static final Locale PREV_LOCALE = Locale.getDefault(); - @DataProvider(name = "propsProvider") private Object[][] createProps() { final Properties simple = new Properties(); simple.setProperty("1", "one"); @@ -101,7 +102,6 @@ private Object[][] createProps() { /** * Returns a {@link Locale} to use for testing */ - @DataProvider(name = "localeProvider") private Object[][] provideLocales() { // pick a non-english locale for testing Set locales = Arrays.stream(Locale.getAvailableLocales()) @@ -122,7 +122,8 @@ private Object[][] provideLocales() { * Tests that the {@link Properties#store(Writer, String)} API writes out the properties * in the expected order */ - @Test(dataProvider = "propsProvider") + @ParameterizedTest + @MethodSource("createProps") public void testStoreWriterKeyOrder(final Properties props, final String[] expectedOrder) throws Exception { // Properties.store(...) to a temp file final Path tmpFile = Files.createTempFile("8231640", "props"); @@ -136,7 +137,8 @@ public void testStoreWriterKeyOrder(final Properties props, final String[] expec * Tests that the {@link Properties#store(OutputStream, String)} API writes out the properties * in the expected order */ - @Test(dataProvider = "propsProvider") + @ParameterizedTest + @MethodSource("createProps") public void testStoreOutputStreamKeyOrder(final Properties props, final String[] expectedOrder) throws Exception { // Properties.store(...) to a temp file final Path tmpFile = Files.createTempFile("8231640", "props"); @@ -161,7 +163,7 @@ private void testStoreKeyOrder(final Properties props, final Path storedProps, try (final InputStream is = Files.newInputStream(storedProps)) { loaded.load(is); } - Assert.assertEquals(loaded, props, "Unexpected properties loaded from stored state"); + Assertions.assertEquals(props, loaded, "Unexpected properties loaded from stored state"); // now read lines from the stored file and keep track of the order in which the keys were // found in that file. Compare that order with the expected store order of the keys. @@ -169,10 +171,10 @@ private void testStoreKeyOrder(final Properties props, final Path storedProps, try (final BufferedReader reader = Files.newBufferedReader(storedProps)) { actualOrder = readInOrder(reader); } - Assert.assertEquals(actualOrder.size(), expectedOrder.length, + Assertions.assertEquals(expectedOrder.length, actualOrder.size(), "Unexpected number of keys read from stored properties"); if (!Arrays.equals(actualOrder.toArray(new String[0]), expectedOrder)) { - Assert.fail("Unexpected order of stored property keys. Expected order: " + Arrays.toString(expectedOrder) + Assertions.fail("Unexpected order of stored property keys. Expected order: " + Arrays.toString(expectedOrder) + ", found order: " + actualOrder); } } @@ -180,7 +182,8 @@ private void testStoreKeyOrder(final Properties props, final Path storedProps, /** * Tests that {@link Properties#store(Writer, String)} writes out a proper date comment */ - @Test(dataProvider = "localeProvider") + @ParameterizedTest + @MethodSource("provideLocales") public void testStoreWriterDateComment(final Locale testLocale) throws Exception { // switch the default locale to the one being tested Locale.setDefault(testLocale); @@ -202,7 +205,8 @@ public void testStoreWriterDateComment(final Locale testLocale) throws Exception /** * Tests that {@link Properties#store(OutputStream, String)} writes out a proper date comment */ - @Test(dataProvider = "localeProvider") + @ParameterizedTest + @MethodSource("provideLocales") public void testStoreOutputStreamDateComment(final Locale testLocale) throws Exception { // switch the default locale to the one being tested Locale.setDefault(testLocale); @@ -232,19 +236,19 @@ private void testDateComment(Path file) throws Exception { while ((line = reader.readLine()) != null) { if (line.startsWith("#")) { if (comment != null) { - Assert.fail("More than one comment line found in the stored properties file " + file); + Assertions.fail("More than one comment line found in the stored properties file " + file); } comment = line.substring(1); } } } if (comment == null) { - Assert.fail("No comment line found in the stored properties file " + file); + Assertions.fail("No comment line found in the stored properties file " + file); } try { FORMATTER.parse(comment); } catch (DateTimeParseException pe) { - Assert.fail("Unexpected date comment: " + comment, pe); + Assertions.fail("Unexpected date comment: " + comment, pe); } } diff --git a/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java b/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java index 69f0db832583..c17c4622ecbd 100644 --- a/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/basic/BasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -43,7 +43,7 @@ * jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * ModuleTestUtil - * @run testng BasicTest + * @run junit BasicTest */ import java.nio.file.Path; @@ -54,13 +54,15 @@ import jdk.test.lib.Utils; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.ProcessTools; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static jdk.test.lib.Asserts.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class BasicTest { private static final String SRC_DIR_APPBASIC = "srcAppbasic"; private static final String SRC_DIR_APPBASIC2 = "srcAppbasic2"; @@ -92,7 +94,6 @@ public class BasicTest { private static final String MAIN = "test/jdk.test.Main"; - @DataProvider(name = "basicTestData") Object[][] basicTestData() { return new Object[][] { // Named module "test" contains resource bundles for root and en, @@ -122,7 +123,8 @@ Object[][] basicTestData() { }; } - @Test(dataProvider = "basicTestData") + @ParameterizedTest + @MethodSource("basicTestData") public void runBasicTest(String src, String mod, List moduleList, List localeList, String resFormat) throws Throwable { Path srcPath = Paths.get(Utils.TEST_SRC, src); diff --git a/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java b/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java index 5655eb5de2d0..df72af388552 100644 --- a/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/cache/CacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,7 +27,7 @@ * @library /test/lib * @modules jdk.compiler * @build CacheTest jdk.test.lib.compiler.CompilerUtils - * @run testng CacheTest + * @run junit CacheTest */ import java.nio.file.Files; @@ -37,11 +37,12 @@ import static jdk.test.lib.process.ProcessTools.*; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CacheTest { private static final String TEST_SRC = System.getProperty("test.src"); @@ -55,7 +56,7 @@ public class CacheTest { private static final String MAIN = "test/jdk.test.Main"; private static final String MAIN_CLASS = "jdk.test.Main"; - @BeforeTest + @BeforeAll public void compileTestModules() throws Exception { for (String mn : new String[] {MAIN_BUNDLES_MODULE, TEST_MODULE}) { diff --git a/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java b/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java index 914ebf6bbf0b..45f52b512c8b 100644 --- a/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java +++ b/test/jdk/java/util/ResourceBundle/modules/casesensitive/CaseInsensitiveNameClash.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -28,7 +28,7 @@ * @modules jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools CaseInsensitiveNameClash - * @run testng CaseInsensitiveNameClash + * @run junit CaseInsensitiveNameClash */ import java.nio.file.Files; @@ -37,10 +37,12 @@ import jdk.test.lib.process.ProcessTools; import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class CaseInsensitiveNameClash { private static final String TEST_SRC = System.getProperty("test.src"); @@ -54,7 +56,7 @@ public class CaseInsensitiveNameClash { /** * Compiles the module used by the test */ - @BeforeTest + @BeforeAll public void compileAll() throws Exception { Path msrc = SRC_DIR.resolve(MODULE); assertTrue(CompilerUtils.compile(msrc, MODS_DIR, diff --git a/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java b/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java index e0fdb9a93abb..ee9da88d705b 100644 --- a/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, 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 @@ -34,7 +34,7 @@ * jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * ModuleTestUtil - * @run testng VisibilityTest + * @run junit VisibilityTest */ import java.nio.file.Path; @@ -46,13 +46,13 @@ 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; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -import static org.testng.Assert.assertEquals; - -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class VisibilityTest { private static final Path SRC_DIR = Paths.get(Utils.TEST_SRC, "src"); private static final Path MODS_DIR = Paths.get(Utils.TEST_CLASSES, "mods"); @@ -63,7 +63,7 @@ public class VisibilityTest { private static final List MODULE_LIST = List.of("embargo", "exported.named.bundles", "named.bundles", "test"); - @BeforeTest + @BeforeAll public void prepareTestEnv() throws Throwable { MODULE_LIST.forEach(mn -> ModuleTestUtil.prepareModule(SRC_DIR, MODS_DIR, mn, ".properties")); @@ -93,7 +93,6 @@ public void prepareTestEnv() throws Throwable { * "exported.named.bundle" are exported to unnamed modules. */ - @DataProvider(name = "RunWithTestResData") Object[][] RunWithTestResData() { return new Object[][] { // Tests using jdk.test.TestWithNoModuleArg and jdk.embargo.TestWithNoModuleArg. @@ -188,7 +187,6 @@ Object[][] RunWithTestResData() { }; } - @DataProvider(name = "RunWithExportedResData") Object[][] RunWithExportedResData() { return new Object[][] { // Tests using jdk.test.TestWithNoModuleArg and jdk.embargo.TestWithNoModuleArg @@ -285,7 +283,6 @@ Object[][] RunWithExportedResData() { }; } - @DataProvider(name = "RunWithPkgResData") Object[][] RunWithPkgResData() { return new Object[][] { // jdk.pkg.resources.* are in an unnamed module. @@ -300,10 +297,11 @@ Object[][] RunWithPkgResData() { /** * Test cases with jdk.test.resources.* */ - @Test(dataProvider = "RunWithTestResData") + @ParameterizedTest + @MethodSource("RunWithTestResData") public void RunWithTestRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.test.resources.* failed. " + "Unexpected exit code: " + exitCode); } @@ -311,10 +309,11 @@ public void RunWithTestRes(List argsList) throws Throwable { /** * Test cases with jdk.test.resources.exported.* */ - @Test(dataProvider = "RunWithExportedResData") + @ParameterizedTest + @MethodSource("RunWithExportedResData") public void RunWithExportedRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.test.resources.exported.* failed. " + "Unexpected exit code: " + exitCode); } @@ -322,10 +321,11 @@ public void RunWithExportedRes(List argsList) throws Throwable { /** * Test cases with jdk.pkg.resources.* */ - @Test(dataProvider = "RunWithPkgResData") + @ParameterizedTest + @MethodSource("RunWithPkgResData") public void RunWithPkgRes(List argsList) throws Throwable { int exitCode = runCmd(argsList); - assertEquals(exitCode, 0, "Execution of the tests with " + assertEquals(0, exitCode, "Execution of the tests with " + "jdk.pkg.resources.* failed. " + "Unexpected exit code: " + exitCode); } diff --git a/test/jdk/java/util/ServiceLoader/BadProvidersTest.java b/test/jdk/java/util/ServiceLoader/BadProvidersTest.java index 58613c7b5e35..39c90824e4c9 100644 --- a/test/jdk/java/util/ServiceLoader/BadProvidersTest.java +++ b/test/jdk/java/util/ServiceLoader/BadProvidersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @modules java.base/jdk.internal.org.objectweb.asm * jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils - * @run testng/othervm BadProvidersTest + * @run junit/othervm BadProvidersTest * @summary Basic test of ServiceLoader with bad provider and bad provider * factories deployed on the module path */ @@ -51,15 +51,16 @@ import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -import static org.testng.Assert.*; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Basic test of `provides S with PF` and `provides S with P` where the provider * factory or provider */ - public class BadProvidersTest { private static final String TEST_SRC = System.getProperty("test.src"); @@ -132,21 +133,10 @@ public void sanityTest2() throws Exception { } - @DataProvider(name = "badfactories") - public Object[][] createBadFactories() { - return new Object[][] { - { "classnotpublic", null }, - { "methodnotpublic", null }, - { "badreturntype", null }, - { "returnsnull", null }, - { "throwsexception", null }, - }; - } - - - @Test(dataProvider = "badfactories", - expectedExceptions = ServiceConfigurationError.class) - public void testBadFactory(String testName, String ignore) throws Exception { + @ParameterizedTest + @ValueSource(strings = { "classnotpublic", "methodnotpublic", "badreturntype", + "returnsnull", "throwsexception" }) + public void testBadFactory(String testName) throws Exception { Path mods = compileTest(TEST1_MODULE); // compile the bad factory @@ -158,28 +148,18 @@ public void testBadFactory(String testName, String ignore) throws Exception { // copy the compiled class into the module Path classFile = Paths.get("p", "ProviderFactory.class"); Files.copy(output.resolve(classFile), - mods.resolve(TEST1_MODULE).resolve(classFile), - StandardCopyOption.REPLACE_EXISTING); + mods.resolve(TEST1_MODULE).resolve(classFile), + StandardCopyOption.REPLACE_EXISTING); - // load providers and instantiate each one - loadProviders(mods, TEST1_MODULE).forEach(Provider::get); + Assertions.assertThrows(ServiceConfigurationError.class, + // load providers and instantiate each one + () -> loadProviders(mods, TEST1_MODULE).forEach(Provider::get) + ); } - - @DataProvider(name = "badproviders") - public Object[][] createBadProviders() { - return new Object[][] { - { "notpublic", null }, - { "ctornotpublic", null }, - { "notasubtype", null }, - { "throwsexception", null } - }; - } - - - @Test(dataProvider = "badproviders", - expectedExceptions = ServiceConfigurationError.class) - public void testBadProvider(String testName, String ignore) throws Exception { + @ParameterizedTest + @ValueSource(strings = { "notpublic", "ctornotpublic", "notasubtype", "throwsexception" }) + public void testBadProvider(String testName) throws Exception { Path mods = compileTest(TEST2_MODULE); // compile the bad provider @@ -191,11 +171,13 @@ public void testBadProvider(String testName, String ignore) throws Exception { // copy the compiled class into the module Path classFile = Paths.get("p", "Provider.class"); Files.copy(output.resolve(classFile), - mods.resolve(TEST2_MODULE).resolve(classFile), - StandardCopyOption.REPLACE_EXISTING); + mods.resolve(TEST2_MODULE).resolve(classFile), + StandardCopyOption.REPLACE_EXISTING); - // load providers and instantiate each one - loadProviders(mods, TEST2_MODULE).forEach(Provider::get); + Assertions.assertThrows(ServiceConfigurationError.class, + // load providers and instantiate each one + () -> loadProviders(mods, TEST2_MODULE).forEach(Provider::get) + ); } @@ -203,7 +185,7 @@ public void testBadProvider(String testName, String ignore) throws Exception { * Test a service provider that defines more than one no-args * public static "provider" method. */ - @Test(expectedExceptions = ServiceConfigurationError.class) + @Test public void testWithTwoFactoryMethods() throws Exception { Path mods = compileTest(TEST1_MODULE); @@ -257,8 +239,10 @@ public void testWithTwoFactoryMethods() throws Exception { .resolve("ProviderFactory.class"); Files.write(classFile, cw.toByteArray()); - // load providers and instantiate each one - loadProviders(mods, TEST1_MODULE).forEach(Provider::get); + Assertions.assertThrows(ServiceConfigurationError.class, + // load providers and instantiate each one + () -> loadProviders(mods, TEST1_MODULE).forEach(Provider::get) + ); } } diff --git a/test/jdk/java/util/ServiceLoader/CachingTest.java b/test/jdk/java/util/ServiceLoader/CachingTest.java index 264c646b5af0..138b6b6862ff 100644 --- a/test/jdk/java/util/ServiceLoader/CachingTest.java +++ b/test/jdk/java/util/ServiceLoader/CachingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * 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 * @summary Test ServiceLoader caches - * @run testng CachingTest + * @run junit CachingTest */ import java.nio.file.Files; @@ -38,9 +38,9 @@ import java.util.Spliterator; import java.util.stream.Collectors; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class CachingTest { @@ -52,17 +52,17 @@ public static class S1 implements S { } public static class S2 implements S { } - private ClassLoader testClassLoader; + private static ClassLoader testClassLoader; // creates the services configuration file and sets the ClassLoader - @BeforeClass - void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { String classes = System.getProperty("test.classes"); Path dir = Paths.get(classes, "META-INF", "services"); Files.createDirectories(dir); Path config = dir.resolve(S.class.getName()); Files.write(config, List.of(S1.class.getName(), S2.class.getName())); - this.testClassLoader = CachingTest.class.getClassLoader(); + testClassLoader = CachingTest.class.getClassLoader(); } private void checkLists(List list1, List list2) { diff --git a/test/jdk/java/util/ServiceLoader/ModulesTest.java b/test/jdk/java/util/ServiceLoader/ModulesTest.java index 002b8458865d..d265ce18f60b 100644 --- a/test/jdk/java/util/ServiceLoader/ModulesTest.java +++ b/test/jdk/java/util/ServiceLoader/ModulesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved. * 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,7 +29,7 @@ * @build jdk.test.lib.util.JarUtils * @compile classpath/pearscript/org/pear/PearScriptEngineFactory.java * classpath/pearscript/org/pear/PearScript.java - * @run testng/othervm ModulesTest + * @run junit/othervm ModulesTest * @summary Basic test for ServiceLoader with a provider deployed as a module. */ @@ -55,9 +55,10 @@ import jdk.test.lib.util.JarUtils; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeTest; -import static org.testng.Assert.*; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * Basic test for ServiceLoader. The test make use of two service providers: @@ -67,12 +68,11 @@ * 2. PearScriptEngine - a ScriptEngineFactory deployed on the class path * with a service configuration file. */ - public class ModulesTest { // Copy the services configuration file for "pearscript" into place. - @BeforeTest - public void setup() throws Exception { + @BeforeAll + public static void setup() throws Exception { Path src = Paths.get(System.getProperty("test.src")); Path classes = Paths.get(System.getProperty("test.classes")); String st = ScriptEngineFactory.class.getName(); @@ -428,30 +428,36 @@ public void testWithCustomLayer3() { // -- nulls -- - @Test(expectedExceptions = { NullPointerException.class }) + @Test public void testLoadNull1() { - ServiceLoader.load(null); + Assertions.assertThrows(NullPointerException.class, + () -> ServiceLoader.load(null)); } - @Test(expectedExceptions = { NullPointerException.class }) + @Test public void testLoadNull2() { - ServiceLoader.load((Class) null, ClassLoader.getSystemClassLoader()); + Assertions.assertThrows(NullPointerException.class, + () -> ServiceLoader.load((Class) null, ClassLoader.getSystemClassLoader())); } - @Test(expectedExceptions = { NullPointerException.class }) + @Test public void testLoadNull3() { class S { } - ServiceLoader.load((ModuleLayer) null, S.class); + Assertions.assertThrows(NullPointerException.class, () -> { + ServiceLoader.load((ModuleLayer) null, S.class); + }); } - @Test(expectedExceptions = { NullPointerException.class }) + @Test public void testLoadNull4() { - ServiceLoader.load(ModuleLayer.empty(), null); + Assertions.assertThrows(NullPointerException.class, + () -> ServiceLoader.load(ModuleLayer.empty(), null)); } - @Test(expectedExceptions = { NullPointerException.class }) + @Test public void testLoadNull5() { - ServiceLoader.loadInstalled(null); + Assertions.assertThrows(NullPointerException.class, + () -> ServiceLoader.loadInstalled(null)); } /** diff --git a/test/jdk/java/util/ServiceLoader/NoInterferenceTest.java b/test/jdk/java/util/ServiceLoader/NoInterferenceTest.java index ff83b836e200..d91bc9c759f4 100644 --- a/test/jdk/java/util/ServiceLoader/NoInterferenceTest.java +++ b/test/jdk/java/util/ServiceLoader/NoInterferenceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @library /test/lib * @modules jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils - * @run testng NoInterferenceTest + * @run junit NoInterferenceTest * @summary Basic test of ServiceLoader that ensures there is no interference * when there are two service interfaces of the same name in a layer * or overridden in a child layer. @@ -46,9 +46,9 @@ import jdk.test.lib.compiler.CompilerUtils; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class NoInterferenceTest { @@ -57,8 +57,8 @@ public class NoInterferenceTest { private static final Path MODS_DIR = Paths.get("mods"); private static final List MODULES = Arrays.asList("s1", "p1", "s2", "p2"); - @BeforeTest - void compile() throws Exception { + @BeforeAll + static void compile() throws Exception { Files.createDirectory(MODS_DIR); for (String name : MODULES) { Path src = SRC_DIR.resolve(name); diff --git a/test/jdk/java/util/ServiceLoader/ReloadTest.java b/test/jdk/java/util/ServiceLoader/ReloadTest.java index d48b5c29f4d6..be2c0d687732 100644 --- a/test/jdk/java/util/ServiceLoader/ReloadTest.java +++ b/test/jdk/java/util/ServiceLoader/ReloadTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ * @modules java.scripting * @library modules classpath/pearscript * @build ReloadTest org.pear.PearScript org.pear.PearScriptEngineFactory bananascript/* - * @run testng/othervm ReloadTest + * @run junit/othervm ReloadTest * @summary Basic test of ServiceLoader.reload */ @@ -40,12 +40,14 @@ import java.util.stream.Stream; import static java.util.ServiceLoader.*; import javax.script.ScriptEngineFactory; -import org.testng.annotations.Test; -import static org.testng.Assert.*; -@Test +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; + public class ReloadTest { + @Test public void testReload() { ServiceLoader sl = load(ScriptEngineFactory.class); List names1 = sl.stream() @@ -58,41 +60,42 @@ public void testReload() { .map(Provider::get) .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toList()); - assertEquals(names1, names2); + assertEquals(names2, names1); } - @Test(expectedExceptions = { ConcurrentModificationException.class }) + @Test public void testIteratorHasNext() { ServiceLoader sl = load(ScriptEngineFactory.class); Iterator iterator = sl.iterator(); sl.reload(); - iterator.hasNext(); + Assertions.assertThrows(ConcurrentModificationException.class, iterator::hasNext); } - @Test(expectedExceptions = { ConcurrentModificationException.class }) + @Test public void testIteratorNext() { ServiceLoader sl = load(ScriptEngineFactory.class); Iterator iterator = sl.iterator(); assertTrue(iterator.hasNext()); sl.reload(); - iterator.next(); + Assertions.assertThrows(ConcurrentModificationException.class, iterator::next); } - @Test(expectedExceptions = { ConcurrentModificationException.class }) + @Test public void testStreamFindAny() { ServiceLoader sl = load(ScriptEngineFactory.class); Stream> stream = sl.stream(); sl.reload(); - stream.findAny(); + Assertions.assertThrows(ConcurrentModificationException.class, stream::findAny); } - @Test(expectedExceptions = { ConcurrentModificationException.class }) + @Test public void testSpliteratorTryAdvance() { ServiceLoader sl = load(ScriptEngineFactory.class); Stream> stream = sl.stream(); Spliterator> spliterator = stream.spliterator(); sl.reload(); - spliterator.tryAdvance(System.out::println); + Assertions.assertThrows(ConcurrentModificationException.class, + () -> spliterator.tryAdvance(System.out::println)); } } diff --git a/test/jdk/java/util/ServiceLoader/TwoIterators.java b/test/jdk/java/util/ServiceLoader/TwoIterators.java index ddb9cc09508b..b86cc45f17f9 100644 --- a/test/jdk/java/util/ServiceLoader/TwoIterators.java +++ b/test/jdk/java/util/ServiceLoader/TwoIterators.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * 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 * @summary Test ServiceLoader with two iterators, interleaving their use * to test that they don't interfere with each other - * @run testng TwoIterators + * @run junit TwoIterators */ import java.nio.file.Files; @@ -35,9 +35,9 @@ import java.util.Iterator; import java.util.ServiceLoader; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; public class TwoIterators { @@ -48,18 +48,17 @@ public static interface S { } public static class S1 implements S { } public static class S2 implements S { } - private ClassLoader testClassLoader; + private static ClassLoader testClassLoader; // creates the services configuration file and sets the ClassLoader - @BeforeClass - void setup() throws Exception { + @BeforeAll + static void setup() throws Exception { String classes = System.getProperty("test.classes"); Path dir = Paths.get(classes, "META-INF", "services"); Files.createDirectories(dir); Path config = dir.resolve(S.class.getName()); Files.write(config, Arrays.asList(S1.class.getName(), S2.class.getName())); - - this.testClassLoader = TwoIterators.class.getClassLoader(); + testClassLoader = TwoIterators.class.getClassLoader(); } @Test diff --git a/test/jdk/java/util/ServiceLoader/basic/ServiceLoaderBasicTest.java b/test/jdk/java/util/ServiceLoader/basic/ServiceLoaderBasicTest.java index 91aba564cd18..4a9bc8088512 100644 --- a/test/jdk/java/util/ServiceLoader/basic/ServiceLoaderBasicTest.java +++ b/test/jdk/java/util/ServiceLoader/basic/ServiceLoaderBasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. * 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,7 +29,7 @@ * @build jdk.test.lib.process.* * jdk.test.lib.util.JarUtils * Basic Load FooService FooProvider1 FooProvider2 FooProvider3 BarProvider - * @run testng ServiceLoaderBasicTest + * @run junit ServiceLoaderBasicTest */ @@ -44,14 +44,16 @@ import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.JarUtils; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static java.util.Arrays.asList; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + public class ServiceLoaderBasicTest { private static final String METAINFO = "META-INF/services/FooService"; @@ -79,8 +81,8 @@ public class ServiceLoaderBasicTest { private static final String XTESTXMETA_CP = XTEST_CP + XMETA; private static final String XTESTXMETAP2_CP = XTESTXMETA_CP + P2; - @BeforeClass - public void initialize() throws Exception { + @BeforeAll + public static void initialize() throws Exception { createProviderConfig(XTEST_CONFIG, "FooProvider1"); createProviderConfig(XMETA_CONFIG, "FooProvider42"); createJar(P2JAR, "FooProvider2", List.of("FooProvider2")); @@ -88,8 +90,7 @@ public void initialize() throws Exception { Files.copy(P2JAR, P2DUPJAR, REPLACE_EXISTING); } - @DataProvider - public Object[][] testCases() { + private static Object[][] testCases() { return new Object[][]{ // CLI options, Test, Runtime arguments // Success cases @@ -110,23 +111,14 @@ public Object[][] testCases() { }; } - @DataProvider - public Object[][] negativeTestCases() { - return new Object[][]{ - {"blah blah"}, - {"9234"}, - {"X!"}, - {"BarProvider"}, - {"FooProvider42"} - }; - } - - @Test(dataProvider = "testCases") + @ParameterizedTest + @MethodSource("testCases") public void testProvider(List args) throws Throwable { runJava(args); } - @Test(dataProvider = "negativeTestCases") + @ParameterizedTest // negative test cases + @ValueSource(strings = { "blah blah", "9234", "X!", "BarProvider", "FooProvider42" }) public void testBadProvider(String providerName) throws Throwable { Files.write(XMETA_CONFIG, providerName.getBytes()); runJava(List.of("-cp", XMETA_CP, "Load", "fail")); @@ -144,12 +136,12 @@ private void runJava(List opts) throws Throwable { .shouldHaveExitValue(0); } - private void createProviderConfig(Path config, String providerName) throws Exception { + private static void createProviderConfig(Path config, String providerName) throws Exception { Files.createDirectories(config.getParent()); Files.write(config, providerName.getBytes(), CREATE); } - private void createJar(Path jar, String provider, List files) throws Exception { + private static void createJar(Path jar, String provider, List files) throws Exception { Path xdir = Path.of(provider); createProviderConfig(xdir.resolve(METAINFO), provider); diff --git a/test/jdk/java/util/StringJoiner/MergeTest.java b/test/jdk/java/util/StringJoiner/MergeTest.java index f47ed3ee094a..574124b9bdde 100644 --- a/test/jdk/java/util/StringJoiner/MergeTest.java +++ b/test/jdk/java/util/StringJoiner/MergeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. * 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,17 +27,18 @@ * @summary test StringJoiner::merge * @modules java.base/jdk.internal.util * @requires vm.bits == "64" & os.maxMemory > 4G - * @run testng/othervm -Xmx4g -XX:+CompactStrings MergeTest + * @run junit/othervm -Xmx4g -XX:+CompactStrings MergeTest */ import java.util.StringJoiner; import java.util.stream.Stream; -import org.testng.annotations.Test; import static jdk.internal.util.ArraysSupport.SOFT_MAX_ARRAY_LENGTH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; -@Test +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; + public class MergeTest { private static final String[] PREFIXES = {"", "{", "@#$%"}; private static final String[] SUFFIXES = {"", "}", "*&%$"}; @@ -69,12 +70,13 @@ private static Stream fixesStream() { return builder.build(); } - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void testNull() { StringJoiner sj = new StringJoiner(",", "{", "}"); - sj.merge(null); + Assertions.assertThrows(NullPointerException.class, () -> sj.merge(null)); } + @Test public void testSimple() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); @@ -83,10 +85,11 @@ public void testSimple() { Stream.of("d", "e", "f").forEachOrdered(other::add); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "a,b,c,d,e,f" + fixes.suf0); + assertEquals(fixes.pre0 + "a,b,c,d,e,f" + fixes.suf0, sj.toString()); }); } + @Test public void testEmptyOther() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); @@ -94,14 +97,15 @@ public void testEmptyOther() { Stream.of("a", "b", "c").forEachOrdered(sj::add); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "a,b,c" + fixes.suf0); + assertEquals(fixes.pre0 + "a,b,c" + fixes.suf0, sj.toString()); other.setEmptyValue("EMPTY"); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "a,b,c" + fixes.suf0); + assertEquals(fixes.pre0 + "a,b,c" + fixes.suf0, sj.toString()); }); } + @Test public void testEmptyThis() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); @@ -109,34 +113,36 @@ public void testEmptyThis() { Stream.of("d", "e", "f").forEachOrdered(other::add); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "d:e:f" + fixes.suf0); + assertEquals(fixes.pre0 + "d:e:f" + fixes.suf0, sj.toString()); sj = new StringJoiner(",", fixes.pre0, fixes.suf0).setEmptyValue("EMPTY"); - assertEquals(sj.toString(), "EMPTY"); + assertEquals("EMPTY", sj.toString()); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "d:e:f" + fixes.suf0); + assertEquals(fixes.pre0 + "d:e:f" + fixes.suf0, sj.toString()); }); } + @Test public void testEmptyBoth() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); StringJoiner other = new StringJoiner(":", fixes.pre1, fixes.suf1); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + fixes.suf0); + assertEquals(fixes.pre0 + fixes.suf0, sj.toString()); other.setEmptyValue("NOTHING"); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + fixes.suf0); + assertEquals(fixes.pre0 + fixes.suf0, sj.toString()); sj = new StringJoiner(",", fixes.pre0, fixes.suf0).setEmptyValue("EMPTY"); - assertEquals(sj.toString(), "EMPTY"); + assertEquals("EMPTY", sj.toString()); sj.merge(other); - assertEquals(sj.toString(), "EMPTY"); + assertEquals("EMPTY", sj.toString()); }); } + @Test public void testCascadeEmpty() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); @@ -144,13 +150,14 @@ public void testCascadeEmpty() { StringJoiner o2 = new StringJoiner(",", "<", ">").setEmptyValue("Empty2"); o1.merge(o2); - assertEquals(o1.toString(), "Empty1"); + assertEquals("Empty1", o1.toString()); sj.merge(o1); - assertEquals(sj.toString(), fixes.pre0 + fixes.suf0); + assertEquals(fixes.pre0 + fixes.suf0, sj.toString()); }); } + @Test public void testDelimiter() { fixesStream().forEach(fixes -> { StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0); @@ -159,18 +166,20 @@ public void testDelimiter() { Stream.of("d", "e", "f").forEachOrdered(other::add); sj.merge(other); - assertEquals(sj.toString(), fixes.pre0 + "a,b,c,d:e:f" + fixes.suf0); + assertEquals(fixes.pre0 + "a,b,c,d:e:f" + fixes.suf0, sj.toString()); }); } + @Test public void testMergeSelf() { fixesStream().forEach(fixes -> { final StringJoiner sj = new StringJoiner(",", fixes.pre0, fixes.suf0).add("a").add("b"); - assertEquals(sj.merge(sj).toString(), fixes.pre0 + "a,b,a,b" + fixes.suf0); - assertEquals(sj.merge(sj).toString(), fixes.pre0 + "a,b,a,b,a,b,a,b" + fixes.suf0); + assertEquals(fixes.pre0 + "a,b,a,b" + fixes.suf0, sj.merge(sj).toString()); + assertEquals(fixes.pre0 + "a,b,a,b,a,b,a,b" + fixes.suf0, sj.merge(sj).toString()); }); } + @Test public void OOM() { String maxString = "*".repeat(SOFT_MAX_ARRAY_LENGTH); diff --git a/test/jdk/java/util/StringJoiner/StringJoinerOomUtf16Test.java b/test/jdk/java/util/StringJoiner/StringJoinerOomUtf16Test.java index b45e66b4d8bd..7fde8b36ffa1 100644 --- a/test/jdk/java/util/StringJoiner/StringJoinerOomUtf16Test.java +++ b/test/jdk/java/util/StringJoiner/StringJoinerOomUtf16Test.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved. * 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,23 @@ * @summary tests StringJoiner OOME when joining sub-max-length Strings * @modules java.base/jdk.internal.util * @requires vm.bits == "64" & os.maxMemory > 4G - * @run testng/othervm -Xmx4g -XX:+CompactStrings StringJoinerOomUtf16Test + * @run junit/othervm -Xmx4g -XX:+CompactStrings StringJoinerOomUtf16Test */ -import org.testng.annotations.Test; import static jdk.internal.util.ArraysSupport.SOFT_MAX_ARRAY_LENGTH; -import static org.testng.Assert.fail; + +import static org.junit.jupiter.api.Assertions.fail; import java.util.StringJoiner; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -@Test(groups = {"unit","string","util","libs"}) +@Tag("unit") +@Tag("string") +@Tag("util") +@Tag("libs") public class StringJoinerOomUtf16Test { // the sum of lengths of the following two strings is way less than @@ -48,6 +53,7 @@ public class StringJoinerOomUtf16Test { private static final String OVERFLOW_UTF16_STRING = "\u017D".repeat(((Integer.MAX_VALUE - SOFT_MAX_ARRAY_LENGTH) >> 1) + 1); + @Test public void OOM1() { try { new StringJoiner("") @@ -60,6 +66,7 @@ public void OOM1() { } } + @Test public void OOM2() { try { new StringJoiner(HALF_MAX_LATIN1_STRING) @@ -72,6 +79,7 @@ public void OOM2() { } } + @Test public void OOM3() { try { new StringJoiner(OVERFLOW_UTF16_STRING) @@ -84,6 +92,7 @@ public void OOM3() { } } + @Test public void OOM4() { try { new StringJoiner("", HALF_MAX_LATIN1_STRING, OVERFLOW_UTF16_STRING) diff --git a/test/jdk/java/util/StringJoiner/StringJoinerTest.java b/test/jdk/java/util/StringJoiner/StringJoinerTest.java index 25948fb8e55d..aa25623dbc39 100644 --- a/test/jdk/java/util/StringJoiner/StringJoinerTest.java +++ b/test/jdk/java/util/StringJoiner/StringJoinerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2026, Oracle and/or its affiliates. All rights reserved. * 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,25 @@ * @summary tests StringJoinerTest * @modules java.base/jdk.internal.util * @requires vm.bits == "64" & os.maxMemory > 4G - * @run testng/othervm -Xmx4g -XX:+CompactStrings StringJoinerTest + * @run junit/othervm -Xmx4g -XX:+CompactStrings StringJoinerTest * @author Jim Gish */ + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + import java.util.ArrayList; import java.util.StringJoiner; -import org.testng.annotations.Test; -import static jdk.internal.util.ArraysSupport.SOFT_MAX_ARRAY_LENGTH; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static jdk.internal.util.ArraysSupport.SOFT_MAX_ARRAY_LENGTH; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; -@Test(groups = {"unit","string","util","libs"}) +@Tag("unit") +@Tag("string") +@Tag("util") +@Tag("libs") public class StringJoinerTest { private static final String EMPTY = "EMPTY"; @@ -51,6 +58,7 @@ public class StringJoinerTest { private static final String DASH = "-"; private static final String MAX_STRING = "*".repeat(SOFT_MAX_ARRAY_LENGTH); + @Test public void addAddAll() { StringJoiner sj = new StringJoiner(DASH, "{", "}"); sj.add(ONE); @@ -61,7 +69,7 @@ public void addAddAll() { nextOne.stream().forEachOrdered(sj::add); String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}"; - assertEquals(sj.toString(), expected); + assertEquals(expected, sj.toString()); } void addAlladd() { @@ -75,10 +83,11 @@ void addAlladd() { sj.add(THREE); String expected = "{"+ONE+DASH+TWO+DASH+THREE+"}"; - assertEquals(sj.toString(), expected); + assertEquals(expected, sj.toString()); } // The following tests do two successive adds of different types + @Test public void addAlladdAll() { StringJoiner sj = new StringJoiner(DASH, "{", "}"); ArrayList firstOne = new ArrayList<>(); @@ -93,9 +102,10 @@ public void addAlladdAll() { nextOne.stream().forEachOrdered(sj::add); String expected = "{"+ONE+DASH+TWO+DASH+THREE+DASH+FOUR+DASH+FIVE+"}"; - assertEquals(sj.toString(), expected); + assertEquals(expected, sj.toString()); } + @Test public void addCharSequence() { StringJoiner sj = new StringJoiner(","); CharSequence cs_one = ONE; @@ -104,13 +114,13 @@ public void addCharSequence() { sj.add(cs_one); sj.add(cs_two); - assertEquals(sj.toString(), ONE + "," + TWO); + assertEquals(ONE + "," + TWO, sj.toString()); sj = new StringJoiner(DASH, "{", "}"); sj.add(cs_one); sj.add(cs_two); - assertEquals(sj.toString(), "{" + ONE + DASH + TWO + "}"); + assertEquals("{" + ONE + DASH + TWO + "}", sj.toString()); StringBuilder builder = new StringBuilder(ONE); StringBuffer buffer = new StringBuffer(THREE); @@ -118,13 +128,14 @@ public void addCharSequence() { sj.add(builder).add(buffer); builder.append(TWO); buffer.append(FOUR); - assertEquals(sj.toString(), "{ " + ONE + ", " + THREE + " }", + assertEquals("{ " + ONE + ", " + THREE + " }", sj.toString(), "CharSequence is copied when add"); sj.add(builder); - assertEquals(sj.toString(), "{ " + ONE + ", " + THREE + ", " + ONE + - TWO + " }"); + assertEquals("{ " + ONE + ", " + THREE + ", " + ONE + + TWO + " }", sj.toString()); } + @Test public void addCharSequenceWithEmptyValue() { StringJoiner sj = new StringJoiner(",").setEmptyValue(EMPTY); CharSequence cs_one = ONE; @@ -133,189 +144,200 @@ public void addCharSequenceWithEmptyValue() { sj.add(cs_one); sj.add(cs_two); - assertEquals(sj.toString(), ONE + "," + TWO); + assertEquals(ONE + "," + TWO, sj.toString()); sj = new StringJoiner(DASH, "{", "}"); sj.add(cs_one); sj.add(cs_two); - assertEquals(sj.toString(), "{" + ONE + DASH + TWO + "}"); + assertEquals("{" + ONE + DASH + TWO + "}", sj.toString()); sj = new StringJoiner(DASH, "{", "}"); - assertEquals(sj.toString(), "{}"); + assertEquals("{}", sj.toString()); sj = new StringJoiner("=", "{", "}").setEmptyValue(""); - assertEquals(sj.toString(), ""); + assertEquals("", sj.toString()); sj = new StringJoiner(DASH, "{", "}").setEmptyValue(EMPTY); - assertEquals(sj.toString(), EMPTY); + assertEquals(EMPTY, sj.toString()); sj.add(cs_one); sj.add(cs_two); - assertEquals(sj.toString(), "{" + ONE + DASH + TWO + "}"); + assertEquals("{" + ONE + DASH + TWO + "}", sj.toString()); } + @Test public void addString() { StringJoiner sj = new StringJoiner(DASH); sj.add(ONE); - assertEquals(sj.toString(), ONE); + assertEquals(ONE, sj.toString()); sj = new StringJoiner(DASH, "{", "}"); sj.add(ONE); - assertEquals(sj.toString(), "{" + ONE + "}"); + assertEquals("{" + ONE + "}", sj.toString()); sj.add(TWO); - assertEquals(sj.toString(), "{" + ONE + DASH + TWO + "}"); + assertEquals("{" + ONE + DASH + TWO + "}", sj.toString()); } + @Test public void lengthWithCustomEmptyValue() { StringJoiner sj = new StringJoiner(DASH, "<", ">").setEmptyValue(EMPTY); - assertEquals(sj.length(), EMPTY.length()); + assertEquals(EMPTY.length(), sj.length()); sj.add(""); - assertEquals(sj.length(), "<>".length()); + assertEquals("<>".length(), sj.length()); sj.add(""); - assertEquals(sj.length(), "<->".length()); + assertEquals("<->".length(), sj.length()); sj.add(ONE); - assertEquals(sj.length(), 4 + ONE_LEN); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(4 + ONE_LEN, sj.length()); + assertEquals(sj.length(), sj.toString().length()); sj.add(TWO); - assertEquals(sj.length(), 5 + ONE_LEN + TWO_LEN); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(5 + ONE_LEN + TWO_LEN, sj.length()); + assertEquals(sj.length(), sj.toString().length()); sj = new StringJoiner("||", "<", "-->"); - assertEquals(sj.length(), 4); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(4, sj.length()); + assertEquals(sj.length(), sj.toString().length()); sj.add("abcdef"); - assertEquals(sj.length(), 10); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(10, sj.length()); + assertEquals(sj.length(), sj.toString().length()); sj.add("xyz"); - assertEquals(sj.length(), 15); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(15, sj.length()); + assertEquals(sj.length(), sj.toString().length()); } + @Test public void noAddAndEmptyValue() { StringJoiner sj = new StringJoiner(DASH, "", "").setEmptyValue(EMPTY); - assertEquals(sj.toString(), EMPTY); + assertEquals(EMPTY, sj.toString()); sj = new StringJoiner(DASH, "<..", ""); - assertEquals(sj.toString(), "<.."); + assertEquals("<..", sj.toString()); sj = new StringJoiner(DASH, "<..", ""); - assertEquals(sj.toString(), "<.."); + assertEquals("<..", sj.toString()); sj = new StringJoiner(DASH, "", "==>"); - assertEquals(sj.toString(), "==>"); + assertEquals("==>", sj.toString()); sj = new StringJoiner(DASH, "{", "}"); - assertEquals(sj.toString(), "{}"); + assertEquals("{}", sj.toString()); } - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void setEmptyValueNull() { - new StringJoiner(DASH, "{", "}").setEmptyValue(null); + Assertions.assertThrows(NullPointerException.class, + () -> new StringJoiner(DASH, "{", "}").setEmptyValue(null)); } - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void setDelimiterNull() { - new StringJoiner(null); + Assertions.assertThrows(NullPointerException.class, + () -> new StringJoiner(null)); } - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void setPrefixNull() { - new StringJoiner(DASH, null, "}"); + Assertions.assertThrows(NullPointerException.class, + () -> new StringJoiner(DASH, null, "}")); } - @Test(expectedExceptions = {NullPointerException.class}) + @Test public void setSuffixNull() { - new StringJoiner(DASH, "{", null); + Assertions.assertThrows(NullPointerException.class, + () -> new StringJoiner(DASH, "{", null)); } + @Test public void stringFromtoString() { StringJoiner sj = new StringJoiner(", "); - assertEquals(sj.toString(), ""); + assertEquals("", sj.toString()); sj = new StringJoiner(",", "{", "}"); - assertEquals(sj.toString(), "{}"); + assertEquals("{}", sj.toString()); sj = new StringJoiner(","); sj.add(ONE); - assertEquals(sj.toString(), ONE); + assertEquals(ONE, sj.toString()); sj.add(TWO); - assertEquals(sj.toString(), ONE + "," + TWO); + assertEquals(ONE + "," + TWO, sj.toString()); sj = new StringJoiner(",", "{--", "--}"); sj.add(ONE); sj.add(TWO); - assertEquals(sj.toString(), "{--" + ONE + "," + TWO + "--}"); + assertEquals("{--" + ONE + "," + TWO + "--}", sj.toString()); } + @Test public void stringFromtoStringWithEmptyValue() { StringJoiner sj = new StringJoiner(" ", "", ""); - assertEquals(sj.toString(), ""); + assertEquals("", sj.toString()); sj = new StringJoiner(", "); - assertEquals(sj.toString(), ""); + assertEquals("", sj.toString()); sj = new StringJoiner(",", "{", "}"); - assertEquals(sj.toString(), "{}"); + assertEquals("{}", sj.toString()); sj = new StringJoiner(",", "{", "}").setEmptyValue(""); - assertEquals(sj.toString(), ""); + assertEquals("", sj.toString()); sj = new StringJoiner(","); sj.add(ONE); - assertEquals(sj.toString(), ONE); + assertEquals(ONE, sj.toString()); sj.add(TWO); - assertEquals(sj.toString(), ONE + "," + TWO); + assertEquals(ONE + "," + TWO, sj.toString()); sj = new StringJoiner(",", "{--", "--}"); sj.add(ONE); - assertEquals(sj.toString(), "{--" + ONE + "--}" ); + assertEquals("{--" + ONE + "--}", sj.toString() ); sj.add(TWO); - assertEquals(sj.toString(), "{--" + ONE + "," + TWO + "--}"); + assertEquals("{--" + ONE + "," + TWO + "--}", sj.toString()); } + @Test public void toStringWithCustomEmptyValue() { StringJoiner sj = new StringJoiner(DASH, "<", ">").setEmptyValue(EMPTY); - assertEquals(sj.toString(), EMPTY); + assertEquals(EMPTY, sj.toString()); sj.add(""); - assertEquals(sj.toString(), "<>"); + assertEquals("<>", sj.toString()); sj.add(""); - assertEquals(sj.toString(), "<->"); + assertEquals("<->", sj.toString()); } private void testCombos(String infix, String prefix, String suffix) { StringJoiner sj = new StringJoiner(infix, prefix, suffix); - assertEquals(sj.toString(), prefix + suffix); - assertEquals(sj.toString().length(), sj.length()); + assertEquals(prefix + suffix, sj.toString()); + assertEquals(sj.length(), sj.toString().length()); // EmptyValue sj = new StringJoiner(infix, prefix, suffix).setEmptyValue(""); - assertEquals(sj.toString(), ""); - assertEquals(sj.toString().length(), sj.length()); + assertEquals("", sj.toString()); + assertEquals(sj.length(), sj.toString().length()); // empty in front sj.add(""); - assertEquals(sj.toString(), prefix + suffix); + assertEquals(prefix + suffix, sj.toString()); // empty in middle sj.add(""); - assertEquals(sj.toString(), prefix + infix + suffix); + assertEquals(prefix + infix + suffix, sj.toString()); sj.add("1"); - assertEquals(sj.toString(), prefix + infix + infix + "1" + suffix); + assertEquals(prefix + infix + infix + "1" + suffix, sj.toString()); // empty at end sj.add(""); - assertEquals(sj.toString(), prefix + infix + infix + "1" + infix + suffix); + assertEquals(prefix + infix + infix + "1" + infix + suffix, sj.toString()); sj = new StringJoiner(infix, prefix, suffix).setEmptyValue(""); sj.add("1"); - assertEquals(sj.toString(), prefix + "1" + suffix); + assertEquals(prefix + "1" + suffix, sj.toString()); sj.add("2"); - assertEquals(sj.toString(), prefix + "1" + infix + "2" + suffix); + assertEquals(prefix + "1" + infix + "2" + suffix, sj.toString()); sj.add(""); - assertEquals(sj.toString(), prefix + "1" + infix + "2" + infix + suffix); + assertEquals(prefix + "1" + infix + "2" + infix + suffix, sj.toString()); sj.add("3"); - assertEquals(sj.toString(), prefix + "1" + infix + "2" + infix + infix + "3" + suffix); + assertEquals(prefix + "1" + infix + "2" + infix + infix + "3" + suffix, sj.toString()); } + @Test public void testDelimiterCombinations() { testCombos("", "", ""); testCombos("", "<", ""); @@ -327,6 +349,7 @@ public void testDelimiterCombinations() { testCombos(",", "<", ">"); } + @Test public void OOM1() { try { new StringJoiner(MAX_STRING, MAX_STRING, MAX_STRING).toString(); @@ -336,6 +359,7 @@ public void OOM1() { } } + @Test public void OOM2() { try { new StringJoiner(MAX_STRING, MAX_STRING, "").toString(); @@ -345,6 +369,7 @@ public void OOM2() { } } + @Test public void OOM3() { try { new StringJoiner(MAX_STRING, "", MAX_STRING).toString(); @@ -354,6 +379,7 @@ public void OOM3() { } } + @Test public void OOM4() { try { new StringJoiner("", MAX_STRING, MAX_STRING).toString(); diff --git a/test/jdk/java/util/TimeZone/NegativeDSTTest.java b/test/jdk/java/util/TimeZone/NegativeDSTTest.java index eb46b8d4b29f..ab9438f23887 100644 --- a/test/jdk/java/util/TimeZone/NegativeDSTTest.java +++ b/test/jdk/java/util/TimeZone/NegativeDSTTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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. */ -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Instant; import java.time.LocalDate; @@ -31,18 +31,19 @@ import java.util.Date; import java.util.TimeZone; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @test * @bug 8212970 8324065 * @summary Test whether the savings are positive in time zones that have * negative savings in the source TZ files. - * @run testng NegativeDSTTest + * @run junit NegativeDSTTest */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class NegativeDSTTest { private static final TimeZone DUBLIN = TimeZone.getTimeZone("Europe/Dublin"); @@ -51,7 +52,6 @@ public class NegativeDSTTest { private static final TimeZone CASABLANCA = TimeZone.getTimeZone("Africa/Casablanca"); private static final int ONE_HOUR = 3600_000; - @DataProvider private Object[][] negativeDST () { return new Object[][] { // TimeZone, localDate, offset, isDaylightSavings @@ -88,10 +88,11 @@ private Object[][] negativeDST () { }; } - @Test(dataProvider="negativeDST") + @ParameterizedTest + @MethodSource("negativeDST") public void test_NegativeDST(TimeZone tz, LocalDate ld, int offset, boolean isDST) { Date d = Date.from(Instant.from(ZonedDateTime.of(ld, LocalTime.MIN, tz.toZoneId()))); - assertEquals(tz.getOffset(d.getTime()), offset); - assertEquals(tz.inDaylightTime(d), isDST); + assertEquals(offset, tz.getOffset(d.getTime())); + assertEquals(isDST, tz.inDaylightTime(d)); } } diff --git a/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java b/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java index 0f1eeb883287..16e24f7cb276 100644 --- a/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java +++ b/test/jdk/java/util/TimeZone/ZoneIdRoundTripTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -25,20 +25,20 @@ import java.time.ZoneOffset; import java.util.TimeZone; -import org.testng.annotations.Test; -import org.testng.annotations.DataProvider; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @test * @bug 8285844 * @summary Checks round-trips between TimeZone and ZoneId are consistent - * @run testng ZoneIdRoundTripTest + * @run junit ZoneIdRoundTripTest */ -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ZoneIdRoundTripTest { - @DataProvider private Object[][] testZoneIds() { return new Object[][] { {ZoneId.of("Z"), 0}, @@ -60,11 +60,12 @@ private Object[][] testZoneIds() { }; } - @Test(dataProvider="testZoneIds") + @ParameterizedTest + @MethodSource("testZoneIds") public void test_ZoneIdRoundTrip(ZoneId zid, int offset) { var tz = TimeZone.getTimeZone(zid); - assertEquals(tz.getRawOffset(), offset); - assertEquals(tz.toZoneId().normalized(), zid.normalized()); + assertEquals(offset, tz.getRawOffset()); + assertEquals(zid.normalized(), tz.toZoneId().normalized()); } } diff --git a/test/jdk/java/util/Vector/ArrayManagement.java b/test/jdk/java/util/Vector/ArrayManagement.java index ce4e695487c8..c1fa6d1c9bcb 100644 --- a/test/jdk/java/util/Vector/ArrayManagement.java +++ b/test/jdk/java/util/Vector/ArrayManagement.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. * Copyright 2016 Google, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -25,7 +26,7 @@ * @test * @bug 8148174 * @summary brittle white box test of internal array management - * @run testng ArrayManagement + * @run junit ArrayManagement */ import java.lang.reflect.Field; @@ -35,8 +36,8 @@ import java.util.List; import java.util.SplittableRandom; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class ArrayManagement { @@ -61,9 +62,9 @@ public void ensureCapacity(int minCapacity) { super.ensureCapacity(minCapacity); assertTrue(capacity() >= minCapacity); if (minCapacity <= oldCapacity) - assertEquals(capacity(), oldCapacity); + assertEquals(oldCapacity, capacity()); if (minCapacity > 0) - assertEquals(modCount(), oldModCount + 1); + assertEquals(oldModCount + 1, modCount()); } } @@ -89,117 +90,117 @@ static void addOneElement(PublicVector list) { case 3: assertTrue(list.addAll(size, singletonList())); break; default: throw new AssertionError(); } - assertEquals(list.modCount(), modCount + 1); - assertEquals(list.size(), size + 1); + assertEquals(modCount + 1, list.modCount()); + assertEquals(size + 1, list.size()); } @Test public void defaultCapacity() { PublicVector list = new PublicVector<>(); - assertEquals(new PublicVector().capacity(), DEFAULT_CAPACITY); + assertEquals(DEFAULT_CAPACITY, new PublicVector().capacity()); for (int i = 0; i < DEFAULT_CAPACITY; i++) { addOneElement(list); - assertEquals(list.capacity(), DEFAULT_CAPACITY); + assertEquals(DEFAULT_CAPACITY, list.capacity()); } addOneElement(list); - assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY)); + assertEquals(newCapacity(DEFAULT_CAPACITY), list.capacity()); } @Test public void defaultCapacityEnsureCapacity() { PublicVector list = new PublicVector<>(); for (int i = 0; i <= DEFAULT_CAPACITY; i++) { list.ensureCapacity(i); // no-op! - assertEquals(list.capacity(), DEFAULT_CAPACITY); + assertEquals(DEFAULT_CAPACITY, list.capacity()); } for (int i = 0; i < DEFAULT_CAPACITY; i++) { addOneElement(list); - assertEquals(list.capacity(), DEFAULT_CAPACITY); + assertEquals(DEFAULT_CAPACITY, list.capacity()); } addOneElement(list); - assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY)); + assertEquals(newCapacity(DEFAULT_CAPACITY), list.capacity()); { int capacity = list.capacity(); list.ensureCapacity(capacity + 1); - assertEquals(list.capacity(), newCapacity(capacity)); + assertEquals(newCapacity(capacity), list.capacity()); } { int capacity = list.capacity(); list.ensureCapacity(3 * capacity); - assertEquals(list.capacity(), 3 * capacity); + assertEquals(3 * capacity, list.capacity()); } } @Test public void ensureCapacityBeyondDefaultCapacity() { PublicVector list = new PublicVector<>(); list.ensureCapacity(DEFAULT_CAPACITY + 1); - assertEquals(list.capacity(), newCapacity(DEFAULT_CAPACITY)); + assertEquals(newCapacity(DEFAULT_CAPACITY), list.capacity()); } @Test public void explicitZeroCapacity() { PublicVector list = new PublicVector<>(0); - assertEquals(list.capacity(), 0); + assertEquals(0, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 1); + assertEquals(1, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 2); + assertEquals(2, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 4); + assertEquals(4, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 4); + assertEquals(4, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); list.clear(); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); } @Test public void explicitZeroCapacityWithCapacityIncrement() { PublicVector list = new PublicVector<>(0, 2); - assertEquals(list.capacity(), 0); + assertEquals(0, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 2); + assertEquals(2, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 2); + assertEquals(2, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 4); + assertEquals(4, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 4); + assertEquals(4, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 6); + assertEquals(6, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 6); + assertEquals(6, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); list.clear(); - assertEquals(list.capacity(), 8); + assertEquals(8, list.capacity()); } @Test public void explicitLargeCapacity() { int n = DEFAULT_CAPACITY * 3; PublicVector list = new PublicVector<>(n); - assertEquals(list.capacity(), n); + assertEquals(n, list.capacity()); list.ensureCapacity(0); list.ensureCapacity(n); for (int i = 0; i < n; i++) addOneElement(list); - assertEquals(list.capacity(), n); + assertEquals(n, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), newCapacity(n)); + assertEquals(newCapacity(n), list.capacity()); } @Test public void explicitLargeCapacityWithCapacityIncrement() { int n = DEFAULT_CAPACITY * 3; PublicVector list = new PublicVector<>(n, 2); - assertEquals(list.capacity(), n); + assertEquals(n, list.capacity()); list.ensureCapacity(0); list.ensureCapacity(n); for (int i = 0; i < n; i++) addOneElement(list); - assertEquals(list.capacity(), n); + assertEquals(n, list.capacity()); addOneElement(list); - assertEquals(list.capacity(), n + 2); + assertEquals(n + 2, list.capacity()); } @Test public void emptyArraysAreNotShared() { diff --git a/test/jdk/java/util/logging/LoggingDeadlock2.java b/test/jdk/java/util/logging/LoggingDeadlock2.java index e8a0bb49d87d..dbb804940e2a 100644 --- a/test/jdk/java/util/logging/LoggingDeadlock2.java +++ b/test/jdk/java/util/logging/LoggingDeadlock2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -309,7 +309,7 @@ private static ProcessResults run(Process p) { errAccumulator.join(); out = outAccumulator.result(); - err = errAccumulator.result(); + err = errAccumulator.result().replaceAll(".* VM warning:.* deprecated.*\\R", ""); } catch (Throwable t) { throwable = t; } diff --git a/test/jdk/javax/accessibility/JSpinner/CustomSpinnerAccessibilityTest.java b/test/jdk/javax/accessibility/JSpinner/CustomSpinnerAccessibilityTest.java new file mode 100644 index 000000000000..12c98c951104 --- /dev/null +++ b/test/jdk/javax/accessibility/JSpinner/CustomSpinnerAccessibilityTest.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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.GridLayout; +import java.lang.reflect.InvocationTargetException; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JSpinner; +import javax.swing.SpinnerListModel; + +/* + * @test + * @bug 8286258 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @requires (os.family == "mac") + * @summary Checks that JSpinner with custom model announces + * the value every time it is changed + * @run main/manual CustomSpinnerAccessibilityTest + */ + +public class CustomSpinnerAccessibilityTest extends JPanel { + private static final String INSTRUCTIONS = """ + 1. Turn on VoiceOver + 2. In the window named "Test UI" click on the text editor inside the + spinner component + 3. Using up and down arrows change current month + 4. Wait for the VoiceOver to finish speaking + 5. Repeat steps 3 and 4 couple more times + + If every time value of the spinner is changed VoiceOver + announces the new value click "Pass". + If instead the value is narrated only partially + and the new value is never fully narrated press "Fail". + """; + + public CustomSpinnerAccessibilityTest() { + super(new GridLayout(0, 2)); + String[] monthStrings = new java.text.DateFormatSymbols().getMonths(); + int lastIndex = monthStrings.length - 1; + if (monthStrings[lastIndex] == null + || monthStrings[lastIndex].length() <= 0) { + String[] tmp = new String[lastIndex]; + System.arraycopy(monthStrings, 0, + tmp, 0, lastIndex); + monthStrings = tmp; + } + + SpinnerListModel model = new SpinnerListModel(monthStrings); + JLabel label = new JLabel("Month: "); + add(label); + JSpinner spinner = new JSpinner(model); + label.setLabelFor(spinner); + add(spinner); + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame.builder() + .title("Custom Spinner Accessibility Test") + .instructions(INSTRUCTIONS) + .testUI(CustomSpinnerAccessibilityTest::new) + .build() + .awaitAndCheck(); + } +} diff --git a/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java b/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java new file mode 100644 index 000000000000..2def2f69d6e9 --- /dev/null +++ b/test/jdk/javax/net/ssl/HttpsURLConnection/SubjectAltNameIP.java @@ -0,0 +1,379 @@ +/* + * 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. + */ + +/* + * @test + * @bug 8369950 + * @summary Test that the HttpsURLConnection does not set IP address literals for + * SNI hostname during TLS handshake + * @library /test/lib + * @modules java.base/sun.net.util + * @comment Insert -Djavax.net.debug=all into the following lines to enable SSL debugging + * @run main/othervm SubjectAltNameIP 127.0.0.1 + * @run main/othervm SubjectAltNameIP [::1] + */ + +import javax.net.ssl.HandshakeCompletedListener; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import java.io.BufferedWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.net.InetAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.URI; +import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; + +import jdk.test.lib.Asserts; +import jdk.test.lib.net.IPSupport; +import jdk.test.lib.net.SimpleSSLContext; +import jtreg.SkippedException; +import sun.net.util.IPAddressUtil; + +public class SubjectAltNameIP { + + // Is the server ready to serve? + private final CountDownLatch serverReady = new CountDownLatch(1); + + // Use any free port by default. + volatile int serverPort = 0; + + // Stores an exception thrown by server in a separate thread. + volatile Exception serverException = null; + + // SSLSocket object created by HttpsClient internally. + SSLSocket clientSSLSocket = null; + + // The hostname the server socket is bound to. + String hostName; + + static final byte[] requestEnd = new byte[] {'\r', '\n', '\r', '\n' }; + + // Read until the end of the request. + void readOneRequest(InputStream is) throws IOException { + int requestEndCount = 0, r; + while ((r = is.read()) != -1) { + if (r == requestEnd[requestEndCount]) { + requestEndCount++; + if (requestEndCount == 4) { + break; + } + } else { + requestEndCount = 0; + } + } + } + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLServerSocketFactory sslssf = + new SimpleSSLContext().get().getServerSocketFactory(); + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslssf.createServerSocket( + serverPort, 0, + InetAddress.getByName(hostName)); + sslServerSocket.setEnabledProtocols(new String[]{"TLSv1.3"}); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal the client, the server is ready to accept connection. + */ + serverReady.countDown(); + + SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); + OutputStream sslOS = sslSocket.getOutputStream(); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sslOS)); + bw.write("HTTP/1.1 200 OK\r\n\r\n"); + bw.flush(); + readOneRequest(sslSocket.getInputStream()); + sslSocket.close(); + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + serverReady.await(); + if (serverException != null) { + throw new RuntimeException("Server failed to start.", serverException); + } + + SSLSocketFactory sf = new SimpleSSLContext().get().getSocketFactory(); + URI uri = new URI("https://" + hostName + ":" + serverPort + "/index.html"); + HttpsURLConnection conn = (HttpsURLConnection)uri.toURL().openConnection(); + + /* + * Simulate an external JSSE implementation and store the client SSLSocket + * used internally. + */ + conn.setSSLSocketFactory(wrapSocketFactory(sf, + sslSocket -> { + Asserts.assertEquals(null, clientSSLSocket, "clientSSLSocket is"); + clientSSLSocket = sslSocket; + })); + conn.getInputStream(); + + var sniSN = clientSSLSocket.getSSLParameters().getServerNames(); + if (sniSN != null && !sniSN.isEmpty()) { + throw new RuntimeException("SNI server name '" + + sniSN.getFirst() + "' must not be set."); + } + + if (conn.getResponseCode() == -1) { + throw new RuntimeException("getResponseCode() returns -1"); + } + } + + public static void main(String[] args) throws Exception { + + if (IPAddressUtil.isIPv6LiteralAddress(args[0]) && !IPSupport.hasIPv6()) { + throw new SkippedException("Skipping test - IPv6 is not supported"); + } + /* + * Start the tests. + */ + new SubjectAltNameIP(args[0]); + } + + Thread serverThread = null; + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + SubjectAltNameIP(String host) throws Exception { + hostName = host; + startServer(); + doClientSide(); + + /* + * Wait for other side to close down. + */ + serverThread.join(); + + if (serverException != null) + throw serverException; + } + + void startServer() { + serverThread = new Thread(() -> { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Store the exception and release the client. + */ + serverException = e; + serverReady.countDown(); + } + }); + serverThread.start(); + } + + /* + * Wraps SSLSocketImpl to simulate a different JSSE implementation + */ + private static SSLSocketFactory wrapSocketFactory(final SSLSocketFactory wrap, final Consumer store) { + return new SSLSocketFactory() { + @Override + public String[] getDefaultCipherSuites() { + return wrap.getDefaultCipherSuites(); + } + @Override + public String[] getSupportedCipherSuites() { + return wrap.getSupportedCipherSuites(); + } + @Override + public Socket createSocket(Socket s, String host, int port, boolean autoClose) + throws IOException { + final SSLSocket so = + (SSLSocket) wrap.createSocket(s, host, port, autoClose); + + // store the underlying SSLSocket for later use + store.accept(so); + + return new SSLSocket() { + @Override + public void connect(SocketAddress endpoint, + int timeout) throws IOException { + so.connect(endpoint, timeout); + } + @Override + public String[] getSupportedCipherSuites() { + return so.getSupportedCipherSuites(); + } + @Override + public String[] getEnabledCipherSuites() { + return so.getEnabledCipherSuites(); + } + @Override + public void setEnabledCipherSuites(String[] suites) { + so.setEnabledCipherSuites(suites); + } + @Override + public String[] getSupportedProtocols() { + return so.getSupportedProtocols(); + } + @Override + public String[] getEnabledProtocols() { + return so.getEnabledProtocols(); + } + @Override + public void setEnabledProtocols(String[] protocols) { + so.setEnabledProtocols(protocols); + } + @Override + public SSLSession getSession() { + return so.getSession(); + } + @Override + public SSLSession getHandshakeSession() { + return so.getHandshakeSession(); + } + @Override + public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { + so.addHandshakeCompletedListener(listener); + } + @Override + public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { + so.removeHandshakeCompletedListener(listener); + } + @Override + public void startHandshake() throws IOException { + so.startHandshake(); + } + @Override + public void setUseClientMode(boolean mode) { + so.setUseClientMode(mode); + } + @Override + public boolean getUseClientMode() { + return so.getUseClientMode(); + } + @Override + public void setNeedClientAuth(boolean need) { + } + @Override + public boolean getNeedClientAuth() { + return false; + } + @Override + public void setWantClientAuth(boolean want) { + } + @Override + public boolean getWantClientAuth() { + return false; + } + @Override + public void setEnableSessionCreation(boolean flag) { + so.setEnableSessionCreation(flag); + } + @Override + public boolean getEnableSessionCreation() { + return so.getEnableSessionCreation(); + } + @Override + public void close() throws IOException { + so.close(); + } + @Override + public boolean isClosed() { + return so.isClosed(); + } + @Override + public void shutdownInput() throws IOException { + so.shutdownInput(); + } + @Override + public boolean isInputShutdown() { + return so.isInputShutdown(); + } + @Override + public void shutdownOutput() throws IOException { + so.shutdownOutput(); + } + @Override + public boolean isOutputShutdown() { + return so.isOutputShutdown(); + } + @Override + public InputStream getInputStream() throws IOException { + return so.getInputStream(); + } + @Override + public OutputStream getOutputStream() throws IOException { + return so.getOutputStream(); + } + @Override + public SSLParameters getSSLParameters() { + return so.getSSLParameters(); + } + @Override + public void setSSLParameters(SSLParameters params) { + so.setSSLParameters(params); + } + }; + } + @Override + public Socket createSocket(String h, int p) { + return null; + } + @Override + public Socket createSocket(String h, int p, InetAddress ipa, int lp) { + return null; + } + @Override + public Socket createSocket(InetAddress h, int p) { + return null; + } + @Override + public Socket createSocket(InetAddress a, int p, InetAddress l, int lp) { + return null; + } + }; + } +} diff --git a/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java b/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java index 0e34f4865ab8..16e009ed5895 100644 --- a/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java +++ b/test/jdk/javax/net/ssl/SSLSocket/Tls13PacketSize.java @@ -107,5 +107,10 @@ protected void runClientApplication(SSLSocket socket) throws Exception { throw new Exception( "Server record plaintext exceeds 2^14 octets: " + extra); } + + int drained = 1; + while (drained < appData.length) { + drained += sslIS.read(appData, drained, appData.length - drained); + } } } diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java index 79476cbb81eb..eb6ecbb12b82 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkClient.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -25,6 +25,7 @@ import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.net.ssl.SNIHostName; @@ -86,6 +87,16 @@ protected void configClientSocket(Builder builder) throws SocketException { if (builder.getAppProtocols() != null) { sslParams.setApplicationProtocols(builder.getAppProtocols()); } + + NamedGroup[] namedGroups = builder.getNamedGroups(); + if (namedGroups != null + && namedGroups.length > 0) { + String[] namedGroupStrs = Arrays.stream(namedGroups) + .map(NamedGroup::name) + .toArray(String[]::new); + sslParams.setNamedGroups(namedGroupStrs); + } + socket.setSSLParameters(sslParams); } diff --git a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java index 1521325b65ac..20bfffbac7d9 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java +++ b/test/jdk/javax/net/ssl/TLSCommon/interop/JdkServer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -22,9 +22,9 @@ */ import java.io.IOException; -import java.net.InetAddress; import java.net.SocketException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.net.ssl.SNIHostName; @@ -85,6 +85,16 @@ protected void configServerSocket(Builder builder) throws SocketException { System.out.println("appProtocol: " + appProtocol); } } + + NamedGroup[] namedGroups = builder.getNamedGroups(); + if (namedGroups != null + && namedGroups.length > 0) { + String[] namedGroupStrs = Arrays.stream(namedGroups) + .map(NamedGroup::name) + .toArray(String[]::new); + sslParams.setNamedGroups(namedGroupStrs); + } + serverSocket.setSSLParameters(sslParams); } diff --git a/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java b/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java index 0891523ac11f..51706cec9270 100644 --- a/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java +++ b/test/jdk/javax/net/ssl/templates/SSLSocketTemplate.java @@ -190,6 +190,7 @@ protected void doServerSide() throws Exception { try { sslServerSocket.setSoTimeout(30000); sslSocket = (SSLSocket)sslServerSocket.accept(); + System.out.println("Connection established on port : " +serverPort); } catch (SocketTimeoutException ste) { // Ignore the test case if no connection within 30 seconds. System.out.println( @@ -228,6 +229,7 @@ protected void doServerSide() throws Exception { } } finally { sslSocket.close(); + System.out.println("Connection closed on port : " +serverPort); } } diff --git a/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java b/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java index 27290738a0cc..afac39b83fbf 100644 --- a/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java +++ b/test/jdk/javax/sound/midi/MidiDeviceConnectors/TestAllDevices.java @@ -24,6 +24,7 @@ /** * @test * @bug 4933700 + * @key sound * @summary Tests that default devices return MidiDeviceTransmitter/Receiver and returned objects return correct MidiDevice * @compile TestAllDevices.java * @run main TestAllDevices diff --git a/test/jdk/javax/sound/midi/Sequencer/Looping.java b/test/jdk/javax/sound/midi/Sequencer/Looping.java index 9bcc9254653d..9a5a89c64723 100644 --- a/test/jdk/javax/sound/midi/Sequencer/Looping.java +++ b/test/jdk/javax/sound/midi/Sequencer/Looping.java @@ -36,7 +36,7 @@ * @test * @bug 4204105 * @summary RFE: add loop() method(s) to Sequencer - * @key intermittent + * @key sound */ public class Looping { diff --git a/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java b/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java index 2a33d28b3f53..e258b4cb53ad 100644 --- a/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java +++ b/test/jdk/javax/sound/midi/SysexMessage/SendRawSysexMessage.java @@ -35,6 +35,7 @@ /** * @test * @bug 8237495 8301310 + * @key sound * @summary fail with memory errors when asked to send a sysex message starting * with 0xF7 */ diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java index efb57eeeae2d..05ba16cded56 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/ExpectedNPEOnNull.java @@ -32,6 +32,7 @@ /** * @test * @bug 8143909 + * @key sound * @author Sergey Bylokhov */ public final class ExpectedNPEOnNull { diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java index 8eabb992bca9..71d27c4943c0 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/FakeInfo.java @@ -35,6 +35,7 @@ /** * @test * @bug 8059743 + * @key sound * @summary MidiDeviceProvider shouldn't returns incorrect results in case of * some unknown MidiDevice.Info * @author Sergey Bylokhov diff --git a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java index 685a5e8af629..5d37759fbad7 100644 --- a/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java +++ b/test/jdk/javax/sound/midi/spi/MidiDeviceProvider/UnsupportedInfo.java @@ -30,6 +30,7 @@ /** * @test * @bug 8058115 + * @key sound * @summary MidiDeviceProvider shouldn't returns incorrect results in case of * unsupported MidiDevice.Info * @author Sergey Bylokhov diff --git a/test/jdk/javax/sound/sampled/Clip/AutoCloseTimeCheck.java b/test/jdk/javax/sound/sampled/Clip/AutoCloseTimeCheck.java index 940124b244ba..ecf958d4a291 100644 --- a/test/jdk/javax/sound/sampled/Clip/AutoCloseTimeCheck.java +++ b/test/jdk/javax/sound/sampled/Clip/AutoCloseTimeCheck.java @@ -39,6 +39,7 @@ /** * @test + * @key sound * @bug 8202264 */ public final class AutoCloseTimeCheck { diff --git a/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java b/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java index c417c5ad8d0b..8ffd760b08ac 100644 --- a/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java +++ b/test/jdk/javax/sound/sampled/Clip/IsRunningHang.java @@ -36,6 +36,7 @@ /** * @test * @bug 8156169 + * @key sound * @run main/othervm/timeout=300 IsRunningHang */ public final class IsRunningHang { diff --git a/test/jdk/javax/sound/sampled/Clip/bug5070081.java b/test/jdk/javax/sound/sampled/Clip/bug5070081.java index e7bf7e30de2a..89e9d591d28d 100644 --- a/test/jdk/javax/sound/sampled/Clip/bug5070081.java +++ b/test/jdk/javax/sound/sampled/Clip/bug5070081.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * 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,8 @@ /* * @test - * @bug 5070081 + * @key sound + * @bug 5070081 8376152 * @summary Tests that javax.sound.sampled.Clip does not loses position through * stop/start */ diff --git a/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java b/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java index 079a785de8bd..42e70521b2b6 100644 --- a/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java +++ b/test/jdk/javax/sound/sampled/DataLine/LongFramePosition.java @@ -29,6 +29,7 @@ /** * @test * @bug 5049129 + * @key sound * @summary DataLine.getLongFramePosition */ public class LongFramePosition { diff --git a/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java b/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java index 177ebce85a01..a99caeea0552 100644 --- a/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java +++ b/test/jdk/javax/sound/sampled/DirectAudio/bug6372428.java @@ -31,6 +31,7 @@ /* * @test * @bug 6372428 + * @key sound * @summary playback and capture doesn't interrupt after terminating thread that * calls start() * @run main bug6372428 diff --git a/test/jdk/javax/swing/AbstractButton/bug4133768.java b/test/jdk/javax/swing/AbstractButton/bug4133768.java new file mode 100644 index 000000000000..ad5f56c01498 --- /dev/null +++ b/test/jdk/javax/swing/AbstractButton/bug4133768.java @@ -0,0 +1,162 @@ +/* + * 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. + */ + +/* + * @test + * @bug 4133768 4363569 + * @summary Tests how button displays its icons + * @key headful + * @run main bug4133768 + */ + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.IOException; +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JCheckBox; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JToggleButton; +import javax.swing.SwingUtilities; + +public class bug4133768 { + private static Icon RED, GREEN; + private static JFrame f; + private static AbstractButton[] buttons; + private static volatile Point buttonLocation; + private static volatile int buttonWidth; + private static volatile int buttonHeight; + private static Robot robot; + + public static void main(String[] args) throws Exception { + try { + createTestImages(); + createUI(); + robot = new Robot(); + robot.delay(1000); + for (AbstractButton b : buttons) { + testEnabledButton(b); + } + for (AbstractButton b : buttons) { + b.setEnabled(false); + robot.delay(1000); + testDisabledButton(b); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } + + private static void createTestImages() throws IOException { + int imageWidth = 32; + int imageHeight = 32; + BufferedImage redImg = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_INT_RGB); + Graphics2D g = redImg.createGraphics(); + g.setColor(Color.RED); + g.fillRect(0, 0, imageWidth, imageHeight); + g.dispose(); + RED = new ImageIcon(redImg); + BufferedImage greenImg = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_INT_RGB); + g = greenImg.createGraphics(); + g.setColor(Color.GREEN); + g.fillRect(0, 0, imageWidth, imageHeight); + g.dispose(); + GREEN = new ImageIcon(greenImg); + } + + private static void createUI() throws Exception { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("ButtonIconsTest"); + buttons = new AbstractButton[] { + new JToggleButton(), + new JRadioButton(), + new JCheckBox() + }; + + JPanel buttonPanel = new JPanel(); + for (int i = 0; i < buttons.length; i++) { + AbstractButton b = buttons[i]; + b.setIcon(RED); + b.setSelected(true); + b.setRolloverSelectedIcon(GREEN); + buttonPanel.add(b); + } + f.setLayout(new GridLayout(2, 1)); + f.add(buttonPanel); + f.pack(); + f.setLocationRelativeTo(null); + f.setAlwaysOnTop(true); + f.setVisible(true); + }); + } + + private static void testEnabledButton(AbstractButton button) throws Exception { + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + buttonLocation = button.getLocationOnScreen(); + buttonWidth = button.getWidth(); + buttonHeight = button.getHeight(); + }); + robot.mouseMove(buttonLocation.x + buttonWidth / 2, + buttonLocation.y + buttonHeight / 2 ); + robot.delay(1000); + Color buttonColor = robot.getPixelColor(buttonLocation.x + + buttonWidth / 2, buttonLocation.y + buttonHeight / 2); + if (!buttonColor.equals(Color.GREEN)) { + throw new RuntimeException("Button roll over color is : " + + buttonColor + " but it should be : " + Color.GREEN); + } + } + + private static void testDisabledButton(AbstractButton button) throws Exception { + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + buttonLocation = button.getLocationOnScreen(); + buttonWidth = button.getWidth(); + buttonHeight = button.getHeight(); + }); + robot.mouseMove(buttonLocation.x + buttonWidth / 2, + buttonLocation.y + buttonHeight / 2 ); + robot.delay(1000); + Color buttonColor = robot.getPixelColor(buttonLocation.x + + buttonWidth / 2, buttonLocation.y + buttonHeight / 2); + if (buttonColor.equals(Color.GREEN) || + buttonColor.equals(Color.RED)) { + throw new RuntimeException("Disabled button color should not be : " + + buttonColor); + } + } +} diff --git a/test/jdk/javax/swing/AbstractButton/bug4391622.java b/test/jdk/javax/swing/AbstractButton/bug4391622.java new file mode 100644 index 000000000000..7d3e8588f175 --- /dev/null +++ b/test/jdk/javax/swing/AbstractButton/bug4391622.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2001, 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.Color; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.awt.image.BufferedImage; +import java.io.IOException; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 4391622 + * @summary The toolbar's button which is added as action should ignore text + * @key headful + * @run main bug4391622 + */ + +public class bug4391622 { + private static Icon RED, GREEN; + private static JButton bt; + private static JFrame f; + private static volatile Point buttonLocation; + private static volatile int buttonWidth; + private static volatile int buttonHeight; + + public static void main(String[] args) throws Exception { + try { + createTestImages(); + createUI(); + runTest(); + verifyTest(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } + + private static void createTestImages() throws IOException { + int imageWidth = 32; + int imageHeight = 32; + BufferedImage redImg = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_INT_RGB); + Graphics2D g = redImg.createGraphics(); + g.setColor(Color.RED); + g.fillRect(0, 0, imageWidth, imageHeight); + g.dispose(); + RED = new ImageIcon(redImg); + BufferedImage greenImg = new BufferedImage(imageWidth, imageHeight, + BufferedImage.TYPE_INT_RGB); + g = greenImg.createGraphics(); + g.setColor(Color.GREEN); + g.fillRect(0, 0, imageWidth, imageHeight); + g.dispose(); + GREEN = new ImageIcon(greenImg); + } + + private static void createUI() throws Exception { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4391622"); + Action changeIt = new ChangeIt(); + + JToolBar toolbar = new JToolBar(); + bt = toolbar.add(changeIt); + f.add(bt); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + } + + private static void runTest() throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(500); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + buttonLocation = bt.getLocationOnScreen(); + buttonWidth = bt.getWidth(); + buttonHeight = bt.getHeight(); + }); + robot.mouseMove(buttonLocation.x + buttonWidth / 2, + buttonLocation.y + buttonHeight / 2 ); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + } + + private static void verifyTest() { + if (bt.getText() != null) { + throw new RuntimeException("The toolbar's button shouldn't" + + " have any text."); + } + } + + public static class ChangeIt extends AbstractAction { + private boolean c = true; + + public ChangeIt() { + putValue(Action.NAME, "Red"); + putValue(Action.SMALL_ICON, RED); + } + + public void actionPerformed(ActionEvent event) { + c = !c; + putValue(Action.NAME, c ? "Red" : "Green"); + putValue(Action.SMALL_ICON, c ? RED : GREEN); + } + } +} diff --git a/test/jdk/javax/swing/JButton/SwingButtonResizeTestWithOpenGL.java b/test/jdk/javax/swing/JButton/SwingButtonResizeTestWithOpenGL.java new file mode 100644 index 000000000000..5b21c07f71e3 --- /dev/null +++ b/test/jdk/javax/swing/JButton/SwingButtonResizeTestWithOpenGL.java @@ -0,0 +1,352 @@ +/* + * 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 + * 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.FlowLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.image.BufferedImage; +import java.awt.image.ColorModel; +import java.awt.image.Raster; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.imageio.ImageIO; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 8338103 + * @key headful + * @summary Verifies that the OpenGL pipeline does not create artifacts + * with swing components after window is zoomed to maximum size and then + * resized back to normal. The test case simulates this operation using + * a JButton. A file image of the component will be saved before and after + * the window resize if the test fails. The test passes if both the button + * images are the same. + * @run main/othervm -Dsun.java2d.opengl=true -Dsun.java2d.opengl.fbobject=false SwingButtonResizeTestWithOpenGL + * @run main/othervm -Dsun.java2d.opengl=true -Dsun.java2d.opengl.fbobject=true SwingButtonResizeTestWithOpenGL + * @run main/othervm -Dsun.java2d.opengl=false SwingButtonResizeTestWithOpenGL + * @run main/othervm SwingButtonResizeTestWithOpenGL + */ +/* + * @test + * @key headful + * @requires (os.family == "windows") + * @run main/othervm -Dsun.java2d.d3d=false SwingButtonResizeTestWithOpenGL + * @run main/othervm -Dsun.java2d.d3d=true SwingButtonResizeTestWithOpenGL + */ +/* + * @test + * @key headful + * @requires (os.family == "linux") + * @run main/othervm -Dsun.java2d.xrender=false SwingButtonResizeTestWithOpenGL + * @run main/othervm -Dsun.java2d.xrender=true SwingButtonResizeTestWithOpenGL + */ +/* + * @test + * @key headful + * @requires (os.family == "mac") + * @run main/othervm -Dsun.java2d.metal=false SwingButtonResizeTestWithOpenGL + * @run main/othervm -Dsun.java2d.metal=true SwingButtonResizeTestWithOpenGL + */ +public class SwingButtonResizeTestWithOpenGL { + private static Robot robot; + private static CountDownLatch focusGainedLatch; + private JFrame frame; + private JButton button; + + public SwingButtonResizeTestWithOpenGL() { + + try { + SwingUtilities.invokeAndWait(() -> createGUI()); + } catch (Exception e) { + throw new RuntimeException("Problems creating GUI"); + } + } + + private void createGUI() { + frame = new JFrame("SwingButtonResizeTestWithOpenGL"); + button = new JButton("Button A"); + frame.setLocation(200, 200); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + button.setPreferredSize(new Dimension(300, 300)); + button.setFocusPainted(false); + button.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent fe) { + focusGainedLatch.countDown(); + } + }); + frame.getContentPane().setLayout(new FlowLayout()); + frame.getContentPane().add(button); + frame.pack(); + frame.setVisible(true); + frame.toFront(); + } + + public static void main(String[] args) throws Exception { + focusGainedLatch = new CountDownLatch(1); + SwingButtonResizeTestWithOpenGL test = + new SwingButtonResizeTestWithOpenGL(); + test.runTest(); + } + + public void runTest() throws Exception { + BufferedImage bimage1; + BufferedImage bimage2; + + try { + robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + if (focusGainedLatch.await(3, TimeUnit.SECONDS)) { + System.out.println("Button focus gained..."); + } else { + System.out.println("Button focus not gained..."); + throw new RuntimeException( + "Can't gain focus on button even after waiting " + + "too long.."); + } + + System.out.println("Getting initial button image..image1"); + bimage1 = getButtonImage(); + + // some platforms may not support maximize frame + if (frame.getToolkit().isFrameStateSupported( + JFrame.MAXIMIZED_BOTH)) { + // maximize frame from normal size + frame.setExtendedState(JFrame.MAXIMIZED_BOTH); + System.out.println("Frame is maximized"); + robot.waitForIdle(); + robot.delay(100); + + if (frame.getToolkit().isFrameStateSupported(JFrame.NORMAL)) { + System.out.println("Frame is back to normal"); + // resize from maximum size to normal + frame.setExtendedState(JFrame.NORMAL); + robot.waitForIdle(); + robot.delay(100); + // capture image of JButton after resize + System.out.println( + "Getting image of JButton after resize..image2"); + bimage2 = getButtonImage(); + + // compare button images from before and after frame resize + DiffImage di = new DiffImage(bimage1.getWidth(), + bimage1.getHeight()); + System.out.println( + "Taking the diff of two images, image1 and image2"); + if (!di.compare(bimage1, bimage2)) { + throw new RuntimeException( + "Button renderings are different after window " + + "resize, num of Diff Pixels=" + + di.getNumDiffPixels()); + } else { + System.out.println("Test passed..."); + } + + } else { + System.out.println( + "Test skipped: JFrame.NORMAL resize is " + + "not supported"); + } + + } else { + System.out.println( + "Test skipped: JFrame.MAXIMIZED_BOTH resize is " + + "not supported"); + } + } finally { + SwingUtilities.invokeAndWait(() -> disposeFrame()); + } + } + + // Capture button rendering as a BufferedImage + private BufferedImage getButtonImage() { + try { + robot.waitForIdle(); + robot.delay(500); + + AtomicReference buttonLocRef = new AtomicReference<>(); + SwingUtilities.invokeAndWait( + () -> buttonLocRef.set(button.getLocationOnScreen())); + Point buttonLoc = buttonLocRef.get(); + System.out.println("Button loc: " + buttonLoc); + return robot.createScreenCapture( + new Rectangle(buttonLoc.x, buttonLoc.y, button.getWidth(), + button.getHeight())); + } catch (Exception e) { + throw new RuntimeException( + "Problems capturing button image from Robot", e); + } + } + + private void disposeFrame() { + if(frame != null) { + frame.dispose(); + } + } + + // Save BufferedImage to PNG file + private void saveButtonImage(BufferedImage image, File file) { + if (image != null) { + try { + System.out.println( + "Saving button image to " + file.getAbsolutePath()); + ImageIO.write(image, "PNG", file); + } catch (Exception e) { + throw new RuntimeException("Could not write image file"); + } + } else { + throw new RuntimeException("BufferedImage was set to null"); + } + } + + private class DiffImage extends BufferedImage { + + public boolean diff = false; + public int nDiff = -1; + + Color bgColor; + + int threshold = 0; + + public DiffImage(int w, int h) { + super(w, h, BufferedImage.TYPE_INT_ARGB); + bgColor = Color.LIGHT_GRAY; + } + + public int getNumDiffPixels() { + return nDiff; + } + + public boolean compare(BufferedImage img1, BufferedImage img2) + throws IOException { + + int minx1 = img1.getMinX(); + int minx2 = img2.getMinX(); + int miny1 = img1.getMinY(); + int miny2 = img2.getMinY(); + + int w1 = img1.getWidth(); + int w2 = img2.getWidth(); + int h1 = img1.getHeight(); + int h2 = img2.getHeight(); + + if ((minx1 != minx2) || (miny1 != miny2) || (w1 != w2) + || (h1 != h2)) { + // image sizes are different + throw new RuntimeException( + "img1: <" + minx1 + "," + miny1 + "," + w1 + "x" + h1 + + ">" + " img2: " + minx2 + "," + miny2 + "," + w2 + "x" + + h2 + ">" + " are different sizes"); + } + // Get the actual data behind the images + Raster ras1 = img1.getData(); + Raster ras2 = img2.getData(); + + ColorModel cm1 = img1.getColorModel(); + ColorModel cm2 = img2.getColorModel(); + + int r1, r2; // red + int g1, g2; // green + int b1, b2; // blue + + Object o1 = null; + Object o2 = null; + nDiff = 0; + for (int x = minx1; x < (minx1 + w1); x++) { + for (int y = miny1; y < (miny1 + h1); y++) { + // Causes rasters to allocate data + o1 = ras1.getDataElements(x, y, o1); + // and we reuse the data on every loop + o2 = ras2.getDataElements(x, y, o2); + + r1 = cm1.getRed(o1); + r2 = cm2.getRed(o2); + g1 = cm1.getGreen(o1); + g2 = cm2.getGreen(o2); + b1 = cm1.getBlue(o1); + b2 = cm2.getBlue(o2); + + int redAbs = Math.abs(r1 - r2); + int greenAbs = Math.abs(g1 - g2); + int blueAbs = Math.abs(b1 - b2); + if ((redAbs > threshold) + || (greenAbs > threshold) + || (blueAbs > threshold)) { + // pixel is different + setDiffPixel(x, y, redAbs, greenAbs, blueAbs); + nDiff++; + } else { + setSamePixel(x, y); + } + + } + } + if (nDiff != 0) { + ImageIO.write(this, "png", + new File("diffImage.png")); + saveButtonImage(img1, new File("image1.png")); + saveButtonImage(img2, new File("image2.png")); + } + return nDiff == 0; + } + + void setDiffPixel(int x, int y, int r, int g, int b) { + diff = true; + setPixelValue(x, y, 255, r, g, b); + } + + void setSamePixel(int x, int y) { + if (bgColor != null) { + setPixelValue(x, y, 255, bgColor.getRed(), + bgColor.getGreen(), + bgColor.getBlue()); + } else { + setPixelValue(x, y, 255, Color.black.getRed(), + Color.black.getGreen(), Color.black.getBlue()); + } + } + + void setPixelValue(int x, int y, int a, int r, int g, int b) { + // setRGB uses BufferedImage.TYPE_INT_ARGB format + int pixel = + ((a & 0xff) << 24) + ((r & 0xff) << 16) + ((g & 0xff) << 8) + + ((b & 0xff)); + setRGB(x, y, pixel); + } + + } + +} + + diff --git a/test/jdk/javax/swing/JColorChooser/Test4234761.java b/test/jdk/javax/swing/JColorChooser/Test4234761.java index c2b2d9ed7b9b..fb55ca37feb7 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4234761.java +++ b/test/jdk/javax/swing/JColorChooser/Test4234761.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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,10 +23,12 @@ /* * @test - * @key headful * @bug 4234761 + * @key headful * @summary RGB values sholdn't be changed in transition to HSB tab - * @author Oleg Mokhovikov + * @library /test/lib + * @build jtreg.SkippedException + * @run main Test4234761 */ import java.awt.Color; @@ -35,11 +37,17 @@ import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JTabbedPane; +import javax.swing.UIManager; + +import jtreg.SkippedException; public class Test4234761 implements PropertyChangeListener { private static final Color COLOR = new Color(51, 51, 51); public static void main(String[] args) { + if (UIManager.getLookAndFeel().getName().contains("GTK")) { + throw new SkippedException("Test skipped for GTK"); + } JColorChooser chooser = new JColorChooser(COLOR); JDialog dialog = Test4177735.show(chooser); diff --git a/test/jdk/javax/swing/JComboBox/bug4135833.java b/test/jdk/javax/swing/JComboBox/bug4135833.java new file mode 100644 index 000000000000..3b2888c862d0 --- /dev/null +++ b/test/jdk/javax/swing/JComboBox/bug4135833.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1998, 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 javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JPanel; + +/* + * @test + * @bug 4135833 + * @summary Tests that JComboBox draws correctly if the first item in list is an empty string + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4135833 + */ + +public class bug4135833 { + private static final String INSTRUCTIONS = """ + Press the combo box. If the popup is readable and appears to be sized properly, + then it passes. The First item is blank intentionally. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Instructions") + .instructions(INSTRUCTIONS) + .columns(50) + .testUI(bug4135833::createTestUI) + .build() + .awaitAndCheck(); + } + + public static JFrame createTestUI() { + JFrame frame = new JFrame("bug4135833"); + JPanel panel = new JPanel(); + JComboBox comboBox = new JComboBox(new Object[]{"", "Bob", "Hank", "Joe", "Fred"}); + panel.add(comboBox); + frame.add(panel); + frame.pack(); + return frame; + } +} diff --git a/test/jdk/javax/swing/JComboBox/bug4171819.java b/test/jdk/javax/swing/JComboBox/bug4171819.java new file mode 100644 index 000000000000..108512edf7e8 --- /dev/null +++ b/test/jdk/javax/swing/JComboBox/bug4171819.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1998, 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 javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.UIManager; + +/* + * @test + * @bug 4171819 + * @summary Tests that JComboBox uses a lower bevel border in windows + * @requires (os.family == "windows") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4171819 + */ + +public class bug4171819 { + static boolean lafOk = true; + + private static final String INSTRUCTIONS = """ + This test is for Windows L&F only. If you see + "No Windows L&F installed" label just press "Pass". + + Look at the combo box. If the border around it looks like it's + lowered rather than raised, it passes the test. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Instructions") + .instructions(INSTRUCTIONS) + .columns(50) + .testUI(bug4171819::createTestUI) + .build() + .awaitAndCheck(); + } + + public static JFrame createTestUI() { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + System.out.println("succeeded"); + } catch (Exception e) { + System.err.println("Couldn't load the Windows Look and Feel"); + lafOk = false; + } + + JFrame frame = new JFrame("bug4171819"); + JPanel panel = new JPanel(); + JComboBox comboBox; + + if (lafOk) { + comboBox = new JComboBox(new Object[]{ + "Coma Berenices", + "Triangulum", + "Camelopardis", + "Cassiopea"}); + panel.add(comboBox); + } else { + JLabel label = new JLabel("No Windows L&F installed"); + panel.add(label); + } + frame.add(panel); + frame.pack(); + return frame; + } +} diff --git a/test/jdk/javax/swing/JComboBox/bug4248128.java b/test/jdk/javax/swing/JComboBox/bug4248128.java new file mode 100644 index 000000000000..311cae4b61a3 --- /dev/null +++ b/test/jdk/javax/swing/JComboBox/bug4248128.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1999, 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.Robot; +import java.awt.event.KeyEvent; +import javax.swing.BoxLayout; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 4248128 7148092 + * @summary Tests that alt+down arrow pulls down JComboBox popup + * @key headful + * @run main bug4248128 + */ + +public class bug4248128 { + static JFrame frame; + static volatile JComboBox combo; + + public static void main(String[] args) throws Exception { + try { + Robot robot = new Robot(); + robot.setAutoDelay(250); + SwingUtilities.invokeAndWait(() -> createTestUI()); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_ALT); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> { + if (!combo.isPopupVisible()) { + throw new RuntimeException("Popup did not appear."); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + public static void createTestUI() { + frame = new JFrame("4248128 Test"); + Object[] fruits = {"Banana", "Pear", "Apple"}; + combo = new JComboBox(fruits); + frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS)); + frame.add(combo); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } +} diff --git a/test/jdk/javax/swing/JComboBox/bug4436376.java b/test/jdk/javax/swing/JComboBox/bug4436376.java new file mode 100644 index 000000000000..064efe8c9586 --- /dev/null +++ b/test/jdk/javax/swing/JComboBox/bug4436376.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2001, 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.FlowLayout; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.awt.event.InputEvent; +import javax.swing.JComboBox; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; + +/* + * @test + * @bug 4436376 + * @key headful + * @summary Tests that ComboBox items can't be deselected with Ctrl+click + * @run main bug4436376 + */ + +public class bug4436376 { + static JFrame frame; + static volatile Point p; + static volatile JComboBox combo; + + final static int SELECTED_INDEX = 2; + + public static void main(String[] args) throws Exception { + try { + Robot robot = new Robot(); + robot.setAutoDelay(250); + SwingUtilities.invokeAndWait(() -> createTestUI()); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> p = combo.getLocationOnScreen()); + robot.waitForIdle(); + + robot.mouseMove(p.x + 10, p.y + 10); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_CONTROL); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.keyRelease(KeyEvent.VK_CONTROL); + robot.waitForIdle(); + + SwingUtilities.invokeAndWait(() -> { + if (combo.getSelectedIndex() != SELECTED_INDEX) { + throw new RuntimeException("Failed: selected index has been changed"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + public static void createTestUI() { + frame = new JFrame("bug4436376"); + String[] items = new String[]{"One", "Two", "Three", "Four"}; + combo = new JComboBox(items); + combo.setSelectedIndex(SELECTED_INDEX); + + frame.setLayout(new FlowLayout()); + frame.add(combo); + frame.setLocationRelativeTo(null); + frame.pack(); + frame.setVisible(true); + } +} diff --git a/test/jdk/javax/swing/JEditorPane/TestBrowserBGColor.java b/test/jdk/javax/swing/JEditorPane/TestBrowserBGColor.java index bff0f7c4aaaa..9abe286a75db 100644 --- a/test/jdk/javax/swing/JEditorPane/TestBrowserBGColor.java +++ b/test/jdk/javax/swing/JEditorPane/TestBrowserBGColor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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,94 +23,79 @@ /* * @test - * @key headful * @bug 8213781 * @summary Verify webpage background color renders correctly in JEditorPane */ -import java.awt.Toolkit; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.io.File; import java.io.IOException; -import java.net.MalformedURLException; -import javax.swing.JDialog; +import java.util.Objects; +import java.util.stream.IntStream; + +import javax.imageio.ImageIO; import javax.swing.JEditorPane; -import javax.swing.JFrame; -import javax.swing.JScrollPane; -import javax.swing.SwingUtilities; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; -import javax.swing.text.html.HTMLFrameHyperlinkEvent; -import javax.swing.text.html.HTMLDocument; -import java.awt.Color; -import java.awt.Insets; -import java.awt.Point; -import java.awt.Robot; +import javax.swing.text.StyleConstants; +import javax.swing.text.View; + +import static java.awt.image.BufferedImage.TYPE_INT_RGB; +import static java.lang.Integer.toHexString; + +public final class TestBrowserBGColor { -public class TestBrowserBGColor extends JFrame implements HyperlinkListener { + private static final String HTML_DOC = + "" + + "" + + "" + + "Title" + + " "; - private static TestBrowserBGColor b; - private static JEditorPane browser; + private static final int SIZE = 300; public static void main(final String[] args) throws Exception { - Robot r = new Robot(); - SwingUtilities.invokeAndWait(() -> { - try { - b = new TestBrowserBGColor(); - } catch (Exception e) { - throw new RuntimeException(e); - } - b.setSize(Toolkit.getDefaultToolkit().getScreenSize()); - b.setVisible(true); - b.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - b.addWindowListener(new WindowAdapter() { - public void windowClosing(WindowEvent e) { - b.dispose(); - b = null; - } - }); - }); + JEditorPane browser = new JEditorPane("text/html", HTML_DOC); + browser.setEditable(false); + browser.setSize(SIZE, SIZE); - r.waitForIdle(); - r.delay(500); + BufferedImage image = new BufferedImage(SIZE, SIZE, TYPE_INT_RGB); + Graphics g = image.getGraphics(); + browser.paint(g); + g.dispose(); - SwingUtilities.invokeAndWait(() -> { - Insets insets = browser.getInsets(); - Point loc = browser.getLocationOnScreen(); - Color c = r.getPixelColor( loc.x + insets.left+100, - loc.y + insets.top + 100); - b.dispose(); - if (!c.equals(Color.WHITE)) { - throw new RuntimeException("webpage background color wrong"); - } - }); + Color bgColor = StyleConstants.getBackground( + getBodyView(browser.getUI() + .getRootView(browser)) + .getAttributes()); + if (!bgColor.equals(Color.WHITE)) { + saveImage(image); + throw new RuntimeException("Wrong background color: " + + toHexString(bgColor.getRGB()) + + " vs " + + toHexString(Color.WHITE.getRGB())); + } } + private static View getBodyView(final View view) { + if ("body".equals(view.getElement() + .getName())) { + return view; + } - String htmlDoc = " Title "; - - public TestBrowserBGColor() throws IOException, MalformedURLException { - browser = new JEditorPane("text/html", htmlDoc); - browser.setEditable(false); - browser.addHyperlinkListener(this); - JScrollPane scroll = new JScrollPane(browser); - getContentPane().add(scroll); + return IntStream.range(0, view.getViewCount()) + .mapToObj(view::getView) + .map(TestBrowserBGColor::getBodyView) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); } - public void hyperlinkUpdate(final HyperlinkEvent e) { - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - JEditorPane pane = (JEditorPane) e.getSource(); - if (e instanceof HTMLFrameHyperlinkEvent) { - HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e; - HTMLDocument doc = (HTMLDocument) pane.getDocument(); - doc.processHTMLFrameHyperlinkEvent(evt); - } else { - try { - pane.setPage(e.getURL()); - } catch (Throwable t) { - t.printStackTrace(); - } - } + private static void saveImage(BufferedImage image) { + try { + ImageIO.write(image, "png", + new File("html-rendering.png")); + } catch (IOException ignored) { } } } diff --git a/test/jdk/javax/swing/JFileChooser/4966171/bug4966171.java b/test/jdk/javax/swing/JFileChooser/4966171/bug4966171.java index f3b3ba684e6d..27f26d570bed 100644 --- a/test/jdk/javax/swing/JFileChooser/4966171/bug4966171.java +++ b/test/jdk/javax/swing/JFileChooser/4966171/bug4966171.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2026, Oracle and/or its affiliates. All rights reserved. * 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,8 +50,8 @@ public static void main(String[] args) throws Exception { } private static void test() { - // Will run the test no more than 10 seconds per L&F - long endtime = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + // Will run the test no more than 5 seconds per L&F + long endtime = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (System.nanoTime() < endtime) { try { var byteOut = new ByteArrayOutputStream(); diff --git a/test/jdk/javax/swing/JFileChooser/FileSizeCheck.java b/test/jdk/javax/swing/JFileChooser/FileSizeCheck.java index 056ce38a0989..6d92032e0d13 100644 --- a/test/jdk/javax/swing/JFileChooser/FileSizeCheck.java +++ b/test/jdk/javax/swing/JFileChooser/FileSizeCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -34,7 +34,6 @@ import java.util.Arrays; import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Predicate; import javax.swing.AbstractButton; import javax.swing.JFileChooser; @@ -52,6 +51,8 @@ * @requires (os.family == "linux") * @summary Verifies if the size of an empty file is shown as 0.0 KB * as well as checks the displayed file sizes are rounded up + * @library /javax/swing/regtesthelpers + * @build Util * @run main FileSizeCheck */ public class FileSizeCheck { @@ -228,31 +229,15 @@ private static void clickDetails() { } private static AbstractButton findDetailsButton(final Container container) { - Component result = findComponent(container, + Component result = Util.findComponent(container, c -> c instanceof JToggleButton button && "Details".equals(button.getToolTipText())); return (AbstractButton) result; } private static JTable findTable(final Container container) { - Component result = findComponent(container, - c -> c instanceof JTable); + Component result = Util.findComponent(container, + c -> c instanceof JTable); return (JTable) result; } - - private static Component findComponent(final Container container, - final Predicate predicate) { - for (Component child : container.getComponents()) { - if (predicate.test(child)) { - return child; - } - if (child instanceof Container cont && cont.getComponentCount() > 0) { - Component result = findComponent(cont, predicate); - if (result != null) { - return result; - } - } - } - return null; - } } diff --git a/test/jdk/javax/swing/JFileChooser/bug4759934.java b/test/jdk/javax/swing/JFileChooser/bug4759934.java index 08ccdebfb2be..c7f340ccdd0b 100644 --- a/test/jdk/javax/swing/JFileChooser/bug4759934.java +++ b/test/jdk/javax/swing/JFileChooser/bug4759934.java @@ -31,10 +31,11 @@ * @run main bug4759934 */ +import java.awt.Component; +import java.awt.Container; import java.awt.Dialog; import java.awt.Point; import java.awt.Robot; -import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import javax.swing.JButton; import javax.swing.JDialog; @@ -72,8 +73,10 @@ public static void main(String[] args) throws Exception { robot.mouseRelease(MouseEvent.BUTTON1_DOWN_MASK); robot.delay(500); - robot.keyPress(KeyEvent.VK_ESCAPE); - robot.keyRelease(KeyEvent.VK_ESCAPE); + SwingUtilities.invokeAndWait(() -> { + JButton cancelBtn = findCancelButton(jfc); + cancelBtn.doClick(); + }); robot.delay(500); SwingUtilities.invokeAndWait(() -> { @@ -121,4 +124,11 @@ private static void createDialog() { dlg.setLocation(fr.getX() + fr.getWidth() + 10, fr.getY()); dlg.setVisible(true); } + + private static JButton findCancelButton(final Container container) { + Component result = Util.findComponent(container, + c -> c instanceof JButton button + && "Cancel".equals(button.getText())); + return (JButton) result; + } } diff --git a/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/ClientDecoratedIconTest.java b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/ClientDecoratedIconTest.java new file mode 100644 index 000000000000..95098984f720 --- /dev/null +++ b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/ClientDecoratedIconTest.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2006, 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 6436437 + * @requires (os.family == "windows") + * @summary Test setIconImages() for client-decorated JFrame + * @library ../../regtesthelpers + * @run main/manual ClientDecoratedIconTest + */ + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JRootPane; +import javax.swing.JTextArea; + +public class ClientDecoratedIconTest extends SwingTestHelper implements ActionListener { + JButton passed; + JButton failed; + + java.util.List icons1; + java.util.List icons2; + IconFrame frame1; + IconFrame frame2; + + Object lock = new Object(); + boolean done = false; + + protected String getInstructions() { + StringBuilder instructionsStr = new StringBuilder(); + instructionsStr.append("This tests the functionality of the setIconImages() API\n"); + instructionsStr.append("You will see two JFrames with custom icons1. Both JFrames should have the same icon: a colored box.\n"); + instructionsStr.append("If either of the JFrames has the default, coffe-cup icon, the test fails.\n"); + instructionsStr.append("If the JFrames DO NOT both have the same colored box as their icon, the test fails.\n"); + instructionsStr.append("If both JFrames DO have the same colored box as their icon, then the test passes."); + return instructionsStr.toString(); + } + + protected Component createContentPane() { + JPanel panel = new JPanel(); + panel.setLayout(new BorderLayout()); + JTextArea instructions = new JTextArea(getInstructions()); + panel.add(instructions, BorderLayout.CENTER); + + passed = new JButton("Icons match (PASS)"); + passed.addActionListener(this); + failed = new JButton("Icons don't match (FAIL)"); + failed.addActionListener(this); + JPanel btnPanel = new JPanel(); + btnPanel.setLayout(new FlowLayout()); + btnPanel.add(passed); + btnPanel.add(failed); + panel.add(btnPanel, BorderLayout.SOUTH); + + return panel; + } + + public void onEDT10() throws IOException { + Image img1 = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + Graphics g = img1.getGraphics(); + g.setColor(Color.green); + g.fillRect(0, 0, 16, 16); + g.dispose(); + Image img2 = new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB); + g = img2.getGraphics(); + g.setColor(Color.magenta); + g.fillRect(0, 0, 24, 24); + g.dispose(); + Image img3 = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); + g = img3.getGraphics(); + g.setColor(Color.red); + g.fillRect(0, 0, 32, 32); + g.dispose(); + Image img4 = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); + g = img4.getGraphics(); + g.setColor(Color.blue); + g.fillRect(0, 0, 64, 64); + g.dispose(); + + icons1 = new ArrayList(4); + icons1.add(img1); + icons1.add(img2); + icons1.add(img3); + icons1.add(img4); + + icons2 = new ArrayList(4); + icons2.add(img4); + icons2.add(img3); + icons2.add(img2); + icons2.add(img1); + + frame1 = new IconFrame(icons1); + frame2 = new IconFrame(icons2); + + frame1.setLocation(50, 250); + frame2.setLocation(275, 250); + + frame1.setVisible(true); + frame2.setVisible(true); + } + + public void onEDT20() { + waitForCondition(new Runnable() { + public void run() { + while (true) { + synchronized(lock) { + if (done) { + return; + } + } + try { + Thread.sleep(250); + } + catch(InterruptedException e) {} + } + } + }); + System.out.println("done waiting"); + } + + public void onEDT30() { + // Needed so waitForCondition() has something to wait for :) + } + + public void actionPerformed(ActionEvent e) { + System.out.println("actionPerformed()"); + if (e.getSource() == passed) { + synchronized(lock) { + done = true; + } + } + if (e.getSource() == failed) { + throw new RuntimeException("Test Failed"); + } + } + + class IconFrame extends JFrame { + public IconFrame(java.util.List icons) { + super("Custom Icon Frame"); + setUndecorated(true); + getRootPane().setWindowDecorationStyle(JRootPane.FRAME); + setIconImages(icons); + setSize(200, 200); + } + } + + public static void main(String[] args) throws Throwable { + new ClientDecoratedIconTest().run(args); + System.out.println("end of main()"); + } +} diff --git a/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogIconTest.java b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogIconTest.java new file mode 100644 index 000000000000..a129e38d39ab --- /dev/null +++ b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogIconTest.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2006, 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 6436437 + * @requires (os.family == "windows") + * @summary Test setIconImages() for client-decorated JDialog + * @library ../../regtesthelpers + * @run main/manual DialogIconTest + */ + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Frame; +import java.awt.Image; +import java.awt.image.BufferedImage; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JPanel; +import javax.swing.JRootPane; +import javax.swing.JTextArea; + +public class DialogIconTest extends SwingTestHelper implements ActionListener { + JButton passed; + JButton failed; + + java.util.List icons1; + IconDialog dialog1; + + Object lock = new Object(); + boolean done = false; + + protected String getInstructions() { + StringBuilder instructionsStr = new StringBuilder(); + instructionsStr.append("This tests the functionality of the setIconImages() API\n"); + instructionsStr.append("You will see a client-decorated JDialog. The JDialog should have a custom icon: a solid-colored box.\n"); + instructionsStr.append("If the JDialog has a colored box for an icon, then the test passes.\n"); + instructionsStr.append("If the JDialog has the default icon, then the test fails.\n"); + return instructionsStr.toString(); + } + + protected Component createContentPane() { + JPanel panel = new JPanel(); + panel.setLayout(new BorderLayout()); + JTextArea instructions = new JTextArea(getInstructions()); + panel.add(instructions, BorderLayout.CENTER); + + passed = new JButton("Solid-color Icon (PASS)"); + passed.addActionListener(this); + failed = new JButton("Default Icon (FAIL)"); + failed.addActionListener(this); + JPanel btnPanel = new JPanel(); + btnPanel.setLayout(new FlowLayout()); + btnPanel.add(passed); + btnPanel.add(failed); + panel.add(btnPanel, BorderLayout.SOUTH); + + return panel; + } + + public void onEDT10() throws IOException { + Image img1 = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + Graphics g = img1.getGraphics(); + g.setColor(Color.green); + g.fillRect(0, 0, 16, 16); + g.dispose(); + Image img2 = new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB); + g = img2.getGraphics(); + g.setColor(Color.magenta); + g.fillRect(0, 0, 24, 24); + g.dispose(); + Image img3 = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB); + g = img3.getGraphics(); + g.setColor(Color.red); + g.fillRect(0, 0, 32, 32); + g.dispose(); + Image img4 = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); + g = img4.getGraphics(); + g.setColor(Color.blue); + g.fillRect(0, 0, 64, 64); + g.dispose(); + + icons1 = new ArrayList(4); + icons1.add(img1); + icons1.add(img2); + icons1.add(img3); + icons1.add(img4); + + dialog1 = new IconDialog(icons1); + dialog1.setLocation(50, 250); + dialog1.setVisible(true); + } + + public void onEDT20() { + waitForCondition(new Runnable() { + public void run() { + while (true) { + synchronized(lock) { + if (done) { + return; + } + } + try { + Thread.sleep(250); + } + catch(InterruptedException e) {} + } + } + }); + System.out.println("done waiting"); + } + + public void onEDT30() { + // Needed so waitForCondition() has something to wait for :) + } + + public void actionPerformed(ActionEvent e) { + System.out.println("actionPerformed()"); + if (e.getSource() == passed) { + synchronized(lock) { + done = true; + } + } + if (e.getSource() == failed) { + throw new RuntimeException("Test Failed"); + } + } + + class IconDialog extends JDialog { + public IconDialog(java.util.List icons) { + super((Frame)null, "Custom Icon Frame", false); + setUndecorated(true); + getRootPane().setWindowDecorationStyle(JRootPane.FRAME); + setIconImages(icons); + setSize(200, 200); + } + } + + public static void main(String[] args) throws Throwable { + new DialogIconTest().run(args); + System.out.println("end of main()"); + } +} diff --git a/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogInheritIcon.java b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogInheritIcon.java new file mode 100644 index 000000000000..908f83a6af43 --- /dev/null +++ b/test/jdk/javax/swing/JFrame/ClientDecoratedIcon/DialogInheritIcon.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2006, 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 6425606 + * @requires (os.family == "windows") + * @summary Test JDialog's inheritance of icons set with JFrame.setIconImages() + * @library ../../regtesthelpers + * @run main/manual DialogInheritIcon + */ + +import javax.swing.JDialog; + +public class DialogInheritIcon extends ClientDecoratedIconTest { + JDialog dialog1; + JDialog dialog2; + + /* + * @Override + */ + protected String getInstructions() { + StringBuilder instructionsStr = new StringBuilder(); + instructionsStr.append("This tests the functionality of JDialog-inherited icons set using the setIconImages() API.\n"); + instructionsStr.append("You will see two JFrames with custom icons, each with a child JDialog below it.\n"); + instructionsStr.append("Both JDialogs should have the same icon: a colored box.\n"); + instructionsStr.append("If either of the JDialogs has the default, coffe-cup icon, the test fails.\n"); + instructionsStr.append("If the JDialogs DO NOT both have the same colored box as their icon, the test fails.\n"); + instructionsStr.append("If both JDialogs DO have the same colored box as their icon, then the test passes.\n"); + instructionsStr.append("Note: If the JDialog icons don't match the icons of the parent JFrame, that is OK."); + return instructionsStr.toString(); + } + + public void onEDT15() { + createDialogs(); + dialog1.setVisible(true); + dialog2.setVisible(true); + } + + protected void createDialogs() { + dialog1 = new JDialog(frame1, "Child JDialog 1", false); + dialog1.setBounds(frame1.getLocation().x, frame1.getLocation().y + frame1.getSize().height + 5, 200, 200); + dialog2 = new JDialog(frame2, "Child JDialog 2", false); + dialog2.setBounds(frame2.getLocation().x, frame2.getLocation().y + frame2.getSize().height + 5, 200, 200); + } + + public static void main(String[] args) throws Throwable { + new DialogInheritIcon().run(args); + System.out.println("end of main()"); + } +} diff --git a/test/jdk/javax/swing/JInternalFrame/bug4130806.java b/test/jdk/javax/swing/JInternalFrame/bug4130806.java new file mode 100644 index 000000000000..10814740b2e4 --- /dev/null +++ b/test/jdk/javax/swing/JInternalFrame/bug4130806.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1999, 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 4130806 + * @summary JInternalFrame's setIcon(true) works correctly + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4130806 + */ + +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import java.beans.PropertyVetoException; + +public class bug4130806 { + + private static final String INSTRUCTIONS = """ + If an icon is visible for the iconified internalframe, the test passes. + Otherwise, the test fails."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4130806 Instructions") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(bug4130806::createTestUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createTestUI() { + JFrame frame = new JFrame("bug4130806"); + JDesktopPane mDesktop = new JDesktopPane(); + frame.add(mDesktop); + frame.pack(); + JInternalFrame jif = new JInternalFrame("My Frame"); + jif.setIconifiable(true); + mDesktop.add(jif); + jif.setBounds(50,50,100,100); + try { + jif.setIcon(true); + } catch (PropertyVetoException e) { + throw new RuntimeException("PropertyVetoException received"); + } + jif.setVisible(true); + frame.setSize(200, 200); + return frame; + } +} diff --git a/test/jdk/javax/swing/JInternalFrame/bug4134077.java b/test/jdk/javax/swing/JInternalFrame/bug4134077.java new file mode 100644 index 000000000000..db609d5a425d --- /dev/null +++ b/test/jdk/javax/swing/JInternalFrame/bug4134077.java @@ -0,0 +1,132 @@ +/* + * 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. + */ + +/* + * @test + * @bug 4134077 + * @requires (os.family == "windows") + * @summary Metal,Window:If JInternalFrame's title text is long last must be ellipsis + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4134077 + */ + +import java.awt.BorderLayout; +import java.awt.ComponentOrientation; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import javax.swing.JButton; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; + +public class bug4134077 { + + private static JFrame frame; + + private static final String INSTRUCTIONS = """ + Try to resize internal frame with diferrent combinations of + LookAndFeels and title pane's buttons and orientation. + + The internal frame's title should clip if its too long to + be entierly visible (ends by "...") + and window can never be + smaller than the width of the first two letters of the title + plus "..."."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4134077 Instructions") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(bug4134077::createTestUI) + .build() + .awaitAndCheck(); + } + + private static void setLF(ActionEvent e) { + try { + UIManager.setLookAndFeel(((JButton)e.getSource()).getActionCommand()); + SwingUtilities.updateComponentTreeUI(frame); + } catch (ClassNotFoundException | InstantiationException + | UnsupportedLookAndFeelException + | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private static JFrame createTestUI() { + frame = new JFrame("bug4134077"); + JDesktopPane jdp = new JDesktopPane(); + frame.add(jdp); + + final JInternalFrame jif = + new JInternalFrame("Very Long Title For Internal Frame", true); + jdp.add(jif); + jif.setSize(150,150); + jif.setLocation(150, 50); + jif.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); + jif.setVisible(true); + + JPanel p = new JPanel(); + + JButton metal = new JButton("Metal"); + metal.setActionCommand("javax.swing.plaf.metal.MetalLookAndFeel"); + metal.addActionListener((ActionEvent e) -> setLF(e)); + p.add(metal); + + JButton windows = new JButton("Windows"); + windows.setActionCommand("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + windows.addActionListener((ActionEvent e) -> setLF(e)); + p.add(windows); + + JButton orientation = new JButton("Change orientation"); + orientation.addActionListener(e -> { + jif.setComponentOrientation( + jif.getComponentOrientation() == ComponentOrientation.LEFT_TO_RIGHT + ? ComponentOrientation.RIGHT_TO_LEFT + : ComponentOrientation.LEFT_TO_RIGHT); + }); + p.add(orientation); + + JButton clo = new JButton("Closable"); + clo.addActionListener(e -> jif.setClosable(!jif.isClosable())); + p.add(clo); + + JButton ico = new JButton("Iconifiable"); + ico.addActionListener(e -> jif.setIconifiable(!jif.isIconifiable())); + p.add(ico); + + JButton max = new JButton("Maximizable"); + max.addActionListener(e -> jif.setMaximizable(!jif.isMaximizable())); + p.add(max); + + frame.add(p, BorderLayout.SOUTH); + frame.setSize(700, 300); + return frame; + } +} diff --git a/test/jdk/javax/swing/JInternalFrame/bug4193070.java b/test/jdk/javax/swing/JInternalFrame/bug4193070.java new file mode 100644 index 000000000000..320b2e6e5633 --- /dev/null +++ b/test/jdk/javax/swing/JInternalFrame/bug4193070.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +/* + * @test + * @bug 4193070 + * @summary Tests correct mouse pointer shape + * @requires (os.family != "mac") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4193070 + */ + +import java.awt.Dimension; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; + +public class bug4193070 { + + private static final String INSTRUCTIONS = """ + Two internal frame will be shown. Select any internal frame; + Move mouse pointer inside the selected internal frame, + then to border of internal frame. + Mouse pointer should take the shape of resize cursor. + Now slowly move the mouse back inside the internal frame. + If mouse pointer shape does not change back to + normal shape of mouse pointer, then test failed. + Now try fast resizing an internal frame. + Check that mouse pointer always has resize shape, + even when it goes over other internal frame. + If during resizing mouse pointer shape changes, + then test failed. Otherwise test succeded."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4193070 Instructions") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(bug4193070::createTestUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createTestUI() { + JFrame f = new JFrame("bug4193070"); + JDesktopPane dp = new JDesktopPane(); + + JInternalFrame intFrm1 = new JInternalFrame(); + intFrm1.setResizable(true); + dp.add(intFrm1); + + JInternalFrame intFrm2 = new JInternalFrame(); + intFrm2.setResizable(true); + dp.add(intFrm2); + + f.setContentPane(dp); + f.setSize(new Dimension(500, 275)); + + intFrm1.setBounds(25, 25, 200, 200); + intFrm1.show(); + + intFrm2.setBounds(275, 25, 200, 200); + intFrm2.show(); + return f; + } +} diff --git a/test/jdk/javax/swing/JInternalFrame/bug4225701.java b/test/jdk/javax/swing/JInternalFrame/bug4225701.java new file mode 100644 index 000000000000..808ebb503baf --- /dev/null +++ b/test/jdk/javax/swing/JInternalFrame/bug4225701.java @@ -0,0 +1,87 @@ +/* + * 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. + */ + +/* + * @test + * @bug 4225701 + * @summary Verifies MetalInternalFrameUI.installKeyboardActions + * doesn't install listener + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4225701 + */ + +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; + +public class bug4225701 { + + private static final String INSTRUCTIONS = """ + Give a focus to the internal frame "Frame 4" and press Ctrl-F4. + The "Frame 4" should be closed. Give a focus to the internal + frame "Frame 1" and press Ctrl-F4. + If "Frame 4" and "Frame 1" is not closed, then press Fail else press Pass."""; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4225701 Instructions") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(bug4225701::createTestUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createTestUI() { + + JFrame frame = new JFrame("bug4225701"); + JInternalFrame jif1 = new JInternalFrame("Frame 1", true, true, true, true); + JInternalFrame jif2 = new JInternalFrame("Frame 2", false); + JInternalFrame jif3 = new JInternalFrame("Frame 3", false); + JInternalFrame jif4 = new JInternalFrame("Frame 4", true, true, true, true); + JDesktopPane jdp = new JDesktopPane(); + + frame.setContentPane(jdp); + + jdp.add(jif1); + jif1.setBounds(0, 150, 150, 150); + jif1.setVisible(true); + + jdp.add(jif2); + jif2.setBounds(100, 100, 150, 150); + jif2.setVisible(true); + + jdp.add(jif3); + jif3.setBounds(200, 50, 150, 150); + jif3.setVisible(true); + + jdp.add(jif4); + jif4.setBounds(300, 0, 150, 150); + jif4.setVisible(true); + + frame.setSize(500, 500); + return frame; + } + +} diff --git a/test/jdk/javax/swing/JList/bug4183379.java b/test/jdk/javax/swing/JList/bug4183379.java new file mode 100644 index 000000000000..784b92a6f16f --- /dev/null +++ b/test/jdk/javax/swing/JList/bug4183379.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2001, 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 4183379 + * @summary JList has wrong scrolling behavior when you click in the "troth" + * of a scrollbar, in a scrollpane. + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4183379 + */ + +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JScrollPane; + +public class bug4183379 { + public static void main(String[] args) throws Exception { + String INSTRUCTIONS = """ + Click mouse several times in the "troth" of a scrollbars + in a scrollpane containing a list. + The list should scrolls by one block, i.e.: + + For vertical scrolling: + - if scrolling down the last visible element should become the + first completely visible element + - if scrolling up, the first visible element should become the + last completely visible element + + For horizontal scrolling: + - for scrolling left if the beginning of the first column is not + visible it should become visible, otherwise the beginning of the + previous column should become visible; + - for scrolling right the next colunm after first visible column + should become visible. + """; + PassFailJFrame.builder() + .title("bug4183379 Instructions") + .instructions(INSTRUCTIONS) + .columns(35) + .testUI(bug4183379::initialize) + .build() + .awaitAndCheck(); + } + + private static JFrame initialize() { + JFrame fr = new JFrame("bug4183379"); + + String[] data = new String[90]; + for (int i=0; i<90; i++) { + data[i] = "item number "+i; + } + + JList lst = new JList(data); + lst.setLayoutOrientation(JList.VERTICAL_WRAP); + lst.setVisibleRowCount(20); + + JScrollPane jsp = new JScrollPane(lst); + fr.add(jsp); + fr.setSize(210,200); + fr.setAlwaysOnTop(true); + return fr; + } +} diff --git a/test/jdk/javax/swing/JList/bug4251306.java b/test/jdk/javax/swing/JList/bug4251306.java new file mode 100644 index 000000000000..ec5309460885 --- /dev/null +++ b/test/jdk/javax/swing/JList/bug4251306.java @@ -0,0 +1,115 @@ +/* + * Copyright (c) 1999, 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 4251306 + * @summary Test that Shift-Space keybinding works properly in JList. + * @key headful + * @run main bug4251306 + */ + +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; + +public class bug4251306 { + private static JFrame f; + private static JList lst; + private static CountDownLatch listGainedFocusLatch; + private static volatile boolean failed; + public static void main(String[] args) throws Exception { + try { + listGainedFocusLatch = new CountDownLatch(1); + createUI(); + runTest(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } + + private static void createUI() throws Exception { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4251306"); + lst = new JList<>(new String[]{"anaheim", "bill", + "chicago", "dingo"}); + lst.addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + listGainedFocusLatch.countDown(); + } + }); + JScrollPane sp = new JScrollPane(lst); + f.add(sp); + f.pack(); + f.setLocationRelativeTo(null); + f.setAlwaysOnTop(true); + f.setVisible(true); + }); + } + + private static void runTest() throws Exception { + if (!listGainedFocusLatch.await(3, TimeUnit.SECONDS)) { + throw new RuntimeException("Waited too long, but can't gain focus for list"); + } + Robot robot = new Robot(); + robot.setAutoDelay(500); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_A); + robot.keyRelease(KeyEvent.VK_A); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_SHIFT); + robot.keyPress(KeyEvent.VK_SPACE); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_SPACE); + robot.keyRelease(KeyEvent.VK_SHIFT); + + SwingUtilities.invokeAndWait(() -> { + if (!lst.isSelectedIndex(0) || + !lst.isSelectedIndex(1) || + !lst.isSelectedIndex(2) || + !lst.isSelectedIndex(3)) { + failed = true; + } + }); + if (failed) { + throw new RuntimeException("Required list items are not selected"); + } + } +} diff --git a/test/jdk/javax/swing/JMenu/bug4624845.java b/test/jdk/javax/swing/JMenu/bug4624845.java new file mode 100644 index 000000000000..54524b7a42e7 --- /dev/null +++ b/test/jdk/javax/swing/JMenu/bug4624845.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2002, 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 4624845 + * @requires (os.family == "windows") + * @summary Tests how submenus in WinLAF are painted + * @key headful + * @run main bug4624845 + */ + +import java.awt.Color; +import java.awt.Point; +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 javax.swing.UIManager; + +public class bug4624845 { + private static JFrame f; + private static JMenu menu, subMenu; + private static JMenuItem menuItem; + private static volatile Point menuLocation; + private static volatile Point subMenuLocation; + private static volatile Point menuItemLocation; + private static volatile int menuWidth; + private static volatile int menuHeight; + private static volatile int subMenuWidth; + private static volatile int subMenuHeight; + private static volatile int menuItemWidth; + private static volatile int menuItemHeight; + private static Color menuItemColor; + private static Color subMenuColor; + private static boolean passed; + private final static int OFFSET = 2; + private static final int COLOR_TOLERANCE = 10; + + public static void main(String[] args) throws Exception { + try { + UIManager.setLookAndFeel + ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception e) { + throw new RuntimeException("Failed to set Windows LAF"); + } + try { + bug4624845 test = new bug4624845(); + SwingUtilities.invokeAndWait(() -> test.createUI()); + runTest(); + verifyColor(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + if (!passed) { + throw new RuntimeException("Nested MenuItem color : " + + menuItemColor + " is not similar to sub Menu color : " + + subMenuColor); + } + } + private void createUI() { + f = new JFrame("bug4624845"); + menu = new JMenu("Menu"); + menu.add(new JMenuItem("Item 1")); + + subMenu = new JMenu("Submenu"); + menuItem = new JMenuItem("This"); + subMenu.add(menuItem); + subMenu.add(new JMenuItem("That")); + menu.add(subMenu); + + JMenuBar mBar = new JMenuBar(); + mBar.add(menu); + f.add(mBar); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + } + + private static void runTest() throws Exception { + Robot robot = new Robot(); + robot.setAutoDelay(200); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + menuLocation = menu.getLocationOnScreen(); + menuWidth = menu.getWidth(); + menuHeight = menu.getHeight(); + }); + robot.mouseMove(menuLocation.x + menuWidth / 2, + menuLocation.y + menuHeight / 2 ); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + subMenuLocation = subMenu.getLocationOnScreen(); + subMenuWidth = subMenu.getWidth(); + subMenuHeight = subMenu.getHeight(); + }); + robot.mouseMove(subMenuLocation.x + subMenuWidth / 2, + subMenuLocation.y + subMenuHeight / 2 ); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + subMenuColor = robot. + getPixelColor(subMenuLocation.x + OFFSET, + subMenuLocation.y + OFFSET); + SwingUtilities.invokeAndWait(() -> { + menuItemLocation = menuItem.getLocationOnScreen(); + menuItemWidth = subMenu.getWidth(); + menuItemHeight = subMenu.getHeight(); + }); + robot.mouseMove(menuItemLocation.x + menuItemWidth / 2, + menuItemLocation.y + menuItemHeight / 2 ); + robot.waitForIdle(); + menuItemColor = robot. + getPixelColor(menuItemLocation.x + OFFSET, + menuItemLocation.y + OFFSET); + } + + private static void verifyColor() { + + int red1 = subMenuColor.getRed(); + int blue1 = subMenuColor.getBlue(); + int green1 = subMenuColor.getGreen(); + + int red2 = menuItemColor.getRed(); + int blue2 = menuItemColor.getBlue(); + int green2 = menuItemColor.getGreen(); + + passed = true; + if ((Math.abs(red1 - red2) > COLOR_TOLERANCE) + || (Math.abs(green1 - green2) > COLOR_TOLERANCE) + || (Math.abs(blue1 - blue2) > COLOR_TOLERANCE)) { + passed = false; + } + } +} diff --git a/test/jdk/javax/swing/JMenuBar/TestMenuMnemonic.java b/test/jdk/javax/swing/JMenuBar/TestMenuMnemonic.java new file mode 100644 index 000000000000..500d3ca3408a --- /dev/null +++ b/test/jdk/javax/swing/JMenuBar/TestMenuMnemonic.java @@ -0,0 +1,132 @@ +/* + * 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 8326458 + * @key headful + * @requires (os.family == "windows") + * @modules java.desktop/com.sun.java.swing.plaf.windows + * @summary Verifies if menu mnemonics toggle on F10 press in Windows LAF + * @run main TestMenuMnemonic + */ + +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.util.concurrent.atomic.AtomicInteger; +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 TestMenuMnemonic { + + private static JFrame frame; + private static JMenuBar menuBar; + private static JMenu fileMenu; + + private static final AtomicInteger mnemonicHideCount = new AtomicInteger(0); + private static final AtomicInteger mnemonicShowCount = new AtomicInteger(0); + + private static final int EXPECTED = 5; + + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + Robot robot = new Robot(); + robot.setAutoDelay(100); + + try { + SwingUtilities.invokeAndWait(TestMenuMnemonic::createAndShowUI); + robot.waitForIdle(); + robot.delay(1000); + + for (int i = 0; i < EXPECTED * 2; i++) { + robot.keyPress(KeyEvent.VK_F10); + robot.waitForIdle(); + robot.delay(50); + robot.keyRelease(KeyEvent.VK_F10); + robot.waitForIdle(); + robot.delay(50); + SwingUtilities.invokeAndWait(TestMenuMnemonic::verifyMnemonicsState); + } + + if (mnemonicShowCount.get() != EXPECTED + && mnemonicHideCount.get() != EXPECTED) { + throw new RuntimeException("Mismatch in Mnemonic show/hide on F10 press"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + + private static void verifyMnemonicsState() { + MenuSelectionManager msm = + MenuSelectionManager.defaultManager(); + MenuElement[] selectedPath = msm.getSelectedPath(); + if (WindowsLookAndFeel.isMnemonicHidden()) { + mnemonicHideCount.getAndIncrement(); + // Check if selection is cleared when mnemonics are hidden + if (selectedPath.length != 0) { + throw new RuntimeException("Menubar is active after" + + " mnemonics are hidden"); + } + } else { + mnemonicShowCount.getAndIncrement(); + if (selectedPath.length != 2 + && (selectedPath[0] != menuBar || selectedPath[1] != fileMenu)) { + throw new RuntimeException("No Menu and Menubar is active when" + + " mnemonics are shown"); + } + } + } + + private static void createAndShowUI() { + frame = new JFrame("Test Menu Mnemonic Show/Hide"); + menuBar = new JMenuBar(); + fileMenu = new JMenu("File"); + JMenu editMenu = new JMenu("Edit"); + fileMenu.setMnemonic(KeyEvent.VK_F); + editMenu.setMnemonic(KeyEvent.VK_E); + JMenuItem item1 = new JMenuItem("Item 1"); + JMenuItem item2 = new JMenuItem("Item 2"); + fileMenu.add(item1); + fileMenu.add(item2); + menuBar.add(fileMenu); + menuBar.add(editMenu); + frame.setJMenuBar(menuBar); + frame.setSize(250, 200); + frame.setLocationRelativeTo(null); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} diff --git a/test/jdk/javax/swing/JMenuItem/LargeMenuTextArrowIconPosition.java b/test/jdk/javax/swing/JMenuItem/LargeMenuTextArrowIconPosition.java new file mode 100644 index 000000000000..72512560cffa --- /dev/null +++ b/test/jdk/javax/swing/JMenuItem/LargeMenuTextArrowIconPosition.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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 8374506 + * @summary Verify if arrow icon positioning is correct in + * parent JMenu in Windows L&F + * @requires (os.family == "windows") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual LargeMenuTextArrowIconPosition + */ + +import java.awt.BorderLayout; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.UIManager; + +public class LargeMenuTextArrowIconPosition { + + private static final String INSTRUCTIONS = """ + A frame will be shown with a label. + Right click on the label. + + Check the arrow icon at the end of + "Really long Menu-Text" text. + If it overlaps with the menu text, + press Fail else press Pass."""; + + public static void main(String[] args) throws Throwable { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + + PassFailJFrame.builder() + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(LargeMenuTextArrowIconPosition::createTestUI) + .build() + .awaitAndCheck(); + } + + private static JFrame createTestUI() { + + JFrame frame = new JFrame("LargeMenuTextArrowIcon"); + frame.setSize(300, 150); + frame.setLayout(new BorderLayout()); + + JPopupMenu popupMenu = new JPopupMenu(); + popupMenu.add(new JCheckBoxMenuItem("CheckBox On", true)); + popupMenu.add(new JCheckBoxMenuItem("CheckBox Icon On", + UIManager.getIcon("FileView.floppyDriveIcon"), true)); + popupMenu.add(new JCheckBoxMenuItem("CheckBox Icon Off", + UIManager.getIcon("FileView.floppyDriveIcon"), false)); + + JMenu menu = new JMenu("Really long Menu-Text"); + menu.add(new JMenuItem("Sub-MenuItem")); + menu.add(new JCheckBoxMenuItem("Sub-CheckBox On", true)); + + popupMenu.add(menu); + + JLabel lbl = new JLabel("Right click to invoke popupMenu"); + lbl.setComponentPopupMenu(popupMenu); + frame.add(lbl, BorderLayout.CENTER); + + return frame; + } + +} diff --git a/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java b/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java index afb1c7bb33f9..5a30e202d9da 100644 --- a/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java +++ b/test/jdk/javax/swing/JMenuItem/MenuItemTest/bug6197830.java @@ -49,6 +49,7 @@ public static void main(String[] args) throws Exception { .columns(35) .testUI(bug6197830::createTestUI) .positionTestUIBottomRowCentered() + .logArea() .build() .awaitAndCheck(); } diff --git a/test/jdk/javax/swing/JRootPane/bug4403624.java b/test/jdk/javax/swing/JRootPane/bug4403624.java new file mode 100644 index 000000000000..1c3ba3ddd2a8 --- /dev/null +++ b/test/jdk/javax/swing/JRootPane/bug4403624.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2001, 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 4403624 + * @summary Tests JRootPane layout with invisible menubar + * @key headful + * @run main bug4403624 + */ + +import java.awt.Color; +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.SwingUtilities; + +public class bug4403624 { + private static JFrame f; + private static Container c; + private static JButton b; + private static volatile Point p; + private static volatile int bWidth; + private static volatile int bHeight; + private static final int OFFSET = 2; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4403624 Test"); + JMenuBar mbar; + mbar = new JMenuBar(); + mbar.add(new JMenu("Menu")); + f.setJMenuBar(mbar); + b = new JButton("Hide Menu"); + b.addActionListener(e -> mbar.setVisible(false)); + c = f.getContentPane(); + c.setLayout(new FlowLayout()); + c.setBackground(Color.GREEN); + c.add(b); + f.pack(); + f.setLocationRelativeTo(null); + f.setAlwaysOnTop(true); + f.setVisible(true); + }); + + Robot r = new Robot(); + r.setAutoDelay(200); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + p = b.getLocationOnScreen(); + bWidth = b.getWidth(); + bHeight = b.getHeight(); + }); + + r.mouseMove(p.x + (bWidth / 2), p.y + (bHeight / 2)); + r.mousePress(InputEvent.BUTTON1_DOWN_MASK); + r.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + + SwingUtilities.invokeAndWait(() -> p = c.getLocationOnScreen()); + + Color c = r.getPixelColor(p.x + OFFSET, p.y + OFFSET); + + if (c.getGreen() < 240 && c.getBlue() > 10 && c.getRed() > 10) { + System.out.println("EXPECTED: " + Color.GREEN); + System.out.println("ACTUAL: " + c); + throw new RuntimeException("Failure to hide menu bar."); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java b/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java index 96b1034c943d..d68f1bff5971 100644 --- a/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java +++ b/test/jdk/javax/swing/JScrollBar/4865918/bug4865918.java @@ -24,14 +24,16 @@ /* * @test * @bug 4865918 - * @requires (os.family != "mac") + * @key headful * @summary REGRESSION:JCK1.4a-runtime api/javax_swing/interactive/JScrollBarTests.html#JScrollBar * @run main bug4865918 */ import java.awt.Dimension; +import java.awt.Robot; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; +import javax.swing.JFrame; import javax.swing.JScrollBar; import javax.swing.SwingUtilities; import java.util.concurrent.CountDownLatch; @@ -41,24 +43,33 @@ public class bug4865918 { + private static JFrame frame; private static TestScrollBar sbar; private static final CountDownLatch mousePressLatch = new CountDownLatch(1); public static void main(String[] argv) throws Exception { - 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()); + try { + Robot robot = new Robot(); + SwingUtilities.invokeAndWait(() -> createAndShowGUI()); - SwingUtilities.invokeAndWait(() -> sbar.pressMouse()); - if (!mousePressLatch.await(2, TimeUnit.SECONDS)) { - throw new RuntimeException("Timed out waiting for mouse press"); - } + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> sbar.pressMouse()); + if (!mousePressLatch.await(2, TimeUnit.SECONDS)) { + throw new RuntimeException("Timed out waiting for mouse press"); + } - if (getValue() != 9) { - throw new RuntimeException("The scrollbar block increment is incorrect"); + if (getValue() != 9) { + throw new RuntimeException("The scrollbar block increment " + + getValue() + " is incorrect"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } @@ -73,8 +84,8 @@ private static int getValue() throws Exception { return result[0]; } - private static void setupTest() { - + private static void createAndShowGUI() { + frame = new JFrame("bug4865918"); sbar = new TestScrollBar(JScrollBar.HORIZONTAL, -1, 10, -100, 100); sbar.setPreferredSize(new Dimension(200, 20)); sbar.setBlockIncrement(10); @@ -83,7 +94,11 @@ public void mousePressed(MouseEvent e) { mousePressLatch.countDown(); } }); - + frame.getContentPane().add(sbar); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + frame.toFront(); } static class TestScrollBar extends JScrollBar { diff --git a/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/HorizScrollers.java b/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/HorizScrollers.java new file mode 100644 index 000000000000..61124ea1e973 --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/HorizScrollers.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2004, 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 5078454 + * @summary Test horizontal wheel scroll behavior of (including RTL) + * @requires (os.family == "windows") + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual HorizScrollers + */ + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; + +import javax.swing.BorderFactory; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; + +public class HorizScrollers { + private static final String INSTRUCTIONS = """ + This is a semi-automatic test with three phases. + For each phase, you will need to change the mouse setting, as + directed by a dialog. Once the correct setting is confirmed, + the next test phase will run automatically. + DO NOT TOUCH ANYTHING DURING TESTING! + + The test will automatically FAIL during testing if something + fails. Otherwise, the test will automatically PASS after the + third testing phase. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("HorizScrollers Instructions") + .instructions(INSTRUCTIONS) + .columns(45) + .testTimeOut(10) + .splitUIRight(ConfigPanel::new) + .logArea(6) + .build() + .awaitAndCheck(); + } + + private static final int[] SCROLLAMTS = {1, 30, 3}; + private static final String[] CONFIG_MSGS = { + "Set the scrolling speed to the slowest value (1 line).", + "Set the scrolling speed to the fastest value (30 lines).", + "Set the scrolling speed to two ticks above the slowest value (3 lines)." + }; + + private static int current = 0; + private static final String MW_TEXT = "Rotate the mouse wheel here"; + private static final String CONFIG_INSTRUCTION_TEMPLATE = """ + Configure Mouse Wheel for Phase %d + + Open the Mouse Control Panel and go to the 'Wheel' tab. + If 'Wheel' tab is not available just press Pass. + + %s + + Test the setting on the area below. + Once the mouse is setup correctly, the area will turn green. + When you're ready for the next part of the test to run, press GO! + """; + + static class ConfigPanel extends JPanel + implements ActionListener, MouseWheelListener { + JTextArea msg; + JButton goBtn; + JLabel mwArea; + int scrollAmount; + + private final Color defaultBg; + + ConfigPanel() { + this.scrollAmount = SCROLLAMTS[current]; + Container content = this; + content.setLayout(new BorderLayout()); + msg = new JTextArea(); + msg.setMargin(new Insets(5, 5, 5, 5)); + msg.setEditable(false); + msg.setLineWrap(true); + msg.setWrapStyleWord(true); + content.add(msg, BorderLayout.NORTH); + + mwArea = new JLabel(MW_TEXT, SwingConstants.CENTER); + mwArea.setPreferredSize(new Dimension(200, 250)); + mwArea.setBorder(BorderFactory.createLineBorder(Color.BLACK)); + mwArea.setOpaque(true); + mwArea.addMouseWheelListener(this); + content.add(mwArea, BorderLayout.CENTER); + + defaultBg = mwArea.getBackground(); + setPhase(current); + + goBtn = new JButton("GO!"); + goBtn.setEnabled(false); + goBtn.addActionListener(this); + JPanel flowPanel = new JPanel(); + flowPanel.setLayout(new FlowLayout()); + flowPanel.add(goBtn); + content.add(flowPanel, BorderLayout.SOUTH); + + setPreferredSize(new Dimension(600, 400)); + } + + public void setPhase(int phase) { + if (phase < 3) { + setVisible(true); + PassFailJFrame.log("Phase %d scroll speed %d" + .formatted(phase + 1, SCROLLAMTS[phase])); + PassFailJFrame.log(CONFIG_MSGS[phase]); + + scrollAmount = SCROLLAMTS[phase]; + msg.setText(CONFIG_INSTRUCTION_TEMPLATE + .formatted(phase + 1, CONFIG_MSGS[phase])); + mwArea.setBackground(defaultBg); + mwArea.setText(MW_TEXT); + } else { + // all cases passed + showFinalReminderIfNeeded(false); + } + } + + private void showFinalReminderIfNeeded(boolean isFailure) { + if (scrollAmount != 3) { + JOptionPane.showMessageDialog( + ConfigPanel.this.getTopLevelAncestor(), + ("Test %s. Please make sure you have restored " + + "the original scrolling speed in the " + + "Mouse settings.") + .formatted(isFailure + ? "failed" + : "passed"), + isFailure + ? "Failure" + : "Success", + isFailure + ? JOptionPane.WARNING_MESSAGE + : JOptionPane.INFORMATION_MESSAGE + ); + } + + if (isFailure) { + PassFailJFrame.forceFail(); + } else { + PassFailJFrame.forcePass(); + } + } + + public void actionPerformed(ActionEvent e) { + if (e.getSource() == goBtn) { + goBtn.setEnabled(false); + + new Thread(() -> { // new thread to avoid running robot on EDT + boolean passed; + try { + passed = RTLScrollers.runTest(SCROLLAMTS[current]); + } catch (Exception ex) { + PassFailJFrame.log("Failure: " + ex); + SwingUtilities.invokeLater(() -> + showFinalReminderIfNeeded(true)); + return; + } + + PassFailJFrame.log("Phase %d passed: %b\n" + .formatted(current + 1, passed)); + if (passed) { + SwingUtilities.invokeLater(() -> { + goBtn.setEnabled(true); + setPhase(++current); + }); + } else { + SwingUtilities.invokeLater(() -> + showFinalReminderIfNeeded(true)); + } + }).start(); + } + } + + public void mouseWheelMoved(MouseWheelEvent e) { + int eventScrollAmt = e.getScrollAmount(); + if (eventScrollAmt == scrollAmount) { + mwArea.setBackground(Color.GREEN); + mwArea.setText("Mouse wheel configured - press Go"); + goBtn.setEnabled(true); + goBtn.requestFocusInWindow(); + PassFailJFrame.log("Proceed to the test with go button"); + return; + } + if (eventScrollAmt < scrollAmount) { + mwArea.setText("Increase the scroll speed. (Want:" + + scrollAmount + " Got:" + eventScrollAmt + ")"); + } else { + mwArea.setText("Decrease the scroll speed. (Want:" + + scrollAmount + " Got:" + eventScrollAmt + ")"); + } + } + } +} diff --git a/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/RTLScrollers.java b/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/RTLScrollers.java new file mode 100644 index 000000000000..da395282bf5b --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/AcceleratedWheelScrolling/RTLScrollers.java @@ -0,0 +1,680 @@ +/* + * Copyright (c) 2004, 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. + */ + +// A few Swing components which use the mouse wheel to scroll + +import java.awt.AWTException; +import java.awt.Color; +import java.awt.ComponentOrientation; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.awt.image.BufferedImage; +import java.lang.reflect.InvocationTargetException; + +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.ListModel; +import javax.swing.ScrollPaneConstants; +import javax.swing.SwingUtilities; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableColumn; +import javax.swing.table.TableModel; + +public class RTLScrollers extends JDialog + implements MouseWheelListener, ActionListener { + private static final int ROWS = 5; + private static final int COLUMNS = 150; + private static final int WINWIDTH = 1000; + + static RTLScrollers rtl; + static volatile RTLScrollers f; + static volatile boolean retVal; + static volatile JScrollPane jsp; + static volatile JScrollBar hsb; + static volatile JScrollBar sb; + static volatile Point loc; + static volatile Dimension size; + TestList list; + JScrollPane listScroller; + JTextArea text; + JScrollPane textScroller; + TestTable table; + JScrollPane tableScroller; + JCheckBoxMenuItem rightToLeft; + ImageIcon photoIcon; + int scrollAmount; + + private static Robot robot; + private static BufferedImage logo = genIcon(166, 39, Color.PINK); + private static BufferedImage photo = genIcon(59, 80, Color.MAGENTA); + private static BufferedImage photo2 = genIcon(80, 53, Color.ORANGE); + + private static BufferedImage genIcon(int width, int height, Color color) { + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics g = image.getGraphics(); + g.setColor(color); + g.fillRect(0, 0, width, height); + + return image; + } + + public RTLScrollers() { + this(0); + } + + public RTLScrollers(int scrollAmount) { + super(new JFrame(), "RTLScrollers", false); + + this.scrollAmount = scrollAmount; + Container content = getContentPane(); + content.setLayout(new GridBagLayout()); + + DefaultListModel listModel = new DefaultListModel<>(); + + photoIcon = new ImageIcon(photo); + for (int i = 0; i < COLUMNS / 4 ; i++) { + for (int j = 0; j < ROWS; j++) { + listModel.addElement(new ImageIcon(logo)); + } + for (int j = 0; j < ROWS; j++) { + listModel.addElement(photoIcon); + } + for (int j = 0; j < ROWS; j++) { + listModel.addElement(new ImageIcon(photo2)); + } + for (int j = 0; j < ROWS; j++) { + listModel.addElement("Text Item " + ((1 + i) * 3)); + } + } + + list = new TestList(listModel); + list.setVisibleRowCount(ROWS); + list.setLayoutOrientation(JList.VERTICAL_WRAP); + listScroller = new JScrollPane(list); + listScroller.addMouseWheelListener(this); + + text = new JTextArea(); + for (int j = 0; j < ROWS ; j++) { + for (int i = 0; i < COLUMNS ; i++) { + text.append(i + " some text, some more text, a really long line of text "); + } + text.append("\n"); + } + + textScroller = new JScrollPane(text); + textScroller.addMouseWheelListener(this); + + DefaultTableModel model = new DefaultTableModel(ROWS, COLUMNS); + table = new TestTable(model); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + for (int i = 0; i < COLUMNS; i++) { + for (int j = 0; j < ROWS; j++) { + table.setValueAt(j + ", " + i, j, i); + } + + TableColumn column = table.getColumnModel().getColumn(i); + + if (i % 4 == 0) { + column.setMinWidth(0); + column.setPreferredWidth(0); + column.setMaxWidth(0); + } + else if ((i + 1) % 4 == 0) { + column.setMinWidth(95); + column.setPreferredWidth(95); + column.setMaxWidth(95); + } + else if ((i + 2) % 4 == 0) { + column.setMinWidth(26); + column.setPreferredWidth(26); + column.setMaxWidth(26); + } + else { + column.setMinWidth(50); + column.setPreferredWidth(50); + column.setMaxWidth(50); + } + } + tableScroller = new JScrollPane(table); + tableScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + tableScroller.addMouseWheelListener(this); + + GridBagConstraints tableGBC = new GridBagConstraints(0, + 0, + 1, + 1, + 1.0, + 0.3, + GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0,0,0,0), + 0, + 0); + content.add(tableScroller, tableGBC); + GridBagConstraints textGBC = new GridBagConstraints(0, + 1, + 1, + 1, + 1.0, + 0.3, + GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0,0,0,0), + 0, + 0); + content.add(textScroller, textGBC); + + GridBagConstraints listGBC = new GridBagConstraints(0, + 2, + 1, + 5, + 1.0, + 1.2, + GridBagConstraints.CENTER, + GridBagConstraints.BOTH, + new Insets(0,0,0,0), + 0, + 0); + + content.add(listScroller, listGBC); + + rightToLeft = new JCheckBoxMenuItem("Right-To-Left", false); + rightToLeft.addActionListener(this); + JMenu menu = new JMenu("Component Orientation"); + menu.add(rightToLeft); + + JMenuItem close = new JMenuItem("Close"); + close.addActionListener(e -> RTLScrollers.this.setVisible(false)); + menu.add(close); + + JMenuBar mb = new JMenuBar(); + mb.add(menu); + setJMenuBar(mb); + setBounds(0, 0, WINWIDTH, 760); + setLocationRelativeTo(null); + } + + public void actionPerformed(ActionEvent e) { + if (rightToLeft.getState()) { + applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); + } + else { + applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); + } + } + public void mouseWheelMoved(MouseWheelEvent e) { + System.out.println("Rotation: " + e.getWheelRotation()); + } + + public static boolean runTest(int scrollAmount) + throws InterruptedException, InvocationTargetException { + System.out.println("RTLS.runTest()"); + if (robot == null) { + try { + robot = new Robot(); + robot.setAutoDelay(150); + robot.setAutoWaitForIdle(true); + } + catch (AWTException e) { + e.printStackTrace(); + return false; + } + } + + robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { + rtl = new RTLScrollers(scrollAmount); + rtl.setVisible(true); + }); + robot.delay(100); + + try { + retVal = rtl.runTests(scrollAmount); + } finally { + SwingUtilities.invokeAndWait(() -> { + rtl.setVisible(false); + rtl.dispose(); + }); + } + + robot.delay(100); + System.out.println("RTLS.runTest(): " + retVal); + return retVal; + } + + private boolean runTests(int scrollAmount) + throws InterruptedException, InvocationTargetException { + if (robot == null) { + try { + robot = new Robot(); + robot.setAutoDelay(150); + robot.setAutoWaitForIdle(true); + } + catch (AWTException e) { + e.printStackTrace(); + return false; + } + } + + // + // run robot tests + // + robot.delay(500); + + System.out.println("Testing Table"); + testComp(table, scrollAmount); + + System.out.println("Testing List"); + testComp(list, scrollAmount); + + SwingUtilities.invokeAndWait(() -> + applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT)); + robot.delay(100); + + System.out.println("Testing RTL Table"); + testComp(table, scrollAmount); + + System.out.println("Testing RTL List"); + testComp(list, scrollAmount); + + return true; + } + + public boolean testComp(TestTools comp, int scrollAmount) + throws InterruptedException, InvocationTargetException { + // Make sure we start from the beginning + SwingUtilities.invokeAndWait(() -> { + jsp = (JScrollPane)((JComponent)comp).getParent().getParent(); + hsb = jsp.getHorizontalScrollBar(); + hsb.setValue(hsb.getMinimum()); + + loc = jsp.getLocationOnScreen(); + size = jsp.getSize(); + }); + int midx = loc.x + size.width / 2; + int midy = loc.y + size.height / 2; + int maxIdx = 0; + robot.mouseMove(midx, midy); + + // Don't bother for max scroll w/ RTL JList, because the block increment is broken + if (scrollAmount != 30 || !(comp instanceof TestList) + || getComponentOrientation().isLeftToRight()) { + scrollToMiddle(jsp, robot); + + // check that we're lined up + comp.checkTopCellIsLinedUp(); + + int startVal = hsb.getValue(); + int leadingCell = comp.getLeadingCell().y; + System.out.println("leadingCell is " + leadingCell); + + // become unaligned + int width = comp.getLeadingCellWidth(); + int midVal = startVal + width / 2; + System.out.println("becoming unaligned: startVal is " + + startVal + ", midVal is " + midVal); + SwingUtilities.invokeAndWait(() -> hsb.setValue(midVal)); + + // + // Check partial inc up + // + robot.mouseWheel(-1); + + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, -scrollAmount + 1); + } + comp.checkTopCellIsLinedUp(); + + // + // Check partial inc down + // + SwingUtilities.invokeAndWait(() -> hsb.setValue(midVal)); + robot.delay(100); + robot.mouseWheel(1); + + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, scrollAmount); + } + comp.checkTopCellIsLinedUp(); + + // + // Check full inc down (3 times) + // + SwingUtilities.invokeAndWait(() -> hsb.setValue(startVal)); + leadingCell = comp.getLeadingCell().y; + + // Once... + robot.mouseWheel(1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, scrollAmount); + } + comp.checkTopCellIsLinedUp(); + + // Twice... + robot.mouseWheel(1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, (2 * scrollAmount)); + } + + comp.checkTopCellIsLinedUp(); + + // Thrice... + robot.mouseWheel(1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, (3 * scrollAmount)); + + } + comp.checkTopCellIsLinedUp(); + + // + // Check full inc up (3 times) + // + leadingCell = comp.getLeadingCell().y; + + // Once... + robot.mouseWheel(-1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, -scrollAmount); + } + comp.checkTopCellIsLinedUp(); + + // Twice... + robot.mouseWheel(-1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, -(2 * scrollAmount)); + } + comp.checkTopCellIsLinedUp(); + + // Thrice... + robot.mouseWheel(-1); + if (scrollAmount == 30) { // hack for max scroll amount + comp.checkTopCellIsMax(maxIdx++); + } + else { + comp.checkTopCellIs(leadingCell, -(3 * scrollAmount)); + } + comp.checkTopCellIsLinedUp(); + } + + // + // Test acceleration for max scrolling + // (this part should still work for RTL JList) + if (scrollAmount == 30) { + SwingUtilities.invokeAndWait(() -> hsb.setValue(hsb.getMinimum())); + robot.delay(100); + robot.mouseWheel(2); + robot.mouseWheel(2); + robot.mouseWheel(2); + if (hsb.getValue() < hsb.getMaximum() - hsb.getVisibleAmount()) { + throw new RuntimeException("Wheel acceleration for max " + + "scrolling doesn't work: hsb value (" + hsb.getValue() + + " < hsb max (" + hsb.getMaximum() + + ") - hsb vis (" + hsb.getVisibleAmount() + ")"); + } + robot.delay(100); + robot.mouseWheel(-2); + robot.mouseWheel(-2); + robot.mouseWheel(-2); + if (hsb.getValue() > hsb.getMinimum()) { + throw new RuntimeException("Wheel acceleration for max " + + "scrolling doesn't work: hsb value (" + + hsb.getValue() + " > hsb min (" + hsb.getMinimum() + ")"); + } + } + + return true; + } + + class TestTable extends JTable implements TestTools { + final int[] MAXVALS = {23, 67, 67, 89, 111, 89, 66, 45}; //Lookup table + public TestTable(TableModel model) { + super(model); + } + + public void checkTopCellIsLinedUp() { + boolean isLeftToRight = getComponentOrientation().isLeftToRight(); + Point leading = getLeadingCell(); + Rectangle visRect = getVisibleRect(); + Rectangle cellRect = getCellRect(leading.x, leading.y, true); + + if (isLeftToRight) { + if (cellRect.x != visRect.x) { + throw new RuntimeException("leading cell is not aligned!"); + } + } + else { + if (cellRect.x + cellRect.width != visRect.x + visRect.width) { + throw new RuntimeException("leading cell is not aligned!"); + } + } + } + + public void checkTopCellIs(int col) { + Point cell = getLeadingCell(); + if (cell.y != col) { + throw new RuntimeException("leading cell (" + cell.y + + ") is not " + col); + } + } + + /* + * Account for 0-width cells + * + * shift is a non-0 number of visible cells to shift. The shift is + * augmented for zero-width cells, and the new sum is passed into + * checkTopCellIs(). + */ + public void checkTopCellIs(int col, int shift) { + if (shift == 0) { + checkTopCellIs(col); + return; + } + + int row = getLeadingCell().x; + int newShift = 0; + int foundCells = 0; + int direction = shift > 0 ? 1 : -1; + int index = col; + Rectangle cellRect; + + while (foundCells < Math.abs(shift)) { + index += direction; + cellRect = getCellRect(row, index, true); + if (cellRect.width > 0) { + foundCells++; + } + newShift++; + } + + checkTopCellIs(col + (direction*newShift)); + } + + public void checkTopCellIsMax(int idx) { + checkTopCellIs(MAXVALS[idx]); + } + + public int getLeadingCellWidth() { + Point leading = getLeadingCell(); + Rectangle cellRect = getCellRect(leading.x, leading.y, true); + return cellRect.width; + } + + public Point getLeadingCell() { + boolean isLeftToRight = getComponentOrientation().isLeftToRight(); + Rectangle visRect = getVisibleRect(); + int row = rowAtPoint(visRect.getLocation()); + int column; + if (isLeftToRight) { + column = columnAtPoint(visRect.getLocation()); + } + else { + column = columnAtPoint(new Point(visRect.x + visRect.width - 1, visRect.y)); + } + return new Point(row, column); + } + } + + class TestList extends JList implements TestTools { + final int[] MAXVALS = {5, 16, 15, 20, 25, 20, 15, 10 }; + public TestList(ListModel model) { + super(model); + } + + // Note - implemented in terms of columns + public Point getLeadingCell() { + System.out.println("TL.gLC(): first vis index is " + + getFirstVisibleIndex()); + return new Point(getFirstVisibleIndex() / ROWS, + getFirstVisibleIndex() / ROWS); + } + public void checkTopCellIsLinedUp() { + boolean isLeftToRight = getComponentOrientation().isLeftToRight(); + int visIdx = getFirstVisibleIndex(); + Rectangle cellRect = getCellBounds(visIdx, visIdx); + Rectangle visRect = getVisibleRect(); + if (isLeftToRight) { + if (cellRect.x != visRect.x) { + throw new RuntimeException("leading cell is not aligned!"); + } + } + else { + if (cellRect.x + cellRect.width != visRect.x + visRect.width) { + throw new RuntimeException("leading cell is not aligned!"); + } + } + } + public void checkTopCellIs(int col) { + int firstVis = getLeadingCell().y; + if (firstVis != col) { + throw new RuntimeException("leading cell (" + + firstVis + ") is not " + col); + } + } + public void checkTopCellIs(int idx, int shift) { + checkTopCellIs(idx + shift); + + } + public void checkTopCellIsMax(int idx) { + checkTopCellIs(MAXVALS[idx]); + } + public int getLeadingCellWidth() { + int visIdx = getFirstVisibleIndex(); + Rectangle cellRect = getCellBounds(visIdx, visIdx); + System.out.println("TL.gLCW(): leading cell width is " + cellRect.width); + return cellRect.width; + } + } + + private interface TestTools { + /** + * Throws a runtime exception if the top cell isn't lined up + */ + void checkTopCellIsLinedUp(); + void checkTopCellIs(int col); + void checkTopCellIs(int col, int shift); + int getLeadingCellWidth(); + Point getLeadingCell(); + + void checkTopCellIsMax(int idx); + } + + public void scrollToMiddle(JScrollPane jsp, Robot robot) + throws InterruptedException, InvocationTargetException { + SwingUtilities.invokeAndWait(() -> { + sb = jsp.getHorizontalScrollBar(); + loc = sb.getLocationOnScreen(); + size = sb.getSize(); + }); + robot.setAutoDelay(250); + + robot.mouseMove(loc.x + size.width / 2, + loc.y + size.height / 2); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + + SwingUtilities.invokeAndWait(() -> { + if (jsp == listScroller) { + int idx = list.getFirstVisibleIndex(); + list.ensureIndexIsVisible(idx); + } + }); + } + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> f = new RTLScrollers()); + } finally { + SwingUtilities.invokeAndWait(() -> { + f.setVisible(true); + f.dispose(); + }); + } + } +} diff --git a/test/jdk/javax/swing/JScrollPane/bug4166037.java b/test/jdk/javax/swing/JScrollPane/bug4166037.java new file mode 100644 index 000000000000..e2ce75867a70 --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/bug4166037.java @@ -0,0 +1,167 @@ +/* + * 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. + */ + +/* + * @test + * @bug 4166037 + * @summary Tests if changes to JScrollPane propagate to ScrollPaneLayout + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4166037 + */ + +import java.awt.Color; + +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.ScrollPaneLayout; + +public class bug4166037 { + static final String INSTRUCTIONS = """ + Press button "Never". Scroll bars should disappear. + Press button "Always". Scroll bars should appear. + Press button "Colhead". Label ColumnHeader should + get replaced with yellow rectangles. + Press button "Corner". You should see 4 green + rectangles in the corners of the scroll pane. + Press button "Rowhead". Label RowHeader should get + replaced with yellow rectangles. + Press button "Viewport". Viewport (the rest of the + area except scrollbars) should get replaced with yellow + rectangles. + If the behavior is as described, the test PASSES. + Otherwise, this test FAILS. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4166037 Test Instructions") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(bug4166037::createUI) + .logArea() + .build() + .awaitAndCheck(); + } + + static JFrame createUI() { + JFrame f = new JFrame("JScrollPane in JScrollLayout Test"); + JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + JPanel p = new JPanel(); + scroll.setSize(200, 200); + f.add(scroll); + f.setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS)); + JButton bn = new JButton("Never"); + bn.addActionListener(e -> { + PassFailJFrame.log("pane before: " + + scroll.getVerticalScrollBarPolicy() + + scroll.getHorizontalScrollBarPolicy()); + PassFailJFrame.log("layout before: " + + ((ScrollPaneLayout) scroll.getLayout()).getVerticalScrollBarPolicy() + + ((ScrollPaneLayout) scroll.getLayout()).getHorizontalScrollBarPolicy()); + scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + PassFailJFrame.log("pane after: " + + scroll.getVerticalScrollBarPolicy() + + scroll.getHorizontalScrollBarPolicy()); + PassFailJFrame.log("layout after: " + + ((ScrollPaneLayout) scroll.getLayout()).getVerticalScrollBarPolicy() + + ((ScrollPaneLayout) scroll.getLayout()).getHorizontalScrollBarPolicy()); + }); + JButton ba = new JButton("Always"); + ba.addActionListener(e -> { + PassFailJFrame.log("pane before: " + + scroll.getVerticalScrollBarPolicy() + + scroll.getHorizontalScrollBarPolicy()); + PassFailJFrame.log("layout before: " + + ((ScrollPaneLayout) scroll.getLayout()).getVerticalScrollBarPolicy() + + ((ScrollPaneLayout) scroll.getLayout()).getHorizontalScrollBarPolicy()); + scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); + PassFailJFrame.log("pane after: " + + scroll.getVerticalScrollBarPolicy() + + scroll.getHorizontalScrollBarPolicy()); + PassFailJFrame.log("layout after: " + + ((ScrollPaneLayout) scroll.getLayout()).getVerticalScrollBarPolicy() + + ((ScrollPaneLayout) scroll.getLayout()).getHorizontalScrollBarPolicy()); + }); + JLabel ch = new JLabel("ColumnHeader"); + scroll.setColumnHeaderView(ch); + JButton b1 = new JButton("Colhead"); + b1.addActionListener(e -> { + JPanel filler = new JPanel(); + filler.setSize(150, 150); + filler.setBackground(Color.yellow); + scroll.getColumnHeader().add(filler); + }); + JButton b2 = new JButton("Corners"); + b2.addActionListener(e -> { + JPanel filler1 = new JPanel(); + filler1.setSize(150, 150); + filler1.setBackground(Color.green); + scroll.setCorner(JScrollPane.LOWER_RIGHT_CORNER, filler1); + JPanel filler2 = new JPanel(); + filler2.setSize(150, 150); + filler2.setBackground(Color.green); + scroll.setCorner(JScrollPane.LOWER_LEFT_CORNER, filler2); + JPanel filler3 = new JPanel(); + filler3.setSize(150, 150); + filler3.setBackground(Color.green); + scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER, filler3); + JPanel filler4 = new JPanel(); + filler4.setSize(150, 150); + filler4.setBackground(Color.green); + scroll.setCorner(JScrollPane.UPPER_LEFT_CORNER, filler4); + }); + JLabel rh = new JLabel("RowHeader"); + scroll.setRowHeaderView(rh); + JButton b3 = new JButton("Rowhead"); + b3.addActionListener(e -> { + JPanel filler = new JPanel(); + filler.setSize(150, 150); + filler.setBackground(Color.yellow); + scroll.getRowHeader().add(filler); + }); + JButton b4 = new JButton("Viewport"); + b4.addActionListener(e -> { + JPanel filler = new JPanel(); + filler.setSize(150, 150); + filler.setBackground(Color.yellow); + scroll.getViewport().add(filler); + }); + + p.add(bn); + p.add(ba); + p.add(b1); + p.add(b2); + p.add(b3); + p.add(b4); + f.add(p); + f.setSize(300, 300); + return f; + } +} diff --git a/test/jdk/javax/swing/JScrollPane/bug4237517.java b/test/jdk/javax/swing/JScrollPane/bug4237517.java new file mode 100644 index 000000000000..4e1d13561998 --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/bug4237517.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1999, 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 4237517 + * @summary Tests that scrolling with blit draws the right thing + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4237517 + */ + +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JScrollPane; + +public class bug4237517 { + static final String INSTRUCTIONS = """ + Select the first item in the list and hit PageDown + key two times. If the list is redrawn correctly, + i.e. if the digits go in order, then the test PASSES. + Otherwise, the test FAILS. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4237517 Test Instructions") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(bug4237517::createUI) + .build() + .awaitAndCheck(); + } + + static JFrame createUI() { + JFrame f = new JFrame("Scrolling Window Blit Test"); + String[] data = new String[100]; + + for (int counter = 0; counter < data.length; counter++) { + data[counter] = Integer.toString(counter); + } + JList list = new JList(data); + JScrollPane sp = new JScrollPane(list); + sp.getViewport().putClientProperty("EnableWindowBlit", Boolean.TRUE); + f.add(sp); + f.setSize(200, 200); + return f; + } +} diff --git a/test/jdk/javax/swing/JScrollPane/bug4237560.java b/test/jdk/javax/swing/JScrollPane/bug4237560.java new file mode 100644 index 000000000000..4f8f27683e54 --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/bug4237560.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1999, 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 4237560 + * @summary Tests that JScrollPane do not distort TAB order in an HTML page + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4237560 + */ + +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.JScrollPane; + +public class bug4237560 { + static final String INSTRUCTIONS = """ + A JEditorPane contains 10 input fields and is inserted into + JScrollPane. Click text field #8 so that it is selected. Press + TAB three times (even if text field #9 and #10 are not visible in + the ScrollPane). If this gives focus to the first text field (#1) + the test PASSES, else it FAILS. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4237560 Test Instructions") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(bug4237560::createUI) + .build() + .awaitAndCheck(); + } + + private static final String TEXT = "
\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "\n" + + "
"; + + private static JFrame createUI() { + JFrame frame = new JFrame("JScrollPane HTML TAB Test"); + JEditorPane viewer = new JEditorPane("text/html", TEXT); + viewer.setEditable(false); + frame.add(new JScrollPane(viewer)); + frame.setSize(300, 300); + return frame; + } +} diff --git a/test/jdk/javax/swing/JScrollPane/bug4244899.java b/test/jdk/javax/swing/JScrollPane/bug4244899.java new file mode 100644 index 000000000000..4cb5367f4f54 --- /dev/null +++ b/test/jdk/javax/swing/JScrollPane/bug4244899.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1999, 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 4244899 + * @summary Tests whether scrolling with blit has artifacts + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @run main/manual bug4244899 + */ + +import javax.swing.JFrame; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.table.AbstractTableModel; + +public class bug4244899 { + static final String INSTRUCTIONS = """ + Widen the first column of the table, so that + you get a horizontal scrollbar. Click in the + scrollbar (not on the thumb, but in the track). + If you notice some artifacts/flashing at + the bottom of the frame, the test FAILS. + Otherwise, the test PASSES. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug4244899 Test Instructions") + .instructions(INSTRUCTIONS) + .columns(40) + .testUI(bug4244899::createUI) + .build() + .awaitAndCheck(); + } + + static class TestModel extends AbstractTableModel { + private final int rows = 20; + private final int cols = 5; + + private Integer[][] data; + + public TestModel() { + data = new Integer[rows][]; + int realCount = 0; + for (int counter = 0; counter < rows; counter++) { + data[counter] = new Integer[cols]; + for (int y = 0; y < cols; y++) { + data[counter][y] = Integer.valueOf(realCount); + realCount = (realCount + 1) % 23; + } + } + } + + public int getRowCount() { + return data.length; + } + + public int getColumnCount() { + return data[0].length; + } + + public Object getValueAt(int row, int column) { + return data[row][column]; + } + } + + static JFrame createUI() { + JFrame f = new JFrame("Scrolling Blit Artifact Test"); + JTable table = new JTable(new TestModel()); + JScrollPane sp = new JScrollPane(table); + sp.getViewport().putClientProperty("EnableWindowBlit", Boolean.TRUE); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + f.add(sp); + f.setSize(400, 400); + return f; + } +} diff --git a/test/jdk/javax/swing/JSlider/bug4382876.java b/test/jdk/javax/swing/JSlider/bug4382876.java index b9ec64aab216..b0988de3cabd 100644 --- a/test/jdk/javax/swing/JSlider/bug4382876.java +++ b/test/jdk/javax/swing/JSlider/bug4382876.java @@ -48,8 +48,8 @@ public class bug4382876 { private static Robot r; private static JFrame f; private static JSlider slider; - private static boolean upFail; - private static boolean downFail; + private static volatile boolean upFail; + private static volatile boolean downFail; public static void main(String[] args) throws Exception { try { @@ -70,23 +70,30 @@ public static void main(String[] args) throws Exception { r.delay(1000); r.keyPress(KeyEvent.VK_PAGE_UP); + r.keyRelease(KeyEvent.VK_PAGE_UP); + SwingUtilities.invokeAndWait(() -> { if (slider.getValue() < -1000) { System.out.println("PAGE_UP VAL: " + slider.getValue()); upFail = true; } }); + if (upFail) { writeFailImage(); throw new RuntimeException("Slider value did NOT change with PAGE_UP"); } + r.keyPress(KeyEvent.VK_PAGE_DOWN); + r.keyRelease(KeyEvent.VK_PAGE_DOWN); + SwingUtilities.invokeAndWait(() -> { if (slider.getValue() > -1000) { System.out.println("PAGE_DOWN VAL: " + slider.getValue()); downFail = true; } }); + if (downFail) { writeFailImage(); throw new RuntimeException("Slider value did NOT change with PAGE_DOWN"); diff --git a/test/jdk/javax/swing/JSpinner/8223788/JSpinnerButtonFocusTest.java b/test/jdk/javax/swing/JSpinner/8223788/JSpinnerButtonFocusTest.java index 4060042ca4f7..994a03959b2b 100644 --- a/test/jdk/javax/swing/JSpinner/8223788/JSpinnerButtonFocusTest.java +++ b/test/jdk/javax/swing/JSpinner/8223788/JSpinnerButtonFocusTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -63,7 +63,7 @@ public static void main(String args[]) throws Exception { robot.setAutoDelay(50); SwingUtilities.invokeAndWait(() -> { - frame = new JFrame(); + frame = new JFrame("JSpinnerButtonFocusTest"); spinner1 = new JSpinner(); spinner2 = new JSpinner(); @@ -72,6 +72,15 @@ public static void main(String args[]) throws Exception { frame.getContentPane().add(spinner2, BorderLayout.SOUTH); editor1 = ((DefaultEditor)spinner1.getEditor()); + editor1.getTextField().addFocusListener(new FocusAdapter() { + @Override + public void focusGained(FocusEvent e) { + super.focusGained(e); + robot.keyPress(KeyEvent.VK_TAB); + robot.keyRelease(KeyEvent.VK_TAB); + latch1.countDown(); + } + }); editor1.setFocusable(false); spinner1.setFocusable(false); @@ -84,26 +93,18 @@ public static void main(String args[]) throws Exception { frame.setFocusTraversalPolicyProvider(true); frame.setAlwaysOnTop(true); - frame.pack(); + frame.setSize(100, 100); + frame.setLocationRelativeTo(null); frame.setVisible(true); }); robot.waitForIdle(); - - editor1.getTextField().addFocusListener(new FocusAdapter() { - @Override - public void focusGained(FocusEvent e) { - super.focusGained(e); - robot.keyPress(KeyEvent.VK_TAB); - robot.keyRelease(KeyEvent.VK_TAB); - latch1.countDown(); - } - }); + robot.delay(1000); SwingUtilities.invokeAndWait(() -> { editor1.getTextField().requestFocusInWindow(); }); - if (!latch1.await(15, TimeUnit.MINUTES)) { + if (!latch1.await(1, TimeUnit.MINUTES)) { throw new RuntimeException(LF.getClassName() + ": Timeout waiting for editor1 to gain focus."); } diff --git a/test/jdk/javax/swing/JTabbedPane/4624207/bug4624207.java b/test/jdk/javax/swing/JTabbedPane/4624207/bug4624207.java index 10de2ab221ad..4d2fdcf030cd 100644 --- a/test/jdk/javax/swing/JTabbedPane/4624207/bug4624207.java +++ b/test/jdk/javax/swing/JTabbedPane/4624207/bug4624207.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2018, 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 @@ -25,25 +25,26 @@ * @test * @key headful * @bug 4624207 + * @requires (os.family != "mac") * @summary JTabbedPane mnemonics don't work from outside the tabbed pane - * @author Oleg Mokhovikov - * @library /test/lib - * @library ../../regtesthelpers - * @build Util jdk.test.lib.Platform * @run main bug4624207 */ -import javax.swing.*; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import java.awt.*; + +import java.awt.BorderLayout; +import java.awt.Robot; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; -import jdk.test.lib.Platform; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JTabbedPane; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; public class bug4624207 implements ChangeListener, FocusListener { - private static volatile boolean stateChanged = false; private static volatile boolean focusGained = false; private static JTextField txtField; @@ -71,51 +72,39 @@ public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(50); - SwingUtilities.invokeAndWait(new Runnable() { - - public void run() { - createAndShowGUI(); - } - }); - + SwingUtilities.invokeAndWait(() -> createAndShowGUI()); robot.waitForIdle(); - - SwingUtilities.invokeAndWait(new Runnable() { - - public void run() { - txtField.requestFocus(); - } - }); - + SwingUtilities.invokeAndWait(() -> txtField.requestFocus()); robot.waitForIdle(); if (!focusGained) { throw new RuntimeException("Couldn't gain focus for text field"); } - SwingUtilities.invokeAndWait(new Runnable() { - - public void run() { - tab.addChangeListener((ChangeListener) listener); - txtField.removeFocusListener((FocusListener) listener); - } + SwingUtilities.invokeAndWait(() -> { + tab.addChangeListener((ChangeListener) listener); + txtField.removeFocusListener((FocusListener) listener); }); robot.waitForIdle(); - if (Platform.isOSX()) { - Util.hitKeys(robot, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_B); - } else { - Util.hitKeys(robot, KeyEvent.VK_ALT, KeyEvent.VK_B); - } + robot.keyPress(KeyEvent.VK_ALT); + robot.keyPress(KeyEvent.VK_B); + robot.keyRelease(KeyEvent.VK_B); + robot.keyRelease(KeyEvent.VK_ALT); robot.waitForIdle(); if (!stateChanged || tab.getSelectedIndex() != 1) { - throw new RuntimeException("JTabbedPane mnemonics don't work from outside the tabbed pane"); + throw new RuntimeException("JTabbedPane mnemonics don't " + + "work from outside the tabbed pane"); } } finally { - if (frame != null) SwingUtilities.invokeAndWait(() -> frame.dispose()); + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } diff --git a/test/jdk/javax/swing/plaf/motif/bug4150591.java b/test/jdk/javax/swing/plaf/motif/bug4150591.java index 66c668a441c3..f3614908cfff 100644 --- a/test/jdk/javax/swing/plaf/motif/bug4150591.java +++ b/test/jdk/javax/swing/plaf/motif/bug4150591.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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,6 +23,7 @@ import com.sun.java.swing.plaf.motif.MotifInternalFrameTitlePane; import javax.swing.JInternalFrame; +import javax.swing.UIManager; /* * @test @@ -36,7 +37,8 @@ */ public class bug4150591 { - public static void main(String[] args) { + public static void main(String[] args) throws Exception { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); MotifInternalFrameTitlePane mtp = new MotifInternalFrameTitlePane(new JInternalFrame()); } } diff --git a/test/jdk/javax/swing/text/Caret/8163124/CaretFloatingPointAPITest.java b/test/jdk/javax/swing/text/Caret/8163124/CaretFloatingPointAPITest.java index 19d6d6a86079..c02fcfcfb907 100644 --- a/test/jdk/javax/swing/text/Caret/8163124/CaretFloatingPointAPITest.java +++ b/test/jdk/javax/swing/text/Caret/8163124/CaretFloatingPointAPITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -222,11 +222,11 @@ public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.draw(new Line2D.Float(c, cy, c, cy + ch)); - g2d.draw(new Line2D.Float(cx, cy, cx + cw, cy)); - g2d.draw(new Line2D.Float(cx, cy + ch, cx + cw, cy + ch)); } void repaint(Rectangle r) { + r.width += 1; + r.height += 1; component.repaint(r); } @@ -424,6 +424,8 @@ protected void adjustVisibility(Rectangle nloc) { protected synchronized void damage(Rectangle r) { if (r != null && component != null) { + r.width += 1; + r.height += 1; component.repaint(r); } } diff --git a/test/jdk/javax/swing/text/JTextComponent/bug4532590.java b/test/jdk/javax/swing/text/JTextComponent/bug4532590.java new file mode 100644 index 000000000000..d317a33fdea2 --- /dev/null +++ b/test/jdk/javax/swing/text/JTextComponent/bug4532590.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2003, 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 4532590 + * @summary Tests that selection is not painted when highlighter is set to null + * @run main bug4532590 + */ + +import java.awt.Color; +import java.awt.image.BufferedImage; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.JTextComponent; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.SwingUtilities; + +public class bug4532590 { + + static final int SELECTION_START = 5; + static final int SELECTION_END = 10; + static final String TEXT = "Typein the missing word."; + + static final Color TEXT_FG = Color.BLACK; + static final Color TEXT_BG = Color.WHITE; + static final Color SELECTION_FG = Color.RED; + static final Color SELECTION_BG = Color.YELLOW; + + JTextComponent[] comps; + JTextPane pane; + JTextArea area, warea; + + int selFG = SELECTION_FG.getRGB(); + int selBG = SELECTION_BG.getRGB(); + + public bug4532590() throws BadLocationException { + // text pane + pane = new JTextPane(); + pane.setContentType("text/plain"); + + // populate the pane + DefaultStyledDocument dsd = new DefaultStyledDocument(); + dsd.insertString(0, "\n" + TEXT + "\n\n", new SimpleAttributeSet()); + pane.setDocument(dsd); + + // text area + area = new JTextArea(); + area.setText("\n" + TEXT); + + // wrapped text area + warea = new JTextArea(); + warea.setText("\n" + TEXT); + + comps = new JTextComponent[3]; + comps[0] = pane; + comps[1] = area; + comps[2] = warea; + } + + void initComp(JTextComponent comp) { + comp.setEditable(false); + comp.setForeground(TEXT_FG); + comp.setBackground(TEXT_BG); + comp.setSelectedTextColor(SELECTION_FG); + comp.setSelectionColor(SELECTION_BG); + comp.setHighlighter(null); + comp.setSize(comp.getPreferredSize()); + + comp.setSelectionStart(SELECTION_START); + comp.setSelectionEnd(SELECTION_END); + comp.getCaret().setSelectionVisible(true); + } + + /** + * Paint given component on an offscreen buffer + */ + BufferedImage drawComp(JTextComponent comp) { + int w = comp.getWidth(); + int h = comp.getHeight(); + + BufferedImage img = + new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + comp.paint(img.createGraphics()); + return img; + } + + void testComp(JTextComponent comp) { + initComp(comp); + BufferedImage img = drawComp(comp); + int w = img.getWidth(null); + int h = img.getHeight(null); + + // scan the image + // there should be no SELECTION_FG or SELECTION_BG pixels + for (int i = 0; i < w; i++) { + for (int j = 0; j < h; j++) { + int rgb = img.getRGB(i, j); + if (rgb == selFG) { + throw new RuntimeException( + "Failed: selection foreground painted"); + } else if (rgb == selBG) { + throw new RuntimeException( + "Failed: selection background painted"); + } + } + } + } + + void test() { + for (int i = 0; i < comps.length; i++) { + testComp(comps[i]); + } + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + try { + new bug4532590().test(); + } catch (BadLocationException e) { + throw new RuntimeException(e); + } + }); + } +} diff --git a/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java b/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java index ff5d52d95a65..62549e7b5183 100644 --- a/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java +++ b/test/jdk/jdk/internal/platform/docker/MetricsCpuTester.java @@ -145,9 +145,13 @@ private static void testCpuSetMemNodes(String cpusetMems) { private static void testCpuShares(long shares) { Metrics metrics = Metrics.systemMetrics(); if ("cgroupv2".equals(metrics.getProvider()) && shares < 1024) { - // Adjust input shares for < 1024 cpu shares as the - // impl. rounds up to the next multiple of 1024 - shares = 1024; + // Don't assert for shares values less than 1024 as we don't + // have a 1-to-1 mapping from the cgroup v2 value to the OCI + // value. + System.out.println("Debug: cgv2 - Got CPU shares of: " + + metrics.getCpuShares() + " - Skipping assert."); + System.out.println("TEST PASSED!!!"); + return; } long newShares = metrics.getCpuShares(); if (newShares != shares) { diff --git a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java index 2afb5ed93b1e..8d63e76c141e 100644 --- a/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java +++ b/test/jdk/jdk/internal/platform/docker/TestDockerMemoryMetrics.java @@ -82,9 +82,7 @@ public static void main(String[] args) throws Exception { testMemorySoftLimit("500m","200m"); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java b/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java index b9d031f03090..5a89c04796aa 100644 --- a/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java +++ b/test/jdk/jdk/internal/platform/docker/TestGetFreeSwapSpaceSize.java @@ -53,9 +53,7 @@ public static void main(String[] args) throws Exception { "150M", Integer.toString(0) ); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java b/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java index 31e90e8802a9..ee9e7f41ab0e 100644 --- a/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java +++ b/test/jdk/jdk/internal/platform/docker/TestLimitsUpdating.java @@ -64,9 +64,7 @@ public static void main(String[] args) throws Exception { try { testLimitUpdates(); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java b/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java index 6b19bb475f13..04c172b13b8f 100644 --- a/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java +++ b/test/jdk/jdk/internal/platform/docker/TestPidsLimit.java @@ -60,9 +60,7 @@ public static void main(String[] args) throws Exception { testPidsLimit("2000"); testPidsLimit("Unlimited"); } finally { - if (!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { - DockerTestUtils.removeDockerImage(imageName); - } + DockerTestUtils.removeDockerImage(imageName); } } diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestFilledChunks.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestFilledChunks.java index 18bfa57a4b18..903df39628c4 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestFilledChunks.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestFilledChunks.java @@ -26,6 +26,7 @@ import java.util.Random; import jdk.jfr.Event; +import jdk.jfr.StackTrace; import jdk.jfr.consumer.RecordingStream; /** @@ -38,6 +39,7 @@ */ public class TestFilledChunks { + @StackTrace(false) static class FillEvent extends Event { String message; int value; diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestMetadataReconstructionWithRetainedStringPool.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestMetadataReconstructionWithRetainedStringPool.java new file mode 100644 index 000000000000..8bbadc6db290 --- /dev/null +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestMetadataReconstructionWithRetainedStringPool.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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.jfr.api.consumer.streaming; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.CountDownLatch; + +import jdk.jfr.Event; +import jdk.jfr.consumer.RecordingStream; + +/** + * @test + * @summary Test that it is possible to register new metadata in a new segment while retaining the string pool. + * @requires vm.flagless + * @requires vm.hasJFR + * @library /test/lib + * @run main/othervm jdk.jfr.api.consumer.streaming.TestMetadataReconstructionWithRetainedStringPool + */ +public class TestMetadataReconstructionWithRetainedStringPool { + /// Minimum string length required to trigger StringPool usage. + /// Mirrors `jdk.jfr.internal.StringPool.MIN_LIMIT`. + private static final int STRING_POOL_MIN_LIMIT = 16; + private static final int EXPECTED_EVENTS = 3; + + // Condition 1: String length > STRING_POOL_MIN_LIMIT triggers CONSTANT_POOL encoding. + private static final String TEXT = "a".repeat(STRING_POOL_MIN_LIMIT + 1);; + + static final class EventA extends Event { + String text = TEXT; + } + + static final class EventB extends Event { + String text = TEXT; + } + + public static void main(String... args) throws InterruptedException { + var aEventsPosted = new CountDownLatch(1); + var readyToPostEventB = new CountDownLatch(1); + var remaining = new CountDownLatch(EXPECTED_EVENTS); + + try (var rs = new RecordingStream()) { + rs.onEvent(e -> { + String textValue = e.getValue("text"); + if (textValue == null) { + throw new RuntimeException("e.getValue(\"text\") returned null"); + } + remaining.countDown(); + System.out.printf("Event #%d [%s]: text=%s%n", + EXPECTED_EVENTS - remaining.getCount(), + e.getEventType().getName(), + textValue); + }); + + rs.onFlush(() -> { + if (aEventsPosted.getCount() == 0) { + readyToPostEventB.countDown(); + } + }); + + rs.startAsync(); + + // Condition 2: Two distinct event types are required. + // First, load EventA as the initial event type and emit its first event. + // This first event looks into the StringPool pre-cache. Although the + // string length qualifies for pooling, because it isn't pre-cached, + // the first event encodes the string inline. + // The second event finds the string in the pre-cache and adds it to the + // pool. A constant pool ID to the pooled string is encoded in the event. + // + new EventA().commit(); + new EventA().commit(); + aEventsPosted.countDown(); + + // Condition 3: Wait for JFR flush. + // The default flush period is ~1 second. + readyToPostEventB.await(); + + // Load the second event type, EventB, AFTER the flush segment containing the two events of type EventA. + // A new metadata description will be constructed, and we verify that the StringPool added in the previous + // segment is still available for the EventB string pool reference to be resolved correctly. + new EventB().commit(); + remaining.await(); + } + } +} diff --git a/test/jdk/jdk/jfr/api/consumer/streaming/TestStartMultiChunk.java b/test/jdk/jdk/jfr/api/consumer/streaming/TestStartMultiChunk.java index baae06b8ec71..c9265d21023b 100644 --- a/test/jdk/jdk/jfr/api/consumer/streaming/TestStartMultiChunk.java +++ b/test/jdk/jdk/jfr/api/consumer/streaming/TestStartMultiChunk.java @@ -44,7 +44,7 @@ */ public class TestStartMultiChunk { - @Period("10 s") + @Period("2 s") @Name("Zebra") static class ZebraEvent extends Event { } @@ -65,7 +65,7 @@ public static void main(String... args) throws Exception { CountDownLatch dogLatch = new CountDownLatch(1); CountDownLatch catLatch = new CountDownLatch(1); CountDownLatch mouseLatch = new CountDownLatch(1); - CountDownLatch zebraLatch = new CountDownLatch(3); + CountDownLatch zebraLatch = new CountDownLatch(2); FlightRecorder.addPeriodicEvent(ZebraEvent.class, () -> { ZebraEvent ze = new ZebraEvent(); diff --git a/test/jdk/jdk/jfr/event/oldobject/OldObjects.java b/test/jdk/jdk/jfr/event/oldobject/OldObjects.java index ba90bb10a9ee..bb0ca27836ea 100644 --- a/test/jdk/jdk/jfr/event/oldobject/OldObjects.java +++ b/test/jdk/jdk/jfr/event/oldobject/OldObjects.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -276,4 +276,16 @@ public static void validateReferenceChainLimit(RecordedEvent e, int maxLength) { throw new RuntimeException("Reference chain max length not respected. Found a chain of length " + length); } } + + public static int countChains(List events) throws IOException { + int found = 0; + for (RecordedEvent e : events) { + RecordedObject ro = e.getValue("object"); + if (ro.getValue("referrer") != null) { + found++; + } + } + System.out.println("Found chains: " + found); + return found; + } } diff --git a/test/jdk/jdk/jfr/event/oldobject/TestDFSWithSmallStack.java b/test/jdk/jdk/jfr/event/oldobject/TestDFSWithSmallStack.java new file mode 100644 index 000000000000..d25a6cd5f67e --- /dev/null +++ b/test/jdk/jdk/jfr/event/oldobject/TestDFSWithSmallStack.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2026, IBM Corp. + * 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.jfr.event.oldobject; + +import java.util.LinkedList; +import java.util.List; + +import jdk.jfr.Recording; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.internal.test.WhiteBox; +import jdk.test.lib.jfr.EventNames; +import jdk.test.lib.jfr.Events; + +/** + * @test id=dfsonly + * @summary Tests that DFS works with a small stack + * @library /test/lib /test/jdk + * @requires vm.hasJFR + * @modules jdk.jfr/jdk.jfr.internal.test + * @run main/othervm -Xmx2g -XX:VMThreadStackSize=512 jdk.jfr.event.oldobject.TestDFSWithSmallStack dfsonly + */ + +/** + * @test id=bfsdfs + * @summary Tests that DFS works with a small stack + * @library /test/lib /test/jdk + * @requires vm.hasJFR + * @modules jdk.jfr/jdk.jfr.internal.test + * @run main/othervm -Xmx2g -XX:VMThreadStackSize=512 jdk.jfr.event.oldobject.TestDFSWithSmallStack bfsdfs + */ +public class TestDFSWithSmallStack { + + // Tests depth first search with a small stack. + + // An non-zero exit code, together with a missing hs-err file or possibly a missing jfr file, + // indicates a native stack overflow happened and is a fail condition for this test. + + // We build up an array of linked lists, each containing enough entries for DFS search to + // max out max_dfs_depth (but not greatly surpass it). + + private static final int TOTAL_OBJECTS = 10_000_000; + private static final int OBJECTS_PER_LIST = 5_000; + public static LinkedList[] leak; + + public static void main(String... args) throws Exception { + + switch (args[0]) { + case "dfsonly" -> WhiteBox.setSkipBFS(true); + case "bfsdfs" -> {} /* ignored */ + default -> throw new RuntimeException("Invalid argument"); + } + + WhiteBox.setWriteAllObjectSamples(true); + int count = 10; + + while (count > 0) { + try (Recording r = new Recording()) { + r.enable(EventNames.OldObjectSample).with("cutoff", "infinity"); + r.start(); + leak = new LinkedList[TOTAL_OBJECTS / OBJECTS_PER_LIST]; + for (int i = 0; i < leak.length; i++) { + leak[i] = new LinkedList(); + for (int j = 0; j < OBJECTS_PER_LIST; j++) { + leak[i].add(new Object()); + } + } + System.gc(); + r.stop(); + List events = Events.fromRecording(r); + Events.hasEvents(events); + if (OldObjects.countChains(events) >= 30) { + return; + } + System.out.println("Not enough chains found, retrying."); + } + count--; + leak = null; + } + } +} diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestEnableDisable.java b/test/jdk/jdk/jfr/jmx/streaming/TestEnableDisable.java index 6a07c57ff787..62d22c821713 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestEnableDisable.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestEnableDisable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -36,7 +36,7 @@ /** * @test * @key jfr - * @summary Tests that event settings for a RemoteRecordingStream can be changed + * @summary Tests that the enabled setting can be configured for a RemoteRecordingStream * @requires vm.hasJFR * @library /test/lib /test/jdk * @run main/othervm jdk.jfr.jmx.streaming.TestEnableDisable diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestMaxSize.java b/test/jdk/jdk/jfr/jmx/streaming/TestMaxSize.java index 7bf389c75ad8..69f36b2ec2a3 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestMaxSize.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestMaxSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -33,6 +33,7 @@ import javax.management.MBeanServerConnection; import jdk.jfr.Event; +import jdk.jfr.StackTrace; import jdk.management.jfr.RemoteRecordingStream; /** @@ -45,6 +46,7 @@ */ public class TestMaxSize { + @StackTrace(false) static class Monkey extends Event { } @@ -92,7 +94,7 @@ private static void emitEvents(int count) throws InterruptedException { m.commit(); } System.out.println("Emitted " + count + " events"); - Thread.sleep(1000); + Thread.sleep(100); } private static int fileCount(Path dir) throws IOException { diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestRemoteDump.java b/test/jdk/jdk/jfr/jmx/streaming/TestRemoteDump.java index 51e0c815dc0b..7a2b52b9deb7 100644 --- a/test/jdk/jdk/jfr/jmx/streaming/TestRemoteDump.java +++ b/test/jdk/jdk/jfr/jmx/streaming/TestRemoteDump.java @@ -97,7 +97,7 @@ private static void testClosed() throws Exception { } } - private static List recordWithPolicy(String filename, Consumer policy) throws Exception { + private static List recordWithPolicy(String filename, boolean awaitEvents, Consumer policy) throws Exception { CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(2); CountDownLatch latch3 = new CountDownLatch(3); @@ -111,14 +111,18 @@ private static List recordWithPolicy(String filename, Consumer recordWithPolicy(String filename, Consumer { + var events = recordWithPolicy("max-size.jfr", false, rs -> { // keeps all events for the dump rs.setMaxSize(100_000_000); }); @@ -140,7 +144,7 @@ private static void testSetMaxSize() throws Exception { } private static void testSetMaxAge() throws Exception { - var events = recordWithPolicy("max-age.jfr", rs -> { + var events = recordWithPolicy("max-age.jfr", false, rs -> { // keeps all events for the dump rs.setMaxAge(Duration.ofDays(1)); }); @@ -151,7 +155,7 @@ private static void testSetMaxAge() throws Exception { } private static void testSetNoPolicy() throws Exception { - var events = recordWithPolicy("no-policy.jfr", rs -> { + var events = recordWithPolicy("no-policy.jfr", true, rs -> { // use default policy, remove after consumption }); // Since latch3 have been triggered at least two events/chunks diff --git a/test/jdk/jdk/jfr/jmx/streaming/TestWithers.java b/test/jdk/jdk/jfr/jmx/streaming/TestWithers.java new file mode 100644 index 000000000000..933337ef76b9 --- /dev/null +++ b/test/jdk/jdk/jfr/jmx/streaming/TestWithers.java @@ -0,0 +1,141 @@ +/* + * 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. + */ +package jdk.jfr.jmx.streaming; + +import java.lang.management.ManagementFactory; +import java.time.Duration; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Predicate; + +import javax.management.MBeanServerConnection; + +import jdk.jfr.Event; +import jdk.jfr.EventSettings; +import jdk.jfr.FlightRecorder; +import jdk.jfr.Name; +import jdk.jfr.Period; +import jdk.jfr.StackTrace; +import jdk.jfr.Threshold; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedStackTrace; +import jdk.management.jfr.RemoteRecordingStream; + +/** + * @test + * @requires vm.flagless + * @summary Tests that event settings for a RemoteRecordingStream can be changed + * @requires vm.hasJFR + * @library /test/lib /test/jdk + * @run main/othervm jdk.jfr.jmx.streaming.TestWithers + */ +public class TestWithers { + private static final Set RESULT = Collections.synchronizedSet(new HashSet<>()); + + @Name("AA") + @StackTrace(false) + static class A extends Event { + } + + @Name("BB") + @StackTrace(true) + static class B extends Event { + } + + @Name("CC") + @Threshold("10 h") + static class C extends Event { + } + + @Name("DD") + @Threshold("10 h") + static class D extends Event { + } + + @Name("EE") + @StackTrace(false) + static class E extends Event { + } + + @Name("FF") + @Period("10 h") + static class F extends Event { + } + + public static void main(String... args) throws Exception { + MBeanServerConnection conn = ManagementFactory.getPlatformMBeanServer(); + try (RemoteRecordingStream stream = new RemoteRecordingStream(conn)) { + addCheck(stream, es -> es.withStackTrace(), "AA", TestWithers::hasStackTrace); + addCheck(stream, es -> es.withoutStackTrace(), "BB", e -> !hasStackTrace(e)); + addCheck(stream, es -> es.withThreshold(Duration.ofMillis(0)), "CC", e -> true); + addCheck(stream, es -> es.withoutThreshold(), "DD", e -> true); + addCheck(stream, es -> es.with("stackTrace", "true"), "EE", TestWithers::hasStackTrace); + addCheck(stream, es -> es.withPeriod(Duration.ofMillis(700)), "FF", e -> true); + FlightRecorder.addPeriodicEvent(F.class, () -> { + F f = new F(); + f.commit(); + }); + stream.onFlush(() -> { + System.out.println(RESULT); + if (RESULT.size() == 6) { + stream.close(); + } + }); + + stream.startAsync(); + A a = new A(); + a.commit(); + + B b = new B(); + b.commit(); + + C c = new C(); + c.commit(); + + D d = new D(); + d.commit(); + + E e = new E(); + e.commit(); + + stream.awaitTermination(); + } + } + + private static void addCheck(RemoteRecordingStream stream, Consumer es, String eventName, Predicate validator) { + es.accept(stream.enable(eventName)); + stream.onEvent(eventName, e -> { + System.out.println(e); + if (validator.test(e)) { + RESULT.add(eventName); + } + }); + } + + private static boolean hasStackTrace(RecordedEvent e) { + RecordedStackTrace rs = e.getStackTrace(); + return rs != null && !rs.getFrames().isEmpty(); + } +} \ No newline at end of file diff --git a/test/jdk/jdk/jfr/jvm/TestWaste.java b/test/jdk/jdk/jfr/jvm/TestWaste.java index 0cc1010765eb..c460fe90a1d5 100644 --- a/test/jdk/jdk/jfr/jvm/TestWaste.java +++ b/test/jdk/jdk/jfr/jvm/TestWaste.java @@ -61,7 +61,7 @@ public static void main(String... args) throws Exception { try (Recording r = new Recording(c)) { // Old objects that are cleared out should not create waste r.enable("jdk.OldObjectSample") - .with("cutoff", "infinity") + .with("cutoff", "2 s") .withStackTrace(); // No stack trace waste from allocation sample r.enable("jdk.ObjectAllocationSample") diff --git a/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java b/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java index 24be874a87f6..391a456962c4 100644 --- a/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java +++ b/test/jdk/jdk/jfr/startupargs/TestMultipleStartupRecordings.java @@ -74,13 +74,6 @@ private static void launchTernary(String options1, String options2, String optio test(pb, "Started recording 1", "Started recording 2", "Started recording 3"); } - private static void testDefault() throws Exception { - System.out.println("testDefault"); - launchUnary(null); - launchBinary(null, null); - launchTernary(null, null, null); - } - private static void testColonDelimited() throws Exception { launchBinary(":name=myrecording1,filename=myrecording1.jfr", ":filename=myrecording2.jfr,name=myrecording2"); } @@ -99,7 +92,6 @@ private static void testWithFlightRecorderOptions() throws Exception { } public static void main(String[] args) throws Exception { - testDefault(); testColonDelimited(); testMixed(); testWithFlightRecorderOptions(); diff --git a/test/jdk/sun/java2d/OpenGL/DrawBitmaskImage.java b/test/jdk/sun/java2d/OpenGL/DrawBitmaskImage.java new file mode 100644 index 000000000000..d2730593b5b1 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/DrawBitmaskImage.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2004, 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 6248561 6264014 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that bitmask image copies work properly with the + * OGL pipeline when a SrcOver composite with extra alpha is involved. + * @run main/othervm -Dsun.java2d.opengl=True DrawBitmaskImage + * @run main/othervm DrawBitmaskImage + */ + +/* + * @test + * @bug 6248561 6264014 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that bitmask image copies work properly with the + * OGL pipeline when a SrcOver composite with extra alpha is involved. + * @run main/othervm -Dsun.java2d.opengl=True DrawBitmaskImage + * @run main/othervm DrawBitmaskImage + */ + +import java.awt.AlphaComposite; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Transparency; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.awt.image.IndexColorModel; +import java.io.File; +import javax.imageio.ImageIO; + +public class DrawBitmaskImage extends Panel { + + static final int TESTW = 200, TESTH = 200; + private static volatile DrawBitmaskImage test; + private static volatile Frame frame; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + g2d.setColor(Color.black); + g2d.fillRect(0, 0, getWidth(), getHeight()); + g2d.setComposite(AlphaComposite.SrcOver.derive(0.50f)); + + BufferedImage img = getGraphicsConfiguration().createCompatibleImage(50, 50, + Transparency.BITMASK); + Graphics2D gimg = img.createGraphics(); + gimg.setComposite(AlphaComposite.Src); + gimg.setColor(new Color(0, 0, 0, 0)); + gimg.fillRect(0, 0, 50, 50); + gimg.setColor(Color.red); + gimg.fillRect(10, 10, 30, 30); + gimg.dispose(); + + + g2d.drawImage(img, 10, 10, null); + + // draw a second time to ensure that the cached copy is used + g2d.drawImage(img, 80, 10, null); + } + + public Dimension getPreferredSize() { + return new Dimension(TESTW, TESTH); + } + + static void createUI() { + test = new DrawBitmaskImage(); + frame = new Frame("OpenGL DrawBitmaskImage Test"); + Panel p = new Panel(); + p.add(test); + frame.add(p); + frame.setSize(TESTW+100, TESTH+100); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + + EventQueue.invokeAndWait(DrawBitmaskImage::createUI); + + robot.waitForIdle(); + robot.delay(2000); + + BufferedImage capture = null; + try { + GraphicsConfiguration gc = frame.getGraphicsConfiguration(); + if (gc.getColorModel() instanceof IndexColorModel) { + System.out.println("IndexColorModel detected: " + + "test considered PASSED"); + return; + } + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, TESTW, TESTH); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test background color + int pixel = capture.getRGB(5, 10); + if (pixel != 0xff000000) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "background (actual=" + + Integer.toHexString(pixel) + ")"); + } + + // Test pixels (allow for small error in the actual red value) + pixel = capture.getRGB(25, 25); + System.out.println("pixel1 is " + Integer.toHexString(pixel)); + + if ((pixel < 0xff7e0000) || (pixel > 0xff900000)) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "first pixel (actual=" + + Integer.toHexString(pixel) + ")"); + } + + pixel = capture.getRGB(95, 25); + System.out.println("pixel2 is " + Integer.toHexString(pixel)); + if ((pixel < 0xff7e0000) || (pixel > 0xff900000)) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "second pixel (actual=" + + Integer.toHexString(pixel) + ")"); + } + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/java/awt/image/VolatileImage/DrawBufImgOp.java b/test/jdk/sun/java2d/OpenGL/DrawBufImgOp.java similarity index 85% rename from test/jdk/java/awt/image/VolatileImage/DrawBufImgOp.java rename to test/jdk/sun/java2d/OpenGL/DrawBufImgOp.java index 011b5e661678..5d60eb7e792a 100644 --- a/test/jdk/java/awt/image/VolatileImage/DrawBufImgOp.java +++ b/test/jdk/sun/java2d/OpenGL/DrawBufImgOp.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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,20 +20,54 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + +/* + * @test + * @bug 6514990 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that calling + * Graphics2D.drawImage(BufferedImage, BufferedImageOp, x, y) to an + * OpenGL-accelerated destination produces the same results when performed + * in software via BufferedImageOp.filter(). + * @run main/othervm -Dsun.java2d.opengl=True DrawBufImgOp -ignore + */ + /* * @test + * @bug 6514990 * @key headful - * @bug 6514990 8198613 + * @requires (os.family == "mac") * @summary Verifies that calling * Graphics2D.drawImage(BufferedImage, BufferedImageOp, x, y) to an - * accelerated destination produces the same results when performed + * OpenGL-accelerated destination produces the same results when performed * in software via BufferedImageOp.filter(). - * @run main/othervm DrawBufImgOp -ignore - * @author campbelc + * @run main/othervm -Dsun.java2d.opengl=True DrawBufImgOp -ignore */ -import java.awt.*; -import java.awt.image.*; +import java.awt.AlphaComposite; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.awt.image.ByteLookupTable; +import java.awt.image.ColorModel; +import java.awt.image.ConvolveOp; +import java.awt.image.IndexColorModel; +import java.awt.image.Kernel; +import java.awt.image.LookupOp; +import java.awt.image.RescaleOp; +import java.awt.image.ShortLookupTable; +import java.awt.image.VolatileImage; import java.io.File; import javax.imageio.ImageIO; @@ -51,14 +85,16 @@ * any exceptions/crashes in the OGL code. When we fix all of the * outstanding bugs with the software codepaths, we can remove the * "-ignore" flag and maybe even restore the "-compare" flag. In the - * meantime, it stil functions well as a manual testcase (with either + * meantime, it also functions well as a manual testcase (with either * the "-show" or "-dump" options). */ public class DrawBufImgOp extends Canvas { private static final int TESTW = 600; private static final int TESTH = 500; - private static boolean done; + + private static volatile DrawBufImgOp test; + private static volatile Frame frame; /* * If true, skips tests that are known to trigger bugs (which in @@ -184,11 +220,6 @@ public class DrawBufImgOp extends Canvas { } public void paint(Graphics g) { - synchronized (this) { - if (done) { - return; - } - } VolatileImage vimg = createVolatileImage(TESTW, TESTH); vimg.validate(getGraphicsConfiguration()); @@ -198,13 +229,6 @@ public void paint(Graphics g) { g2d.dispose(); g.drawImage(vimg, 0, 0, null); - - Toolkit.getDefaultToolkit().sync(); - - synchronized (this) { - done = true; - notifyAll(); - } } /* @@ -379,6 +403,8 @@ private static void compareImages(BufferedImage refImg, Color expected = new Color(refImg.getRGB(x, y)); Color actual = new Color(testImg.getRGB(x, y)); if (!isSameColor(expected, actual, tolerance)) { + saveImage("referenceimage", refImg); + saveImage("testimage", testImg); throw new RuntimeException("Test failed at x="+x+" y="+y+ " (expected="+expected+ " actual="+actual+ @@ -410,7 +436,20 @@ private static boolean isSameColor(Color c1, Color c2, int e) { return false; } + + static void createUI() { + test = new DrawBufImgOp(); + Panel panel = new Panel(); + panel.add(test); + frame = new Frame("OpenGL DrawBufImgOp Test"); + frame.add(panel); + frame.setSize(TESTW+100, TESTH+100); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + public static void main(String[] args) throws Exception { + boolean show = false; boolean dump = false; boolean compare = false; @@ -427,43 +466,27 @@ public static void main(String[] args) throws Exception { } } - DrawBufImgOp test = new DrawBufImgOp(); - Frame frame = new Frame(); - frame.add(test); - frame.pack(); - frame.setVisible(true); + Robot robot = new Robot(); - // Wait until the component's been painted - synchronized (test) { - while (!done) { - try { - test.wait(); - } catch (InterruptedException e) { - throw new RuntimeException("Failed: Interrupted"); - } - } - } + EventQueue.invokeAndWait(DrawBufImgOp::createUI); - GraphicsConfiguration gc = frame.getGraphicsConfiguration(); - if (gc.getColorModel() instanceof IndexColorModel) { - System.out.println("IndexColorModel detected: " + - "test considered PASSED"); - frame.dispose(); - return; - } + robot.waitForIdle(); + robot.delay(2000); - // Grab the screen region BufferedImage capture = null; try { - Robot robot = new Robot(); + GraphicsConfiguration gc = frame.getGraphicsConfiguration(); + if (gc.getColorModel() instanceof IndexColorModel) { + System.out.println("IndexColorModel detected: " + + "test considered PASSED"); + return; + } Point pt1 = test.getLocationOnScreen(); Rectangle rect = new Rectangle(pt1.x, pt1.y, TESTW, TESTH); capture = robot.createScreenCapture(rect); - } catch (Exception e) { - throw new RuntimeException("Problems creating Robot"); } finally { - if (!show) { - frame.dispose(); + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); } } @@ -471,14 +494,21 @@ public static void main(String[] args) throws Exception { if (dump || compare) { BufferedImage ref = test.makeReferenceImage(); if (dump) { - ImageIO.write(ref, "png", - new File("DrawBufImgOp.ref.png")); - ImageIO.write(capture, "png", - new File("DrawBufImgOp.cap.png")); + saveImage("DrawBufImgOp_ref", ref); + saveImage("DrawBufImgOp_cap", capture); } if (compare) { test.compareImages(ref, capture, 1); } } } + + static void saveImage(String name, BufferedImage img) { + try { + File file = new File(name + ".png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/test/jdk/sun/java2d/OpenGL/DrawImageBg.java b/test/jdk/sun/java2d/OpenGL/DrawImageBg.java new file mode 100644 index 000000000000..7fc38d91b06e --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/DrawImageBg.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2004, 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 4993274 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that managed image copies and transforms work properly + * with the OGL pipeline when a background color is specified. + * @run main/othervm -Dsun.java2d.opengl=True DrawImageBg + * @run main/othervm DrawImageBg + */ + +/* + * @test + * @bug 4993274 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that managed image copies and transforms work properly + * with the OGL pipeline when a background color is specified. + * @run main/othervm -Dsun.java2d.opengl=True DrawImageBg + * @run main/othervm DrawImageBg + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Transparency; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class DrawImageBg extends Panel { + + static volatile Frame frame; + static volatile DrawImageBg test; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + g2d.setColor(Color.black); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + BufferedImage img = getGraphicsConfiguration().createCompatibleImage(50, 50, + Transparency.BITMASK); + Graphics2D gimg = img.createGraphics(); + gimg.setComposite(AlphaComposite.Src); + gimg.setColor(new Color(0, 0, 0, 0)); + gimg.fillRect(0, 0, 50, 50); + gimg.setColor(Color.red); + gimg.fillRect(10, 10, 30, 30); + gimg.dispose(); + + g2d.drawImage(img, 10, 10, Color.blue, null); + + // draw a second time to ensure that the cached copy is used + g2d.drawImage(img, 80, 10, Color.blue, null); + } + + static void createUI() { + frame = new Frame("OpenGL DrawImageBg Test"); + test = new DrawImageBg(); + frame.add(test); + frame.setSize(300, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + + BufferedImage capture = null; + Robot robot = new Robot(); + try { + EventQueue.invokeAndWait(DrawImageBg::createUI); + robot.waitForIdle(); + robot.delay(3000); + + // Grab the screen region + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x+80, pt1.y, 80, 80); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + if (capture == null) { + throw new RuntimeException("Screen capture is null"); + } + + // Test inner and outer pixels + int pixel1 = capture.getRGB(5, 10); + if (pixel1 != 0xff0000ff) { + saveImage(capture); + throw new RuntimeException(getMsg("outer", pixel1)); + } + int pixel2 = capture.getRGB(25, 25); + if (pixel2 != 0xffff0000) { + saveImage(capture); + throw new RuntimeException(getMsg("inner", pixel2)); + } + } + + static String getMsg(String r, int p1) { + return "Failed: Incorrect color for " + r + " pixel: got " + Integer.toHexString(p1); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/FlipCoexistTest.java b/test/jdk/sun/java2d/OpenGL/FlipCoexistTest.java new file mode 100644 index 000000000000..beb5da887b4b --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/FlipCoexistTest.java @@ -0,0 +1,134 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * 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.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferStrategy; +import java.awt.image.BufferedImage; +import java.io.File; + +import javax.imageio.ImageIO; + +/** + * @test + * @bug 8378201 + * @key headful + * @summary Verifies that WINDOW and FLIP_BACKBUFFER surfaces sharing the same X + * Window render and flip correctly + * @run main/othervm FlipCoexistTest + * @run main/othervm -Dsun.java2d.opengl=True FlipCoexistTest + */ +public final class FlipCoexistTest { + + private static final int SIZE = 200; + private static final int TOLERANCE = 10; + + public static void main(String[] args) throws Exception { + Frame f = new Frame("FlipCoexistTest"); + try { + f.setUndecorated(true); + f.setSize(SIZE, SIZE); + f.setLocation(100, 100); + f.setVisible(true); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + int w = f.getWidth(); + int h = f.getHeight(); + + // Fill window RED via direct render (WINDOW surface) + Graphics g = f.getGraphics(); + g.setColor(Color.RED); + g.fillRect(0, 0, w, h); + g.dispose(); + robot.waitForIdle(); + robot.delay(500); + + // Request flip if available, blit is also useful to cover + f.createBufferStrategy(2); + BufferStrategy bs = f.getBufferStrategy(); + + // Render BLUE to back buffer, do not flip yet + Graphics bg = bs.getDrawGraphics(); + bg.setColor(Color.BLUE); + bg.fillRect(0, 0, w, h); + bg.dispose(); + + // Paint small GREEN rect via direct render + g = f.getGraphics(); + g.setColor(Color.GREEN); + g.fillRect(0, 0, 10, 10); + g.dispose(); + robot.waitForIdle(); + robot.delay(500); + + // GREEN rect must be visible + check(robot, f, 5, 5, Color.GREEN, "small rect"); + + // RED must survive the context round-trip + check(robot, f, w / 2, h / 2, Color.RED, "survived"); + + // Show back buffer, BLUE must appear + bs.show(); + + robot.waitForIdle(); + robot.delay(500); + check(robot, f, w / 2, h / 2, Color.BLUE, "flip"); + } finally { + f.dispose(); + } + } + + private static void check(Robot robot, Frame frame, int x, int y, Color exp, + String desc) + { + Point loc = frame.getLocationOnScreen(); + Color c = robot.getPixelColor(loc.x + x, loc.y + y); + if (!isAlmostEqual(c, exp)) { + saveImage(robot, frame, desc); + throw new RuntimeException("%s: %s != %s".formatted(desc, exp, c)); + } + } + + private static void saveImage(Robot r, Frame f, String name) { + try { + Rectangle rect = f.getBounds(); + BufferedImage img = r.createScreenCapture(rect); + ImageIO.write(img, "png", new File(name + ".png")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static boolean isAlmostEqual(Color c1, Color c2) { + return Math.abs(c1.getRed() - c2.getRed()) <= TOLERANCE + && Math.abs(c1.getGreen() - c2.getGreen()) <= TOLERANCE + && Math.abs(c1.getBlue() - c2.getBlue()) <= TOLERANCE; + } +} diff --git a/test/jdk/sun/java2d/OpenGL/LargeOps.java b/test/jdk/sun/java2d/OpenGL/LargeOps.java new file mode 100644 index 000000000000..ace60b7a3c49 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/LargeOps.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2004, 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 6219284 6358147 6274813 6578452 + * @key headful + * @summary Verifies that OGLRenderer.drawPoly(), + * OGLTextRenderer.drawGlyphList(), and OGLMaskFill work properly when the + * operation parameters exceed the capacity of the render queue. With the + * single-threaded OpenGL pipeline, there are some operations that require + * a separate buffer to be spawned if the parameters cannot fit entirely on + * the standard buffer. This test exercises this special case. + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.lcdshader=true LargeOps + */ + +import java.awt.Canvas; +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Robot; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class LargeOps extends Canvas { + + private static final int NUM_POINTS = 8000; + private int[] xPoints, yPoints; + private String str; + + public LargeOps() { + xPoints = new int[NUM_POINTS]; + yPoints = new int[NUM_POINTS]; + for (int i = 0; i < NUM_POINTS; i++) { + xPoints[i] = (i % 2 == 0) ? 10 : 400; + yPoints[i] = (i % 2 == 1) ? i+3 : i; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < NUM_POINTS; i+=11) { + sb.append("ThisIsATest"); + } + str = sb.toString(); + } + + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D)g; + g2d.setColor(Color.white); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + // draw large polyline + g2d.setColor(Color.green); + g2d.drawPolyline(xPoints, yPoints, NUM_POINTS); + + // draw long string + g2d.setColor(Color.blue); + g2d.drawString(str, 10, 100); + + // draw long string with larger pt size + Font font = g2d.getFont(); + g2d.setFont(font.deriveFont(40.0f)); + g2d.drawString(str, 10, 150); + + // do the same with LCD hints enabled + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); + g2d.setFont(font); + g2d.drawString(str, 10, 200); + g2d.setFont(font.deriveFont(43.0f)); + g2d.drawString(str, 10, 250); + + g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR); + g2d.setFont(font); + g2d.drawString(str, 10, 300); + g2d.setFont(font.deriveFont(37.0f)); + g2d.drawString(str, 10, 350); + } + + static volatile Frame frame; + static volatile LargeOps test; + + static void createUI() { + frame = new Frame("OpenGL LargeOps Test"); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) { + frame.dispose(); + } + }); + test = new LargeOps(); + frame.add(test); + frame.setSize(600, 600); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + try { + Robot robot = new Robot(); + EventQueue.invokeAndWait(LargeOps::createUI); + robot.waitForIdle(); + robot.delay(6000); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/MultiWindowFillTest.java b/test/jdk/sun/java2d/OpenGL/MultiWindowFillTest.java new file mode 100644 index 000000000000..59c58d944d79 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/MultiWindowFillTest.java @@ -0,0 +1,122 @@ +/* + * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. + * 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.Graphics; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; + +import javax.imageio.ImageIO; + +/** + * @test + * @bug 8378201 + * @key headful + * @summary Verifies that window content survives a GL context switch to another + * window and back + * @run main/othervm MultiWindowFillTest + * @run main/othervm -Dsun.java2d.opengl=True MultiWindowFillTest + */ +public final class MultiWindowFillTest { + + private static final int SIZE = 100; + private static final int TOLERANCE = 10; + + public static void main(String[] args) throws Exception { + Frame f1 = new Frame("f1"); + Frame f2 = new Frame("f2"); + try { + f1.setUndecorated(true); + f1.setSize(SIZE, SIZE); + f1.setLocation(100, 100); + f2.setUndecorated(true); + f2.setSize(SIZE, SIZE); + f2.setLocation(300, 100); + + f1.setVisible(true); + f2.setVisible(true); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + int w = f1.getWidth(); + int h = f1.getHeight(); + + // Fill both, initializes surfaces + fill(f1, Color.RED, w, h); + fill(f2, Color.BLUE, w, h); + + // Touch both again + fill(f1, Color.RED, 2, 2); + fill(f2, Color.BLUE, 2, 2); + + robot.waitForIdle(); + robot.delay(1000); + + check(robot, f1, w, h, Color.RED, "f1 red"); + check(robot, f2, w, h, Color.BLUE, "f2 blue"); + } finally { + f1.dispose(); + f2.dispose(); + } + } + + private static void fill(Frame frame, Color c, int w, int h) { + Graphics g = frame.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, w, h); + g.dispose(); + } + + private static void check(Robot robot, Frame frame, int w, int h, + Color exp, String desc) + { + Point loc = frame.getLocationOnScreen(); + Color c = robot.getPixelColor(loc.x + w / 2, loc.y + h / 2); + if (!isAlmostEqual(c, exp)) { + saveImage(robot, frame, desc); + throw new RuntimeException("%s: %s != %s".formatted(desc, exp, c)); + } + } + + private static void saveImage(Robot r, Frame f, String name) { + try { + Rectangle rect = f.getBounds(); + BufferedImage img = r.createScreenCapture(rect); + ImageIO.write(img, "png", new File(name + ".png")); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static boolean isAlmostEqual(Color c1, Color c2) { + return Math.abs(c1.getRed() - c2.getRed()) <= TOLERANCE + && Math.abs(c1.getGreen() - c2.getGreen()) <= TOLERANCE + && Math.abs(c1.getBlue() - c2.getBlue()) <= TOLERANCE; + } +} diff --git a/test/jdk/sun/java2d/OpenGL/OpaqueDest.java b/test/jdk/sun/java2d/OpenGL/OpaqueDest.java new file mode 100644 index 000000000000..397d516f9ae3 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/OpaqueDest.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 2004, 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 6277977 6319663 8369335 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that blending operations do not inadvertantly leave + * non-opaque alpha values in the framebuffer. Note that this test is + * intended to run on GraphicsConfigs that support a stored alpha channel + * (to verify the bug at hand), but it is also a useful for testing the + * compositing results on any configuration. + * @run main/othervm -Dsun.java2d.opengl=True OpaqueDest + * @run main/othervm OpaqueDest + */ + +/* + * @test + * @bug 6277977 6319663 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that blending operations do not inadvertantly leave + * non-opaque alpha values in the framebuffer. Note that this test is + * intended to run on GraphicsConfigs that support a stored alpha channel + * (to verify the bug at hand), but it is also a useful for testing the + * compositing results on any configuration. + * @run main/othervm -Dsun.java2d.opengl=True OpaqueDest + * @run main/othervm OpaqueDest + */ + +import java.awt.AlphaComposite; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.awt.image.IndexColorModel; +import java.io.File; +import javax.imageio.ImageIO; + +public class OpaqueDest extends Canvas { + + private static volatile Frame frame; + private static volatile OpaqueDest test; + private static final int W = 100, H = 100; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + + g2d.setColor(Color.red); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + // This will clear the rectangle to black + g2d.setComposite(AlphaComposite.Clear); + g2d.fillRect(10, 10, 80, 80); + + // If everything is working properly, then this will fill the + // rectangle with red again. Before this bug was fixed, the previous + // Clear operation would leave zero values in the destination's + // alpha channel (if present), and therefore a SrcIn operation + // would result in all-black. + g2d.setComposite(AlphaComposite.SrcIn); + g2d.fillRect(10, 10, 80, 80); + } + + public Dimension getPreferredSize() { + return new Dimension(W, H); + } + + static void createUI() { + test = new OpaqueDest(); + frame = new Frame("OpenGL OpaqueDest Test"); + Panel p = new Panel(); + p.add(test); + frame.add(p); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + + EventQueue.invokeAndWait(OpaqueDest::createUI); + + robot.waitForIdle(); + robot.delay(2000); + + BufferedImage capture = null; + try { + GraphicsConfiguration gc = frame.getGraphicsConfiguration(); + if (gc.getColorModel() instanceof IndexColorModel) { + System.out.println("IndexColorModel detected: " + + "test considered PASSED"); + return; + } + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, W, H); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + + // Test all pixels (every one should be red) + for (int y = 0; y < W; y++) { + for (int x = 0; x < H; x++) { + int actual = capture.getRGB(x, y); + int expected = 0xffff0000; + if (!similar(actual, expected)) { + String msg = "Test failed at x="+x+" y="+y+ + " (expected="+ + Integer.toHexString(expected) + + " actual="+ + Integer.toHexString(actual) + + ")"; + if ( ( x== 0) || ( x == W) || ( y == 0) || ( y == H)) { + System.err.println(msg); + } else { + saveImage(capture); + throw new RuntimeException(msg); + } + } + } + } + } + + static boolean similar(int p1, int p2) { + int a1 = (p1 >> 24) & 0xff; + int r1 = (p1 >> 16) & 0xff; + int g1 = (p1 >> 8) & 0xff; + int b1 = p1 & 0xff; + int a2 = (p2 >> 24) & 0xff; + int r2 = (p2 >> 16) & 0xff; + int g2 = (p2 >> 8) & 0xff; + int b2 = p2 & 0xff; + + int allowedDiff = 0x01; // tiny rounding error allowed. + return + (Math.abs(a1 - a2) <= allowedDiff) && + (Math.abs(r1 - r2) <= allowedDiff) && + (Math.abs(g1 - g2) <= allowedDiff) && + (Math.abs(b1 - b2) <= allowedDiff); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/ScaleParamsOOB.java b/test/jdk/sun/java2d/OpenGL/ScaleParamsOOB.java new file mode 100644 index 000000000000..acb5e41ce6f6 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/ScaleParamsOOB.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2004, 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 5104584 8237244 8369335 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that scaling an image works properly when the + * source parameters are outside the source bounds. + * @run main/othervm -Dsun.java2d.opengl=True ScaleParamsOOB + * @run main/othervm ScaleParamsOOB + */ + +/* + * @test + * @bug 5104584 8237244 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that scaling an image works properly when the + * source parameters are outside the source bounds. + * @run main/othervm -Dsun.java2d.opengl=True ScaleParamsOOB + * @run main/othervm ScaleParamsOOB + */ + + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class ScaleParamsOOB extends Panel { + + private static final int TOLERANCE = 12; + + private static volatile ScaleParamsOOB test; + private static volatile Frame frame; + + private BufferedImage img; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + g2d.setColor(Color.black); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + BufferedImage img = getGraphicsConfiguration().createCompatibleImage(40, 40); + Graphics2D gimg = img.createGraphics(); + gimg.setColor(Color.red); + gimg.fillRect(0, 0, 40, 40); + gimg.dispose(); + + // first time will be a sw->surface blit + g2d.drawImage(img, + 10, 10, 90, 90, + -60, -60, 100, 100, + null); + + // second time will be a texture->surface blit + g2d.drawImage(img, + 110, 10, 190, 90, + -60, -60, 100, 100, + null); + } + + public Dimension getPreferredSize() { + return new Dimension(300, 200); + } + + private static void testRegion(BufferedImage bi, + Rectangle wholeRegion, + Rectangle affectedRegion) + { + int x1 = wholeRegion.x; + int y1 = wholeRegion.y; + int x2 = x1 + wholeRegion.width; + int y2 = y1 + wholeRegion.height; + + int ax1 = affectedRegion.x; + int ay1 = affectedRegion.y; + int ax2 = ax1 + affectedRegion.width; + int ay2 = ay1 + affectedRegion.height; + + for (int y = y1; y < y2; y++) { + for (int x = x1; x < x2; x++) { + int actual = bi.getRGB(x, y); + int expected = 0; + if (affectedRegion.contains(x, y)) { + expected = Color.red.getRGB(); + } else { + expected = Color.black.getRGB(); + } + int alpha = (actual >> 24) & 0xFF; + int red = (actual >> 16) & 0xFF; + int green = (actual >> 8) & 0xFF; + int blue = (actual) & 0xFF; + + int standardAlpha = (expected >> 24) & 0xFF; + int standardRed = (expected >> 16) & 0xFF; + int standardGreen = (expected >> 8) & 0xFF; + int standardBlue = (expected) & 0xFF; + + if ((Math.abs(alpha - standardAlpha) > TOLERANCE) || + (Math.abs(red - standardRed) > TOLERANCE) || + (Math.abs(green - standardGreen) > TOLERANCE) || + (Math.abs(blue - standardBlue) > TOLERANCE)) { + + String msg = ("Test failed at x="+x+" y="+y+ + " (expected="+ + Integer.toHexString(expected) + + " actual="+ + Integer.toHexString(actual) + + ")"); + // log edge pixel differences, but don't fail the test. + if ((x == ax1) || (x == ax2) || (y == ay1) || (y == ay2)) { + System.err.println(msg); + } else { + saveImage(bi); + throw new RuntimeException(msg); + } + } + } + } + } + + private static void createAndShowGUI() { + test = new ScaleParamsOOB(); + frame = new Frame("OpenGL ScaleParamsOOB Test"); + frame.setAlwaysOnTop(true); + frame.add(test); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + + EventQueue.invokeAndWait(() -> createAndShowGUI()); + + robot.waitForIdle(); + robot.delay(2000); + + // Grab the screen region + BufferedImage capture = null; + try { + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, 200, 200); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test background color + int pixel = capture.getRGB(5, 5); + if (pixel != 0xff000000) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "background: " + Integer.toHexString(pixel)); + } + + // Test pixels + testRegion(capture, + new Rectangle(5, 5, 90, 90), + new Rectangle(40, 40, 20, 20)); + testRegion(capture, + new Rectangle(105, 5, 90, 90), + new Rectangle(140, 40, 20, 20)); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/ShapeClip.java b/test/jdk/sun/java2d/OpenGL/ShapeClip.java new file mode 100644 index 000000000000..f50b7aff5a64 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/ShapeClip.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2004, 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 5002133 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that the OpenGL pipeline does not affect the color + * buffer when setting up a complex (shape) clip region. The test fails if + * the circular clip region is filled with a green color (the green region + * should not be visible at all). + * @run main/othervm -Dsun.java2d.opengl=True ShapeClip + * @run main/othervm ShapeClip + */ + +/* + * @test + * @bug 5002133 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that the OpenGL pipeline does not affect the color + * buffer when setting up a complex (shape) clip region. The test fails if + * the circular clip region is filled with a green color (the green region + * should not be visible at all). + * @run main/othervm -Dsun.java2d.opengl=True ShapeClip + * @run main/othervm ShapeClip + */ + +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.geom.Ellipse2D; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class ShapeClip extends Panel { + + private static volatile Frame frame; + private static volatile ShapeClip test; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + + int width = getWidth(); + int height = getHeight(); + + g2d.setColor(Color.black); + g2d.fillRect(0, 0, width, height); + + g2d.setColor(Color.green); + g2d.fillRect(0, 0, 1, 1); + g2d.setClip(new Ellipse2D.Double(10, 10, 100, 100)); + g2d.setColor(Color.blue); + g2d.fillRect(30, 30, 20, 20); + } + + static void createUI() { + test = new ShapeClip(); + frame = new Frame("OpenGL ShapeClip Test"); + frame.add(test); + frame.setSize(200, 200); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + + EventQueue.invokeAndWait(ShapeClip::createUI); + + robot.waitForIdle(); + robot.delay(2000); + + // Grab the screen region + BufferedImage capture = null; + try { + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, 80, 80); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test blue rectangle + int pixel1 = capture.getRGB(40, 40); + if (pixel1 != 0xff0000ff) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "rectangle " + Integer.toHexString(pixel1)); + } + + // Test clip region (should be same color as background) + int pixel2 = capture.getRGB(60, 40); + if (pixel2 != 0xff000000) { + saveImage(capture); + throw new RuntimeException("Failed: Incorrect color for " + + "clip region " + Integer.toHexString(pixel2)); + } + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/SrcMaskOps.java b/test/jdk/sun/java2d/OpenGL/SrcMaskOps.java new file mode 100644 index 000000000000..9908cffdefb0 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/SrcMaskOps.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2004, 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 4942939 4970674 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that OGLMaskFill, OGLMaskBlit, and OGLTextRenderer + * operations work properly for non-SrcOver composites. + * @run main/othervm -Dsun.java2d.opengl=True SrcMaskOps + * @run main/othervm SrcMaskOps + */ + +/* + * @test + * @bug 4942939 4970674 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that OGLMaskFill, OGLMaskBlit, and OGLTextRenderer + * operations work properly for non-SrcOver composites. + * @run main/othervm -Dsun.java2d.opengl=True SrcMaskOps + * @run main/othervm SrcMaskOps + */ + +import java.awt.AlphaComposite; +import java.awt.Color; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GradientPaint; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.RenderingHints; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class SrcMaskOps extends Panel { + + static volatile Frame frame; + static volatile SrcMaskOps test; + + static final int SRX = 50; + static final int SRY = 50; + static final int GPX = 90; + static final int GPY = 50; + static final int DTX = 120; + static final int DTY = 70; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + + g2d.setColor(Color.white); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g2d.setComposite(AlphaComposite.Src); + + g2d.setColor(Color.blue); + g2d.drawRect(SRX, SRY, 20, 20); + + g2d.setPaint(new GradientPaint(0.0f, 0.0f, Color.red, + 100.0f, 100.f, Color.red, true)); + g2d.drawRect(GPX, GPY, 20, 20); + + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_OFF); + + g2d.setColor(Color.red); + Font font = new Font(Font.DIALOG, Font.PLAIN, 20); + g2d.setFont(font); + g2d.drawString("HELLO", DTX, DTY); + } + + static void createUI() { + frame = new Frame("OpenGL SrcMaskOps Test"); + test = new SrcMaskOps(); + frame.add(test); + frame.setSize(300, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + + Robot robot = new Robot(); + BufferedImage capture = null; + try { + EventQueue.invokeAndWait(SrcMaskOps::createUI); + robot.waitForIdle(); + robot.delay(3000); + + // Grab the screen region + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, 300, 300); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test solid rectangle + int pixel1, pixel2; + pixel1 = capture.getRGB(SRX, SRY); + pixel2 = capture.getRGB(SRX+2, SRY+2); + if (!similar(pixel1, 0xff0000ff) || !similar(pixel2, 0xffffffff)) { + saveImage(capture); + throw new RuntimeException(getMsg("solid rectangle", pixel1, pixel2)); + } + + // Test GradientPaint rectangle + pixel1 = capture.getRGB(GPX, GPY); + pixel2 = capture.getRGB(GPX+2, GPY+2); + if (!similar(pixel1, 0xffff0000) || !similar(pixel2, 0xffffffff)) { + saveImage(capture); + throw new RuntimeException(getMsg("GradientPaint rectangle", pixel1, pixel2)); + } + + // Test solid text + pixel1 = capture.getRGB(DTX+2, DTY-5); + pixel2 = capture.getRGB(DTX+5, DTY-5); + if (!similar(pixel1, 0xffff0000) || !similar(pixel2, 0xffffffff)) { + saveImage(capture); + throw new RuntimeException(getMsg("solid text", pixel1, pixel2)); + } + + } + + static boolean similar(int p1, int p2) { + int a1 = (p1 >> 24) & 0xff; + int r1 = (p1 >> 16) & 0xff; + int g1 = (p1 >> 8) & 0xff; + int b1 = p1 & 0xff; + int a2 = (p2 >> 24) & 0xff; + int r2 = (p2 >> 16) & 0xff; + int g2 = (p2 >> 8) & 0xff; + int b2 = p2 & 0xff; + + int allowedDiff = 0x10; + return + (Math.abs(a1 - a2) <= allowedDiff) && + (Math.abs(r1 - r2) <= allowedDiff) && + (Math.abs(g1 - g2) <= allowedDiff) && + (Math.abs(b1 - b2) <= allowedDiff); + } + + static String getMsg(String r, int p1, int p2) { + return "Failed: Incorrect color[s] for " + r + " got " + + Integer.toHexString(p1) + " and " + Integer.toHexString(p2); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/OpenGL/VolatileSubRegion.java b/test/jdk/sun/java2d/OpenGL/VolatileSubRegion.java new file mode 100644 index 000000000000..7ec350bc9587 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/VolatileSubRegion.java @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2004, 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 6244071 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that copying a subregion from a VolatileImage works + * properly with the OGL pipeline. + * @run main/othervm VolatileSubRegion + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=true VolatileSubRegion + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=false VolatileSubRegion + */ + +/* + * @test + * @bug 6244071 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that copying a subregion from a VolatileImage works + * properly with the OGL pipeline. + * @run main/othervm VolatileSubRegion + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=true VolatileSubRegion + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=false VolatileSubRegion + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.awt.image.IndexColorModel; +import java.awt.image.VolatileImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class VolatileSubRegion extends Panel { + + private VolatileImage img; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + + if (img == null) { + img = createVolatileImage(200, 200); + Graphics2D goff = img.createGraphics(); + goff.setColor(Color.green); + goff.fillRect(50, 0, 100, 50); + goff.setColor(Color.blue); + goff.fillRect(0, 0, 200, 200); + goff.setColor(Color.red); + goff.fillRect(50, 50, 100, 100); + goff.setColor(Color.yellow); + goff.fillRect(50, 150, 100, 50); + goff.dispose(); + } + + g2d.setColor(Color.white); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + g2d.drawImage(img, + 50, 50, 200, 200, + 50, 50, 200, 200, + null); + + } + + + private static volatile VolatileSubRegion test; + private static volatile Frame frame; + + static void createUI() { + test = new VolatileSubRegion(); + frame = new Frame("OpenGL VolatileSubRegion Test"); + frame.add(test); + frame.setSize(300, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + Robot robot = new Robot(); + + EventQueue.invokeAndWait(VolatileSubRegion::createUI); + + robot.waitForIdle(); + robot.delay(2000); + + BufferedImage capture = null; + try { + GraphicsConfiguration gc = frame.getGraphicsConfiguration(); + if (gc.getColorModel() instanceof IndexColorModel) { + System.out.println("IndexColorModel detected: " + + "test considered PASSED"); + return; + } + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, 200, 200); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test pixels + int pixel1 = capture.getRGB(49, 50); + if (pixel1 != 0xffffffff) { + saveImage(capture); + throw new RuntimeException(getMsg("background pixel", pixel1)); + } + int pixel2 = capture.getRGB(50, 50); + if (pixel2 != 0xffff0000) { + saveImage(capture); + throw new RuntimeException(getMsg("red region", pixel2)); + } + int pixel3 = capture.getRGB(50, 150); + if (pixel3 != 0xffffff00) { + saveImage(capture); + throw new RuntimeException(getMsg("yellow region", pixel3)); + } + } + + static String getMsg(String r, int p1) { + return "Failed: Incorrect color for " + r + " : got " + Integer.toHexString(p1); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/test/jdk/sun/java2d/OpenGL/XformVolatile.java b/test/jdk/sun/java2d/OpenGL/XformVolatile.java new file mode 100644 index 000000000000..44e7c7ee8ba7 --- /dev/null +++ b/test/jdk/sun/java2d/OpenGL/XformVolatile.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2004, 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 4970836 + * @key headful + * @requires (os.family != "mac") + * @summary Verifies that transformed VolatileImage copies work properly with + * the OGL pipeline. + * @run main/othervm XformVolatile + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=true XformVolatile + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=false XformVolatile + */ + +/* + * @test + * @bug 4970836 + * @key headful + * @requires (os.family == "mac") + * @summary Verifies that transformed VolatileImage copies work properly with + * the OGL pipeline. + * @run main/othervm XformVolatile + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=true XformVolatile + * @run main/othervm -Dsun.java2d.opengl=True -Dsun.java2d.opengl.fbobject=false XformVolatile + */ + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Panel; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.image.BufferedImage; +import java.awt.image.VolatileImage; +import java.io.File; +import javax.imageio.ImageIO; + +public class XformVolatile extends Panel { + + private static volatile Frame frame; + private static volatile XformVolatile test; + private volatile VolatileImage img; + + public void paint(Graphics g) { + + Graphics2D g2d = (Graphics2D)g; + + if (img == null) { + img = createVolatileImage(200, 200); + Graphics2D goff = img.createGraphics(); + goff.setColor(Color.blue); + goff.fillRect(0, 0, 200, 200); + goff.setColor(Color.red); + goff.fillPolygon(new int[] {10, 100, 190}, + new int[] {190, 10, 190}, 3); + goff.dispose(); + } + + g2d.setColor(Color.black); + g2d.fillRect(0, 0, getWidth(), getHeight()); + + g2d.rotate(Math.toRadians(3.0)); + g2d.drawImage(img, 0, 0, null); + } + + static void createUI() { + test = new XformVolatile(); + frame = new Frame("OpenGL XformVolatile Test"); + frame.add(test); + frame.setSize(300, 300); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + public static void main(String[] args) throws Exception { + + Robot robot = new Robot(); + + EventQueue.invokeAndWait(XformVolatile::createUI); + + robot.waitForIdle(); + robot.delay(2000); + + // Grab the screen region + BufferedImage capture = null; + try { + Point pt1 = test.getLocationOnScreen(); + Rectangle rect = new Rectangle(pt1.x, pt1.y, 200, 200); + capture = robot.createScreenCapture(rect); + } finally { + if (frame != null) { + EventQueue.invokeAndWait(frame::dispose); + } + } + + // Test inner and outer pixels + int pixel1 = capture.getRGB(5, 175); + if (pixel1 != 0xff0000ff) { + saveImage(capture); + throw new RuntimeException(getMsg("inner", pixel1)); + } + int pixel2 = capture.getRGB(5, 188); + if (pixel2 != 0xffff0000) { + saveImage(capture); + throw new RuntimeException(getMsg("inner", pixel2)); + } + } + + static String getMsg(String r, int p1) { + return "Failed: Incorrect color for " + r + " pixel: got " + Integer.toHexString(p1); + } + + static void saveImage(BufferedImage img) { + try { + File file = new File("capture.png"); + ImageIO.write(img, "png", file); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java b/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java index efa938036706..9b109e954ebc 100644 --- a/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java +++ b/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, 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 @@ -21,10 +21,10 @@ * questions. */ -import java.awt.AWTException; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; +import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics; import java.awt.Point; @@ -42,18 +42,18 @@ * make sure the pixels on the screen are red. * * Note that we force the use of shared memory pixmaps in the shell script. - * - * @author Dmitri.Trembovetski */ public class SharedMemoryPixmapsTest { - static final int IMAGE_SIZE = 100; - static boolean show = false; - final Frame testFrame; - /** Creates a new instance of SharedMemoryPixmapsTest */ - public SharedMemoryPixmapsTest() { + static final int IMAGE_SIZE = 200; + static volatile boolean show = false; + static volatile Frame testFrame; + static volatile TestComponent testComponent; + + static void createUI() { testFrame = new Frame("SharedMemoryPixmapsTest"); - testFrame.add(new TestComponent()); + testComponent = new TestComponent(); + testFrame.add(testComponent); testFrame.setUndecorated(true); testFrame.setResizable(false); testFrame.pack(); @@ -62,7 +62,7 @@ public SharedMemoryPixmapsTest() { testFrame.toFront(); } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { for (String s : args) { if ("-show".equals(s)) { show = true; @@ -70,12 +70,43 @@ public static void main(String[] args) { System.err.println("Usage: SharedMemoryPixmapsTest [-show]"); } } - new SharedMemoryPixmapsTest(); + EventQueue.invokeAndWait(SharedMemoryPixmapsTest::createUI); + if (testRendering()) { + System.err.println("Test Passed"); + } else { + System.err.println("Test Failed"); + } + if (!show && testFrame != null) { + EventQueue.invokeAndWait(testFrame::dispose); + } + } + + static boolean testRendering() throws Exception { + Robot r = new Robot(); + r.waitForIdle(); + r.delay(2000); + Point p = testComponent.getLocationOnScreen(); + BufferedImage b = + r.createScreenCapture(new Rectangle(p, testComponent.getPreferredSize())); + for (int y = 20; y < b.getHeight() - 40; y++) { + for (int x = 20; x < b.getWidth() - 40; x++) { + if (b.getRGB(x, y) != Color.red.getRGB()) { + System.err.println("Incorrect pixel at " + + x + "x" + y + " : " + + Integer.toHexString(b.getRGB(x, y))); + if (show) { + return false; + } + System.err.println("Test Failed"); + System.exit(1); + } + } + } + return true; } - private class TestComponent extends Component { + static class TestComponent extends Component { VolatileImage vi = null; - boolean tested = false; void initVI() { int res; @@ -104,54 +135,10 @@ public synchronized void paint(Graphics g) { g.setColor(Color.green); g.fillRect(0, 0, getWidth(), getHeight()); + vi = null; initVI(); g.drawImage(vi, 0, 0, null); } while (vi.contentsLost()); - - Toolkit.getDefaultToolkit().sync(); - if (!tested) { - if (testRendering()) { - System.err.println("Test Passed"); - } else { - System.err.println("Test Failed"); - } - tested = true; - } - if (!show) { - testFrame.setVisible(false); - testFrame.dispose(); - } - } - - private boolean testRendering() throws RuntimeException { - try { - Thread.sleep(2000); - } catch (InterruptedException ex) {} - Robot r = null; - try { - r = new Robot(); - } catch (AWTException ex) { - ex.printStackTrace(); - throw new RuntimeException("Can't create Robot"); - } - Point p = getLocationOnScreen(); - BufferedImage b = - r.createScreenCapture(new Rectangle(p, getPreferredSize())); - for (int y = 0; y < b.getHeight(); y++) { - for (int x = 0; x < b.getWidth(); x++) { - if (b.getRGB(x, y) != Color.red.getRGB()) { - System.err.println("Incorrect pixel" + " at " - + x + "x" + y + " : " + - Integer.toHexString(b.getRGB(x, y))); - if (show) { - return false; - } - System.err.println("Test Failed"); - System.exit(1); - } - } - } - return true; } @Override @@ -159,5 +146,4 @@ public Dimension getPreferredSize() { return new Dimension(IMAGE_SIZE, IMAGE_SIZE); } } - } diff --git a/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh b/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh index 10dd58d90de8..786957ca0ebc 100644 --- a/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh +++ b/test/jdk/sun/java2d/X11SurfaceData/SharedMemoryPixmapsTest/SharedMemoryPixmapsTest.sh @@ -1,6 +1,6 @@ #!/bin/sh # -# Copyright (c) 2005, 2008, 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 @@ -29,7 +29,6 @@ # by filling a VolatileImage with red color and copying it # to the screen. # Note that we force the use of shared memory pixmaps. -# @author Dmitri.Trembovetski echo "TESTJAVA=${TESTJAVA}" echo "TESTSRC=${TESTSRC}" diff --git a/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/GetServerCertificates.java b/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/GetServerCertificates.java new file mode 100644 index 000000000000..135c2375f222 --- /dev/null +++ b/test/jdk/sun/net/www/protocol/https/HttpsURLConnection/GetServerCertificates.java @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * 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 8376031 + * @modules jdk.httpserver + * @library /test/lib + * @summary Ensure HttpsURLConnection::getServerCertificates does not + * throw after calling getResponseCode() if the response doesn't have + * a body. + * @run main/othervm ${test.main.class} + * @run main/othervm -Djava.net.preferIPv6Addresses=true ${test.main.class} + */ + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; + +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import jdk.test.lib.net.SimpleSSLContext; +import jdk.test.lib.net.URIBuilder; + +// Use of the static import (RSPBODY_EMPTY) depends on JDK-8331195, +// which requires a CSR approval before backporting. +// import static com.sun.net.httpserver.HttpExchange.RSPBODY_EMPTY; + + +public class GetServerCertificates { + + static final String URI_PATH = "/GetServerCertificates/"; + static final String BODY = "Go raibh maith agat"; + // Using constant (RSPBODY_EMPTY) instead of a static import that depends + // on JDK-8331195, which requires a CSR approval before backporting. + static final long RSPBODY_EMPTY = -1l; + enum TESTS { + HEAD("head", 200, "HEAD"), + NOBODY("nobody", 200, "GET", "POST"), + S204("204", 204, "GET", "POST"), + S304("304", 304, "GET", "POST"), + S200("200", 200, "GET", "POST"); + final String test; + final int code; + final List methods; + private TESTS(String test, int code, String... methods) { + this.test = test; + this.code = code; + this.methods = List.of(methods); + } + boolean isFor(String path) { + return path != null && path.endsWith("/" + test); + } + + String test() { return test; } + int code() { return code; } + List methods() { return methods; } + static Optional fromPath(String path) { + return Stream.of(values()) + .filter(test -> test.isFor(path)) + .findFirst(); + } + } + + void test(String[] args) throws Exception { + SSLContext.setDefault(SimpleSSLContext.findSSLContext()); + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); + HttpServer server = startHttpServer(); + try { + InetSocketAddress address = server.getAddress(); + URI uri = URIBuilder.newBuilder() + .scheme("https") + .host(address.getAddress()) + .port(address.getPort()) + .path(URI_PATH) + .build(); + for (var test : TESTS.values()) { + for (String method : test.methods()) { + doClient(method, uri, test); + } + } + + } finally { + server.stop(1000); + } + } + + void doClient(String method, URI baseUri, TESTS test) throws Exception { + assert baseUri.getRawQuery() == null; + assert baseUri.getRawFragment() == null; + assert test.methods().contains(method); + + String uriStr = baseUri.toString(); + if (!uriStr.endsWith("/")) uriStr = uriStr + "/"; + + URI uri = new URI(uriStr + test.test()); + assert uri.toString().endsWith("/" + test.test()); + int code = test.code(); + System.out.println("doClient(%s, %s, %s)" + .formatted(method, test.test(), test.code)); + + // first request - should create a TCP connection + HttpsURLConnection uc = (HttpsURLConnection) + uri.toURL().openConnection(Proxy.NO_PROXY); + if (!"GET".equals(method)) { + uc.setRequestMethod(method); + } + try { + uc.getServerCertificates(); + throw new AssertionError("Expected IllegalStateException not thrown"); + } catch (IllegalStateException ise) { + System.out.println("Got expected ISE: " + ise); + } + int resp = uc.getResponseCode(); + check(resp == code, "Unexpected response code. Expected %s, got %s" + .formatted(code, resp)); + + check(uc.getServerCertificates()); + if (test == TESTS.S200) { + byte[] bytes = uc.getInputStream().readAllBytes(); + String body = new String(bytes, StandardCharsets.UTF_8); + System.out.println("body: " + body); + check(BODY.equals(body), "Unexpected response body. Expected \"%s\", got \"%s\"" + .formatted(BODY, body)); + } + + // second request - should go on the same TCP connection. + // We don't have a reliable way to test that, and it could + // go on a new TCP connection if the previous connection + // was already closed. It is not an issue either way. + uc = (HttpsURLConnection) + uri.toURL().openConnection(Proxy.NO_PROXY); + if (!"GET".equals(method)) { + uc.setRequestMethod(method); + } + try { + uc.getServerCertificates(); + throw new AssertionError("Expected IllegalStateException not thrown"); + } catch (IllegalStateException ise) { + System.out.println("Got expected ISE: " + ise); + } + resp = uc.getResponseCode(); + check(resp == code, "Unexpected response code. Expected %s, got %s" + .formatted(code, resp)); + + check(uc.getServerCertificates()); + if (test == TESTS.S200) { + byte[] bytes = uc.getInputStream().readAllBytes(); + String body = new String(bytes, StandardCharsets.UTF_8); + System.out.println("body: " + body); + check(BODY.equals(body), "Unexpected response body. Expected \"%s\", got \"%s\"" + .formatted(BODY, body)); + } + + uc.disconnect(); + try { + uc.getServerCertificates(); + throw new AssertionError("Expected IllegalStateException not thrown"); + } catch (IllegalStateException ise) { + System.out.println("Got expected ISE: " + ise); + } + + // third request - forces the connection to close + // after use so that we don't find any connection in the pool + // for the next test case, assuming there was only + // one connection in the first place. + // Again there's no easy way to verify that the pool + // is empty (and it's not really necessary to bother) + uc = (HttpsURLConnection) + uri.toURL().openConnection(Proxy.NO_PROXY); + if (!"GET".equals(method)) { + uc.setRequestMethod(method); + } + uc.setRequestProperty("Connection", "close"); + try { + uc.getServerCertificates(); + throw new AssertionError("Expected IllegalStateException not thrown"); + } catch (IllegalStateException ise) { + System.out.println("Got expected ISE: " + ise); + } + resp = uc.getResponseCode(); + check(resp == code, "Unexpected response code. Expected %s, got %s" + .formatted(code, resp)); + check(uc.getServerCertificates()); + uc.disconnect(); + try { + uc.getServerCertificates(); + throw new AssertionError("Expected IllegalStateException not thrown"); + } catch (IllegalStateException ise) { + System.out.println("Got expected ISE: " + ise); + } + } + + // HTTP Server + HttpServer startHttpServer() throws IOException { + InetAddress localhost = InetAddress.getLoopbackAddress(); + HttpsServer httpServer = HttpsServer + .create(new InetSocketAddress(localhost, 0), 0); + var configurator = new HttpsConfigurator(SimpleSSLContext.findSSLContext()); + httpServer.setHttpsConfigurator(configurator); + httpServer.createContext(URI_PATH, new SimpleHandler()); + httpServer.start(); + return httpServer; + } + + static class SimpleHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + try { + String path = t.getRequestURI().getRawPath(); + var test = TESTS.fromPath(path); + if (!path.startsWith(URI_PATH) || !test.isPresent()) { + t.getRequestBody().close(); + t.getResponseHeaders().add("Connection", "close"); + t.sendResponseHeaders(421, RSPBODY_EMPTY); + t.close(); + return; + } + try (var is = t.getRequestBody()) { + is.readAllBytes(); + } + switch (test.get()) { + case S204, S304, NOBODY -> + t.sendResponseHeaders(test.get().code(), RSPBODY_EMPTY); + case S200 -> { + byte[] bytes = BODY.getBytes(StandardCharsets.UTF_8); + t.sendResponseHeaders(test.get().code(), bytes.length); + try (var os = t.getResponseBody()) { + os.write(bytes); + } + } + case HEAD -> { + assert t.getRequestMethod().equals("HEAD"); + byte[] bytes = BODY.getBytes(StandardCharsets.UTF_8); + t.sendResponseHeaders(test.get().code(), bytes.length); + } + } + t.close(); + } catch (Throwable error) { + error.printStackTrace(); + throw error; + } + } + } + + volatile int passed = 0, failed = 0; + boolean debug = false; + void pass() {passed++;} + void fail() {failed++;} + void fail(String msg) {System.err.println(msg); fail();} + void unexpected(Throwable t) {failed++; t.printStackTrace();} + void debug(String message) { if (debug) System.out.println(message); } + void check(boolean cond, String failMessage) {if (cond) pass(); else fail(failMessage);} + void check(java.security.cert.Certificate[] certs) { + // Use List.of to check that certs is not null and does not + // contain null. NullPointerException will be thrown here + // if that happens, which will make the test fail. + check(!List.of(certs).isEmpty(), "no certificates returned"); + } + public static void main(String[] args) throws Throwable { + Class k = new Object(){}.getClass().getEnclosingClass(); + try {k.getMethod("instanceMain",String[].class) + .invoke( k.newInstance(), (Object) args);} + catch (Throwable e) {throw e.getCause();}} + public void instanceMain(String[] args) throws Throwable { + try {test(args);} catch (Throwable t) {unexpected(t);} + System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); + if (failed > 0) throw new AssertionError("Some tests failed");} +} diff --git a/test/jdk/sun/security/krb5/auto/UserIterCount.java b/test/jdk/sun/security/krb5/auto/UserIterCount.java index a90da012a061..f972e20ee1e1 100644 --- a/test/jdk/sun/security/krb5/auto/UserIterCount.java +++ b/test/jdk/sun/security/krb5/auto/UserIterCount.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * 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,11 +30,19 @@ * @run main jdk.test.lib.FileInstaller TestHosts TestHosts * @run main/othervm -Djdk.net.hosts.file=TestHosts UserIterCount */ + +import java.util.HashMap; + +import sun.security.krb5.EncryptionKey; +import sun.security.krb5.KrbException; import sun.security.krb5.PrincipalName; public class UserIterCount { static class MyKDC extends OneKDC { + static final HashMap CACHE + = new HashMap<>(); + public MyKDC() throws Exception { super(null); } @@ -51,6 +59,18 @@ protected byte[] getParams(PrincipalName p, int etype) { return super.getParams(p, etype); } } + + @Override + EncryptionKey keyForUser(PrincipalName p, int etype, boolean server) + throws KrbException { + var key = p.toString() + etype + server; + var v = CACHE.get(key); + if (v == null) { + v = super.keyForUser(p, etype, server); + CACHE.put(key, v); + } + return v; + } } public static void main(String[] args) throws Exception { diff --git a/test/jdk/sun/security/krb5/config/native/TestDynamicStore.java b/test/jdk/sun/security/krb5/config/native/TestDynamicStore.java index 7e396013a71e..a1281995c46e 100644 --- a/test/jdk/sun/security/krb5/config/native/TestDynamicStore.java +++ b/test/jdk/sun/security/krb5/config/native/TestDynamicStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -34,6 +34,8 @@ import jdk.test.lib.Asserts; import sun.security.krb5.Config; +import javax.swing.JOptionPane; + // =================== Attention =================== // This test calls a native method implemented in libTestDynamicStore.m // to modify system-level Kerberos 5 settings stored in the dynamic store. @@ -56,6 +58,17 @@ static int action(char what, char whom) throws Exception { public static void main(String[] args) throws Exception { + // Show a popup to remind to run this test as sudo user + // this will only trigger if sudo (root) user is not detected + if (!"root".equals(System.getProperty("user.name"))) { + + JOptionPane.showMessageDialog(null, """ + This test MUST be run as ROOT.\s + Please close and RESTART the test."""); + + Asserts.assertFalse(true, "This test must be run as ROOT"); + } + System.loadLibrary("TestDynamicStore"); Config cfg = Config.getInstance(); diff --git a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/NISTWrapKAT.java b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/NISTWrapKAT.java index e1f32ea80765..b570a0dd0301 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/NISTWrapKAT.java +++ b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/NISTWrapKAT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -29,13 +29,19 @@ * @summary Verify that the AES-Key-Wrap and AES-Key-Wrap-Pad ciphers * work as expected using NIST test vectors. */ +import jtreg.SkippedException; + import java.security.Key; import java.security.AlgorithmParameters; import java.security.Provider; -import javax.crypto.*; -import javax.crypto.spec.*; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.util.ArrayList; import java.util.Arrays; import java.math.BigInteger; +import java.util.List; // adapted from com/sun/crypto/provider/Cipher/KeyWrap/NISTWrapKAT.java public class NISTWrapKAT extends PKCS11Test { @@ -73,8 +79,11 @@ public class NISTWrapKAT extends PKCS11Test { "308D49692B5F8CF638D54BB4B985633504237329964C76EBB3F669870A708DBC"; private static String KWP_AES256_224 = "0942747DB07032A3F04CDB2E7DE1CBA038F92BC355393AE9A0E4AE8C901912AC3D3AF0F16D240607"; - // from RFC 5649 sec6 - private static String KEK2 = "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8"; + // from RFC 5649 sec6 + private static String KEK2 = + "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8"; + + private static final List skippedAlgoList = new ArrayList <>(); private static byte[] toBytes(String hex, int hexLen) { if (hexLen < hex.length()) { @@ -91,10 +100,18 @@ private static byte[] toBytes(String hex, int hexLen) { byte[] out = new byte[outLen]; if (val.length < outLen) { // enlarge - System.arraycopy(val, 0, out, outLen - val.length, val.length); + System.arraycopy(val, + 0, + out, + outLen - val.length, + val.length); } else { // truncate - System.arraycopy(val, val.length - outLen, out, 0, outLen); + System.arraycopy(val, + val.length - outLen, + out, + 0, + outLen); } return out; } @@ -143,7 +160,8 @@ public Object[][] testData() { "AFBEB0F07DFBF5419200F2CCB50BB24F" }, { "AES/KWP/NoPadding", KEK2, 24, "C37B7E6492584340BED12207808941155068F738", 20, - "138BDEAA9B8FA7FC61F97742E72248EE5AE6AE5360D1AE6A5F54F373FA543B6A" }, + "138BDEAA9B8FA7FC61F97742E72248EE5AE6AE5360D1AE6A5F54F373FA543B6A" + }, // some more test vectors for KW and KWP // from csrc.nist.gov/groups/STM/cavp/documents/mac/kwtestvectors.zip { "AES/KW/NoPadding", "7575da3a93607cc2bfd8cec7aadfd9a6", 16, @@ -256,7 +274,10 @@ public void testKeyWrap(String algo, String key, int keyLen, dataLen + "-byte key with " + 8*keyLen + "-bit KEK"); int allowed = Cipher.getMaxAllowedKeyLength("AES"); if (keyLen > allowed) { - System.out.println("=> skip, exceeds max allowed size " + allowed); + System.err.println("Skip, exceeds max allowed size " + allowed); + skippedAlgoList.add(algo + " Cipher with wrapping " + + dataLen + "-byte key with " + 8 * keyLen + + "-bit KEK exceeds max allowed size " + allowed); return; } Cipher c1 = Cipher.getInstance(algo, @@ -275,7 +296,8 @@ public void testKeyWrap(String algo, String key, int keyLen, c1.init(Cipher.WRAP_MODE, cipherKey); IvParameterSpec ivSpec = new IvParameterSpec(c1.getIV()); c2.init(Cipher.WRAP_MODE, cipherKey, ivSpec); - AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); + AlgorithmParameters params = + AlgorithmParameters.getInstance("AES"); params.init(ivSpec); c3.init(Cipher.WRAP_MODE, cipherKey, params); @@ -300,9 +322,12 @@ public void testKeyWrap(String algo, String key, int keyLen, params.init(ivSpec); c3.init(Cipher.UNWRAP_MODE, cipherKey, params); - Key unwrapped = c1.unwrap(wrapped, "AES", Cipher.SECRET_KEY); - Key unwrapped2 = c2.unwrap(wrapped, "AES", Cipher.SECRET_KEY); - Key unwrapped3 = c3.unwrap(wrapped, "AES", Cipher.SECRET_KEY); + Key unwrapped = + c1.unwrap(wrapped, "AES", Cipher.SECRET_KEY); + Key unwrapped2 = + c2.unwrap(wrapped, "AES", Cipher.SECRET_KEY); + Key unwrapped3 = + c3.unwrap(wrapped, "AES", Cipher.SECRET_KEY); if (!Arrays.equals(unwrapped.getEncoded(), dataVal) || !Arrays.equals(unwrapped2.getEncoded(), dataVal) || @@ -319,7 +344,10 @@ public void testEnc(String algo, String key, int keyLen, String data, dataLen + "-byte data with " + 8*keyLen + "-bit KEK"); int allowed = Cipher.getMaxAllowedKeyLength("AES"); if (keyLen > allowed) { - System.out.println("=> skip, exceeds max allowed size " + allowed); + System.err.println("Skip, exceeds max allowed size " + allowed); + skippedAlgoList.add(algo + " Cipher with enc " + + dataLen + "-byte data with " + 8 * keyLen + + "-bit KEK exceeds max allowed size " + allowed); return; } Cipher c1 = Cipher.getInstance(algo, @@ -336,7 +364,8 @@ public void testEnc(String algo, String key, int keyLen, String data, c1.init(Cipher.ENCRYPT_MODE, cipherKey); IvParameterSpec ivSpec = new IvParameterSpec(c1.getIV()); c2.init(Cipher.ENCRYPT_MODE, cipherKey, ivSpec); - AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); + AlgorithmParameters params = + AlgorithmParameters.getInstance("AES"); params.init(ivSpec); c3.init(Cipher.ENCRYPT_MODE, cipherKey, params); @@ -384,18 +413,24 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { Object[][] testDatum = testData(); - for (int i = 0; i < testDatum.length; i++) { - Object[] td = testDatum[i]; + for (Object[] td : testDatum) { String algo = (String) td[0]; if (p.getService("Cipher", algo) == null) { - System.out.println("Skip, due to no support: " + algo); + System.err.println("Skip, due to no support: " + algo); + skippedAlgoList.add("No support for " + algo); continue; } - testKeyWrap(algo, (String)td[1], (int)td[2], (String)td[3], - (int)td[4], (String)td[5], p); - testEnc(algo, (String)td[1], (int)td[2], (String)td[3], - (int)td[4], (String)td[5], p); + testKeyWrap(algo, (String) td[1], (int) td[2], (String) td[3], + (int) td[4], (String) td[5], p); + testEnc(algo, (String) td[1], (int) td[2], (String) td[3], + (int) td[4], (String) td[5], p); + } + + if (!skippedAlgoList.isEmpty()) { + throw new SkippedException("One or more tests skipped " + + skippedAlgoList); + } else { + System.out.println("All Tests Passed"); } - System.out.println("Test Passed"); } } diff --git a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/TestGeneral.java b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/TestGeneral.java index 0cfb4557572c..d7cdfc6c04c5 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/TestGeneral.java +++ b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/TestGeneral.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -29,18 +29,30 @@ * @library /test/lib ../.. * @run main/othervm TestGeneral */ +import jtreg.SkippedException; + import java.nio.ByteBuffer; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.Key; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Provider; +import java.util.ArrayList; import java.util.Arrays; import java.util.HexFormat; -import java.security.*; -import javax.crypto.*; -import javax.crypto.spec.*; +import java.util.List; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; // adapted from com/sun/crypto/provider/Cipher/KeyWrap/TestGeneral.java public class TestGeneral extends PKCS11Test { private static final byte[] DATA_32 = - Arrays.copyOf("1234567890123456789012345678901234".getBytes(), 32); + Arrays.copyOf("1234567890123456789012345678901234".getBytes(), + 32); private static final SecretKey KEY = new SecretKeySpec(DATA_32, 0, 16, "AES"); private static final int KW_IV_LEN = 8; @@ -49,7 +61,8 @@ public class TestGeneral extends PKCS11Test { private static final int MAX_KWP_PAD_LEN = 7; // 0-7 public static void testEnc(Cipher c, byte[] in, int startLen, int inc, - IvParameterSpec[] ivs, int maxPadLen) throws Exception { + IvParameterSpec[] ivs, int maxPadLen) + throws Exception { System.out.println("testEnc, input len=" + startLen + " w/ inc=" + inc); @@ -96,7 +109,7 @@ public static void testEnc(Cipher c, byte[] in, int startLen, int inc, } public static void testKAT(Cipher c, String keyStr, String inStr, - String expectedStr) throws Exception { + String expectedStr) throws Exception { System.out.println("testKAT, input len: " + inStr.length()/2); @@ -245,15 +258,21 @@ public void main(Provider p) throws Exception { SecretKey aes256 = new SecretKeySpec(DATA_32, "AES"); SecretKey any256 = new SecretKeySpec(DATA_32, "ANY"); PrivateKey priv = KeyPairGenerator.getInstance - ("RSA", System.getProperty("test.provider.name","SunRsaSign")) + ("RSA", + System.getProperty( + "test.provider.name", + "SunRsaSign")) .generateKeyPair().getPrivate(); String[] algos = { "AES/KW/PKCS5Padding", "AES/KW/NoPadding", "AES/KWP/NoPadding" }; + + final List skippedList = new ArrayList<>(); + for (String a : algos) { if (p.getService("Cipher", a) == null) { - System.out.println("Skip, due to no support: " + a); + skippedList.add(a); continue; } @@ -329,6 +348,12 @@ public void main(Provider p) throws Exception { testWrap(c, keys, ivs, padLen); testIv(c, ivLen, allowCustomIv); } - System.out.println("All Tests Passed"); + + if (!skippedList.isEmpty()) { + throw new SkippedException("One or more tests skipped " + + "due to no support " + skippedList); + } else { + System.out.println("All Tests Passed"); + } } } diff --git a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/XMLEncKAT.java b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/XMLEncKAT.java index 1857e619cc64..5ba02416c8b2 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/XMLEncKAT.java +++ b/test/jdk/sun/security/pkcs11/Cipher/KeyWrap/XMLEncKAT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -28,14 +28,16 @@ * @library /test/lib ../.. * @run main/othervm XMLEncKAT */ +import jtreg.SkippedException; + import java.util.Base64; import java.security.Key; -import java.security.AlgorithmParameters; import java.security.Provider; -import javax.crypto.*; -import javax.crypto.spec.*; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; -import java.io.IOException; // adapted from com/sun/crypto/provider/Cipher/KeyWrap/XMLEncKAT.java public class XMLEncKAT extends PKCS11Test { @@ -105,7 +107,9 @@ private void testKeyWrap(Provider p, String cAlg, byte[] cKeyVal, // first test UNWRAP with known values for (int i = 0; i < base64Wrapped.length; i++) { byte[] wrappedKey = base64D.decode(base64Wrapped[i]); - key[i] = c.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); + key[i] = c.unwrap(wrappedKey, + "AES", + Cipher.SECRET_KEY); if (c.getIV() != null) { params[i] = new IvParameterSpec(c.getIV()); } @@ -131,8 +135,7 @@ public void main(Provider p) throws Exception { String wrapAlg = "AESWrap"; if (p.getService("Cipher", wrapAlg) == null) { - System.out.println("Skip, due to no support: " + wrapAlg); - return; + throw new SkippedException("No support " + wrapAlg); } String keyAlg = "AES"; diff --git a/test/jdk/sun/security/pkcs11/Cipher/ReinitCipher.java b/test/jdk/sun/security/pkcs11/Cipher/ReinitCipher.java index da547da752b0..78a623cb3738 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/ReinitCipher.java +++ b/test/jdk/sun/security/pkcs11/Cipher/ReinitCipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -33,6 +33,8 @@ * @run main/othervm -Djava.security.manager=allow ReinitCipher sm */ +import jtreg.SkippedException; + import java.security.Provider; import java.util.Random; import javax.crypto.Cipher; @@ -47,8 +49,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { if (p.getService("Cipher", "ARCFOUR") == null) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Algorithm ARCFOUR is not supported by provider, skipping"); } Random random = new Random(); byte[] data1 = new byte[10 * 1024]; diff --git a/test/jdk/sun/security/pkcs11/Cipher/Test4512704.java b/test/jdk/sun/security/pkcs11/Cipher/Test4512704.java index ddca64ecb691..7aafa4fd70f4 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/Test4512704.java +++ b/test/jdk/sun/security/pkcs11/Cipher/Test4512704.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -29,14 +29,16 @@ * @run main Test4512704 * @summary Verify that AES cipher can generate default IV in encrypt mode */ -import java.io.PrintStream; -import java.security.*; -import java.security.spec.*; -import java.util.Random; +import jtreg.SkippedException; -import javax.crypto.*; -import javax.crypto.spec.*; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import java.security.Provider; +import java.security.spec.AlgorithmParameterSpec; public class Test4512704 extends PKCS11Test { @@ -48,9 +50,8 @@ public void test(String mode, Provider p) throws Exception { transformation = "AES/" + mode + "/NoPadding"; c = Cipher.getInstance(transformation, p); } catch (GeneralSecurityException e) { - System.out.println("Skip testing " + p.getName() + - ", no support for " + mode); - return; + throw new SkippedException("Skip testing " + p.getName() + + ", no support for " + mode); } SecretKey key = new SecretKeySpec(new byte[16], "AES"); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCM.java b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCM.java index 06c1e84392c3..f6b6157cefa2 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCM.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -31,13 +31,21 @@ * @key randomness */ -import java.security.*; -import javax.crypto.*; -import javax.crypto.spec.*; -import java.math.*; -import java.io.*; +import jtreg.SkippedException; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import javax.crypto.Cipher; +import javax.crypto.CipherInputStream; +import javax.crypto.CipherOutputStream; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import java.security.GeneralSecurityException; +import java.security.Provider; +import java.util.Arrays; +import java.util.Random; -import java.util.*; public class TestCICOWithGCM extends PKCS11Test { public static void main(String[] args) throws Exception { @@ -55,9 +63,8 @@ public void test(String mode, Provider p) throws Exception { String transformation = "AES/" + mode + "/NoPadding"; c = Cipher.getInstance(transformation, p); } catch (GeneralSecurityException e) { - System.out.println("Skip testing " + p.getName() + - ", no support for " + mode); - return; + throw new SkippedException("Skip testing " + p.getName() + + ", no support for " + mode); } SecretKey key = new SecretKeySpec(new byte[16], "AES"); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCMAndAAD.java b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCMAndAAD.java index be2b1d18c8f0..13ab8541351d 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCMAndAAD.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestCICOWithGCMAndAAD.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 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 @@ -30,6 +30,8 @@ * @summary Test CipherInputStream/OutputStream with AES GCM mode with AAD. * @key randomness */ +import jtreg.SkippedException; + import java.io.*; import java.security.*; import java.util.*; @@ -44,7 +46,6 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { test("GCM", p); -// test("CCM", p); } public void test(String mode, Provider p) throws Exception { @@ -53,9 +54,8 @@ public void test(String mode, Provider p) throws Exception { String transformation = "AES/" + mode + "/NoPadding"; c = Cipher.getInstance(transformation, p); } catch (GeneralSecurityException e) { - System.out.println("Skip testing " + p.getName() + - ", no support for " + mode); - return; + throw new SkippedException("Skip testing " + p.getName() + + ", no support for " + mode); } SecretKey key = new SecretKeySpec(new byte[16], "AES"); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPoly.java b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPoly.java index 26853ae3ee6d..da351bc7493d 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPoly.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPoly.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -47,7 +47,7 @@ import javax.crypto.spec.SecretKeySpec; import javax.crypto.NoSuchPaddingException; -import jdk.test.lib.Utils; +import jtreg.SkippedException; public class TestChaChaPoly extends PKCS11Test { @@ -70,8 +70,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance(ALGO, p); } catch (NoSuchAlgorithmException nsae) { - System.out.println("Skip; no support for " + ALGO); - return; + throw new SkippedException("Skip; no support for " + ALGO); } this.p = p; testTransformations(); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyKAT.java b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyKAT.java index 5649ed013ef5..d2590b2c3cba 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyKAT.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyKAT.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -26,22 +26,25 @@ * @bug 8255410 * @library /test/lib .. * @modules jdk.crypto.cryptoki - * @build jdk.test.lib.Convert * @run main/othervm TestChaChaPolyKAT * @summary ChaCha20-Poly1305 Cipher Implementation (KAT) */ -import java.util.*; +import jtreg.SkippedException; + import java.security.GeneralSecurityException; import java.security.Provider; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; -import javax.crypto.spec.ChaCha20ParameterSpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.AEADBadTagException; import java.nio.ByteBuffer; -import jdk.test.lib.Convert; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; public class TestChaChaPolyKAT extends PKCS11Test { public static class TestData { @@ -126,8 +129,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance(ALGO, p); } catch (NoSuchAlgorithmException nsae) { - System.out.println("Skip; no support for " + ALGO); - return; + throw new SkippedException("Skip; no support for " + ALGO); } int testsPassed = 0; diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyNoReuse.java b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyNoReuse.java index 94272367caa3..60d80b9e3653 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyNoReuse.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyNoReuse.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -30,18 +30,22 @@ * (key/nonce reuse check) */ -import java.util.*; +import jtreg.SkippedException; + import javax.crypto.Cipher; import java.security.spec.AlgorithmParameterSpec; import java.security.Provider; import java.security.NoSuchAlgorithmException; -import javax.crypto.spec.ChaCha20ParameterSpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; -import javax.crypto.AEADBadTagException; import javax.crypto.SecretKey; import java.security.InvalidKeyException; import java.security.InvalidAlgorithmParameterException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; public class TestChaChaPolyNoReuse extends PKCS11Test { @@ -238,8 +242,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance(CIPHER_ALGO, p); } catch (NoSuchAlgorithmException nsae) { - System.out.println("Skip; no support for " + CIPHER_ALGO); - return; + throw new SkippedException("Skip; no support for " + CIPHER_ALGO); } int testsPassed = 0; diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyOutputSize.java b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyOutputSize.java index 57a7b9a46067..f68340658fa3 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyOutputSize.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestChaChaPolyOutputSize.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -30,14 +30,14 @@ * @run main TestChaChaPolyOutputSize */ +import jtreg.SkippedException; + import java.nio.ByteBuffer; import java.security.GeneralSecurityException; -import java.security.Key; import java.security.SecureRandom; import java.security.Provider; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; -import javax.crypto.spec.ChaCha20ParameterSpec; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; @@ -60,8 +60,7 @@ public void main(Provider p) throws GeneralSecurityException { try { Cipher.getInstance(ALGO, p); } catch (NoSuchAlgorithmException nsae) { - System.out.println("Skip; no support for " + ALGO); - return; + throw new SkippedException("Skip; no support for " + ALGO); } testGetOutSize(p); testMultiPartAEADDec(p); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestCipherMode.java b/test/jdk/sun/security/pkcs11/Cipher/TestCipherMode.java index 76f0c9dc4122..cf3d948be17f 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestCipherMode.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestCipherMode.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -30,6 +30,8 @@ * @run main/othervm TestCipherMode */ +import jtreg.SkippedException; + import java.security.Provider; import java.security.Key; import java.security.KeyPair; @@ -38,20 +40,22 @@ import java.security.PublicKey; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class TestCipherMode extends PKCS11Test { - private static String[] TRANSFORMATIONS = { - "AES/ECB/PKCS5Padding", "AES/GCM/NoPadding", - "RSA/ECB/PKCS1Padding" + private static final String[] TRANSFORMATIONS = { + "AES/ECB/PKCS5Padding", "AES/GCM/NoPadding", + "RSA/ECB/PKCS1Padding" }; - private static byte[] BYTES16 = - Arrays.copyOf(TRANSFORMATIONS[0].getBytes(), 16); + private static final byte[] BYTES16 = + Arrays.copyOf("AES/ECB/PKCS5Padding".getBytes(), 16); private static SecretKey AES_KEY = new SecretKeySpec(BYTES16, "AES"); private static PublicKey RSA_PUBKEY = null; private static PrivateKey RSA_PRIVKEY = null; @@ -97,18 +101,29 @@ public void main(Provider p) throws Exception { // test all cipher impls, e.g. P11Cipher, P11AEADCipher, and // P11RSACipher - for (String t : TRANSFORMATIONS) { - checkModes(t, p); + List skipped = new ArrayList<>(); + for (final String t : TRANSFORMATIONS) { + try { + checkModes(t, p); + } catch (SkippedException skippedException) { + // printing to System.out, so it's easier to see which test it relates to + skippedException.printStackTrace(System.out); + skipped.add(t); + } + } + + if (!skipped.isEmpty()) { + throw new SkippedException("Some tests skipped: " + skipped); + } else { + System.out.println("All tests passed"); } - System.out.println("All tests passed"); } private static void checkModes(String t, Provider p) throws Exception { try { Cipher.getInstance(t, p); } catch (Exception e) { - System.out.println("Skip " + t + " due to " + e.getMessage()); - return; + throw new SkippedException("Skip " + t + " due to " + e.getMessage()); } for (CipherMode m : CipherMode.values()) { diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestGCMKeyAndIvCheck.java b/test/jdk/sun/security/pkcs11/Cipher/TestGCMKeyAndIvCheck.java index adabcc571aaa..4e78d8d39d77 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestGCMKeyAndIvCheck.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestGCMKeyAndIvCheck.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2023, 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 @@ -31,13 +31,21 @@ */ -import java.security.*; +import jtreg.SkippedException; + +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Provider; import java.security.spec.AlgorithmParameterSpec; -import javax.crypto.*; -import javax.crypto.spec.*; -import java.math.*; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; -import java.util.*; +import java.util.Arrays; public class TestGCMKeyAndIvCheck extends PKCS11Test { @@ -77,9 +85,8 @@ public void test(String mode, Provider p) throws Exception { String transformation = "AES/" + mode + "/NoPadding"; c = Cipher.getInstance(transformation, p); } catch (GeneralSecurityException e) { - System.out.println("Skip testing " + p.getName() + - ", no support for " + mode); - return; + throw new SkippedException("Skip testing " + p.getName() + + ", no support for " + mode); } System.out.println("Testing against " + p.getName()); SecretKey key = new SecretKeySpec(new byte[16], "AES"); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestKATForGCM.java b/test/jdk/sun/security/pkcs11/Cipher/TestKATForGCM.java index 95e6e5b1a0a8..e5e8284e6f4a 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestKATForGCM.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestKATForGCM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, 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 @@ -30,6 +30,8 @@ * @summary Known Answer Test for AES cipher with GCM mode support in * PKCS11 provider. */ +import jtreg.SkippedException; + import java.security.GeneralSecurityException; import java.security.Provider; import java.util.Arrays; @@ -311,23 +313,27 @@ public void main(Provider p) throws Exception { try { c = Cipher.getInstance(transformation, p); } catch (GeneralSecurityException e) { - System.out.println("Skip testing " + p.getName() + - ", no support for " + transformation); - return; + throw new SkippedException("Skip testing " + p.getName() + + ", no support for " + transformation); } try { if (execute(testValues, c)) { System.out.println("Test Passed!"); } } catch (Exception e) { - System.out.println("Exception occured using " + p.getName() + " version " + p.getVersionStr()); + System.out.println("Exception occured using " + p.getName() + + " version " + p.getVersionStr()); if (isNSS(p)) { - double ver = getNSSInfo("nss"); + Version ver = getNSSInfo("nss"); String osName = System.getProperty("os.name"); - if (ver > 3.139 && ver < 3.15 && osName.equals("Linux")) { + + if (osName.equals("Linux") && + ver.major() == 3 && ver.minor() < 15 + && (ver.minor() > 13 && ver.patch() >= 9)) { // warn about buggy behaviour on Linux with nss 3.14 - System.out.println("Warning: old NSS " + ver + " might be problematic, consider upgrading it"); + System.out.println("Warning: old NSS " + ver + + " might be problematic, consider upgrading it"); } } throw e; diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestRSACipher.java b/test/jdk/sun/security/pkcs11/Cipher/TestRSACipher.java index 6799b19d3e7c..3460eb64e171 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestRSACipher.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestRSACipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -45,6 +45,7 @@ import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import jdk.test.lib.security.SecurityUtils; +import jtreg.SkippedException; public class TestRSACipher extends PKCS11Test { @@ -56,8 +57,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance(RSA_ALGOS[0], p); } catch (GeneralSecurityException e) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Algorithm " + RSA_ALGOS[0] + " is not supported by provider, skipping"); } String kpgAlgorithm = "RSA"; int keySize = SecurityUtils.getTestKeySize(kpgAlgorithm); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestRSACipherWrap.java b/test/jdk/sun/security/pkcs11/Cipher/TestRSACipherWrap.java index 0be916ebf9e7..23568da93e11 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestRSACipherWrap.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestRSACipherWrap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2024, 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 @@ -44,6 +44,7 @@ import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import jdk.test.lib.security.SecurityUtils; +import jtreg.SkippedException; public class TestRSACipherWrap extends PKCS11Test { @@ -55,8 +56,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance(RSA_ALGOS[0], p); } catch (GeneralSecurityException e) { - System.out.println(RSA_ALGOS[0] + " unsupported, skipping"); - return; + throw new SkippedException(RSA_ALGOS[0] + " unsupported, skipping"); } String kpgAlgorithm = "RSA"; KeyPairGenerator kpg = KeyPairGenerator.getInstance(kpgAlgorithm, p); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestRawRSACipher.java b/test/jdk/sun/security/pkcs11/Cipher/TestRawRSACipher.java index fe6433d096e3..dae331bc85f6 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestRawRSACipher.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestRawRSACipher.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2024, 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 @@ -42,6 +42,7 @@ import java.util.Random; import javax.crypto.Cipher; import jdk.test.lib.security.SecurityUtils; +import jtreg.SkippedException; public class TestRawRSACipher extends PKCS11Test { @@ -50,8 +51,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance("RSA/ECB/NoPadding", p); } catch (GeneralSecurityException e) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Algorithm RSA/ECB/NoPadding is not supported by provider, skipping"); } String kpgAlgorithm = "RSA"; diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphers.java b/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphers.java index 5082336d36b8..81862fb05f28 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphers.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphers.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2018, 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 @@ -33,11 +33,15 @@ * @run main/othervm -Djava.security.manager=allow TestSymmCiphers sm */ +import jtreg.SkippedException; + import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.security.AlgorithmParameters; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.ArrayList; +import java.util.List; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; @@ -45,42 +49,32 @@ public class TestSymmCiphers extends PKCS11Test { - private static class CI { // class for holding Cipher Information - - String transformation; - String keyAlgo; - int dataSize; + private record CI (String transformation, String keyAlgo, int dataSize){} // record for holding Cipher Information - CI(String transformation, String keyAlgo, int dataSize) { - this.transformation = transformation; - this.keyAlgo = keyAlgo; - this.dataSize = dataSize; - } - } private static final CI[] TEST_LIST = { - new CI("ARCFOUR", "ARCFOUR", 400), - new CI("RC4", "RC4", 401), - new CI("DES/CBC/NoPadding", "DES", 400), - new CI("DESede/CBC/NoPadding", "DESede", 160), - new CI("AES/CBC/NoPadding", "AES", 4800), - new CI("Blowfish/CBC/NoPadding", "Blowfish", 24), - new CI("DES/cbc/PKCS5Padding", "DES", 6401), - new CI("DESede/CBC/PKCS5Padding", "DESede", 402), - new CI("AES/CBC/PKCS5Padding", "AES", 30), - new CI("Blowfish/CBC/PKCS5Padding", "Blowfish", 19), - new CI("DES/ECB/NoPadding", "DES", 400), - new CI("DESede/ECB/NoPadding", "DESede", 160), - new CI("AES/ECB/NoPadding", "AES", 4800), - new CI("DES/ECB/PKCS5Padding", "DES", 32), - new CI("DES/ECB/PKCS5Padding", "DES", 6400), - new CI("DESede/ECB/PKCS5Padding", "DESede", 400), - new CI("AES/ECB/PKCS5Padding", "AES", 64), - - new CI("DES", "DES", 6400), - new CI("DESede", "DESede", 408), - new CI("AES", "AES", 128), - - new CI("AES/CTR/NoPadding", "AES", 3200) + new CI("ARCFOUR", "ARCFOUR", 400), + new CI("RC4", "RC4", 401), + new CI("DES/CBC/NoPadding", "DES", 400), + new CI("DESede/CBC/NoPadding", "DESede", 160), + new CI("AES/CBC/NoPadding", "AES", 4800), + new CI("Blowfish/CBC/NoPadding", "Blowfish", 24), + new CI("DES/cbc/PKCS5Padding", "DES", 6401), + new CI("DESede/CBC/PKCS5Padding", "DESede", 402), + new CI("AES/CBC/PKCS5Padding", "AES", 30), + new CI("Blowfish/CBC/PKCS5Padding", "Blowfish", 19), + new CI("DES/ECB/NoPadding", "DES", 400), + new CI("DESede/ECB/NoPadding", "DESede", 160), + new CI("AES/ECB/NoPadding", "AES", 4800), + new CI("DES/ECB/PKCS5Padding", "DES", 32), + new CI("DES/ECB/PKCS5Padding", "DES", 6400), + new CI("DESede/ECB/PKCS5Padding", "DESede", 400), + new CI("AES/ECB/PKCS5Padding", "AES", 64), + + new CI("DES", "DES", 6400), + new CI("DESede", "DESede", 408), + new CI("AES", "AES", 128), + + new CI("AES/CTR/NoPadding", "AES", 3200) }; private static StringBuffer debugBuf = new StringBuffer(); @@ -90,11 +84,10 @@ public void main(Provider p) throws Exception { // NSS reports CKR_DEVICE_ERROR when the data passed to // its EncryptUpdate/DecryptUpdate is not multiple of blocks int firstBlkSize = 16; - boolean status = true; + List skippedList = new ArrayList<>(); Random random = new Random(); try { - for (int i = 0; i < TEST_LIST.length; i++) { - CI currTest = TEST_LIST[i]; + for (CI currTest : TEST_LIST) { System.out.println("===" + currTest.transformation + "==="); try { KeyGenerator kg = @@ -123,7 +116,8 @@ public void main(Provider p) throws Exception { System.out.println("Decryption tests: DONE"); } catch (NoSuchAlgorithmException nsae) { System.out.println("Skipping unsupported algorithm: " + - nsae); + nsae); + skippedList.add(currTest); } } } catch (Exception ex) { @@ -134,11 +128,15 @@ public void main(Provider p) throws Exception { } throw ex; } + + if (!skippedList.isEmpty()){ + throw new SkippedException("Some tests skipped: " + skippedList); + } } private static void test(Cipher cipher, int mode, SecretKey key, - AlgorithmParameters params, int firstBlkSize, - byte[] in, byte[] answer) throws Exception { + AlgorithmParameters params, int firstBlkSize, + byte[] in, byte[] answer) throws Exception { // test setup long startTime, endTime; cipher.init(mode, key, params); diff --git a/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java b/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java index ea5181e98dc3..cc27fedf2dab 100644 --- a/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java +++ b/test/jdk/sun/security/pkcs11/Cipher/TestSymmCiphersNoPad.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2018, 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 @@ -33,6 +33,8 @@ * @run main/othervm -Djava.security.manager=allow TestSymmCiphersNoPad sm */ +import jtreg.SkippedException; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -40,6 +42,8 @@ import java.security.AlgorithmParameters; import java.security.NoSuchAlgorithmException; import java.security.Provider; +import java.util.ArrayList; +import java.util.List; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; @@ -48,46 +52,35 @@ public class TestSymmCiphersNoPad extends PKCS11Test { - private static class CI { // class for holding Cipher Information - String transformation; - String keyAlgo; - int dataSize; + private record CI (String transformation, String keyAlgo, int dataSize){} // record for holding Cipher Information - CI(String transformation, String keyAlgo, int dataSize) { - this.transformation = transformation; - this.keyAlgo = keyAlgo; - this.dataSize = dataSize; - } - } + private static StringBuffer debugBuf; - private static final CI TEST_LIST[] = { - new CI("ARCFOUR", "ARCFOUR", 400), - new CI("RC4", "RC4", 401), - new CI("DES/CBC/NoPadding", "DES", 400), - new CI("DESede/CBC/NoPadding", "DESede", 160), - new CI("AES/CBC/NoPadding", "AES", 4800), - new CI("Blowfish/CBC/NoPadding", "Blowfish", 24), - new CI("AES/CTR/NoPadding", "AES", 1600), - new CI("AES/CTR/NoPadding", "AES", 65) + private static final CI[] TEST_LIST = { + new CI("ARCFOUR", "ARCFOUR", 400), + new CI("RC4", "RC4", 401), + new CI("DES/CBC/NoPadding", "DES", 400), + new CI("DESede/CBC/NoPadding", "DESede", 160), + new CI("AES/CBC/NoPadding", "AES", 4800), + new CI("Blowfish/CBC/NoPadding", "Blowfish", 24), + new CI("AES/CTR/NoPadding", "AES", 1600), + new CI("AES/CTR/NoPadding", "AES", 65) }; - private static StringBuffer debugBuf; - @Override public void main(Provider p) throws Exception { - boolean status = true; + List skippedList = new ArrayList<>(); Random random = new Random(); try { - for (int i = 0; i < TEST_LIST.length; i++) { - CI currTest = TEST_LIST[i]; + for (CI currTest : TEST_LIST) { System.out.println("===" + currTest.transformation + "==="); try { KeyGenerator kg = - KeyGenerator.getInstance(currTest.keyAlgo, p); + KeyGenerator.getInstance(currTest.keyAlgo, p); SecretKey key = kg.generateKey(); Cipher c1 = Cipher.getInstance(currTest.transformation, p); Cipher c2 = Cipher.getInstance(currTest.transformation, - System.getProperty("test.provider.name", "SunJCE")); + System.getProperty("test.provider.name", "SunJCE")); byte[] plainTxt = new byte[currTest.dataSize]; random.nextBytes(plainTxt); @@ -97,16 +90,17 @@ public void main(Provider p) throws Exception { AlgorithmParameters params = c2.getParameters(); byte[] answer = c2.doFinal(plainTxt); test(c1, Cipher.ENCRYPT_MODE, key, params, - plainTxt, answer); + plainTxt, answer); System.out.println("Encryption tests: DONE"); c2.init(Cipher.DECRYPT_MODE, key, params); byte[] answer2 = c2.doFinal(answer); test(c1, Cipher.DECRYPT_MODE, key, params, - answer, answer2); + answer, answer2); System.out.println("Decryption tests: DONE"); } catch (NoSuchAlgorithmException nsae) { System.out.println("Skipping unsupported algorithm: " + nsae); + skippedList.add(currTest); } } } catch (Exception ex) { @@ -116,6 +110,10 @@ public void main(Provider p) throws Exception { } throw ex; } + + if (!skippedList.isEmpty()){ + throw new SkippedException("Some tests skipped: " + skippedList); + } } private static void test(Cipher cipher, int mode, SecretKey key, diff --git a/test/jdk/sun/security/pkcs11/Config/ReadConfInUTF16Env.java b/test/jdk/sun/security/pkcs11/Config/ReadConfInUTF16Env.java index 11a6a781e01d..23f5fc3d6a1c 100644 --- a/test/jdk/sun/security/pkcs11/Config/ReadConfInUTF16Env.java +++ b/test/jdk/sun/security/pkcs11/Config/ReadConfInUTF16Env.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, 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 @@ -29,6 +29,7 @@ */ import jdk.test.lib.process.ProcessTools; +import jtreg.SkippedException; import org.testng.annotations.Test; import java.security.Provider; @@ -47,8 +48,7 @@ static class TestSunPKCS11Provider { public static void main(String[] args) throws Exception { Provider p = Security.getProvider("SunPKCS11"); if (p == null) { - System.out.println("Skipping test - no PKCS11 provider available"); - return; + throw new SkippedException("No PKCS11 provider available"); } System.out.println(p.getName()); } diff --git a/test/jdk/sun/security/pkcs11/KeyStore/SecretKeysBasic.java b/test/jdk/sun/security/pkcs11/KeyStore/SecretKeysBasic.java index 4d876604c018..1ff80fcaf07f 100644 --- a/test/jdk/sun/security/pkcs11/KeyStore/SecretKeysBasic.java +++ b/test/jdk/sun/security/pkcs11/KeyStore/SecretKeysBasic.java @@ -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 @@ -116,11 +116,14 @@ private static boolean checkSecretKeyEntry(String alias, // A bug in NSS 3.12 (Mozilla bug 471665) causes AES key lengths // to be read incorrectly. Checking for improper 16 byte length // in key string. - if (isNSS(provider) && expected.getAlgorithm().equals("AES") && - (getNSSVersion() >= 3.12 && getNSSVersion() <= 3.122)) { - System.out.println("NSS 3.12 bug returns incorrect AES key "+ - "length breaking key storage. Aborting..."); - return true; + if (isNSS(provider) && expected.getAlgorithm().equals("AES")) { + Version version = getNSSVersion(); + if (version.major() == 3 && version.minor() == 12 + && version.patch() <= 2) { + System.out.println("NSS 3.12 bug returns incorrect AES key " + + "length breaking key storage. Aborting..."); + return true; + } } if (saveBeforeCheck) { @@ -168,7 +171,7 @@ private static void dumpKey(String info, SecretKey key) { private static void doTest() throws Exception { // Make sure both NSS libraries are the same version. if (isNSS(provider) && - (getLibsoftokn3Version() != getLibnss3Version())) { + (!getLibsoftokn3Version().equals(getLibnss3Version()))) { System.out.println("libsoftokn3 and libnss3 versions do not match. Aborting test..."); return; } diff --git a/test/jdk/sun/security/pkcs11/PKCS11Test.java b/test/jdk/sun/security/pkcs11/PKCS11Test.java index c231791e9728..21324922c70c 100644 --- a/test/jdk/sun/security/pkcs11/PKCS11Test.java +++ b/test/jdk/sun/security/pkcs11/PKCS11Test.java @@ -82,10 +82,10 @@ public abstract class PKCS11Test { // Version of the NSS artifact. This coincides with the version of // the NSS version - private static final String NSS_BUNDLE_VERSION = "3.111"; + private static final String NSS_BUNDLE_VERSION = "3.117"; private static final String NSSLIB = "jpg.tests.jdk.nsslib"; - static double nss_version = -1; + static Version nss_version = null; static ECCState nss_ecc_status = ECCState.Basic; // The NSS library we need to search for in getNSSLibDir() @@ -95,8 +95,8 @@ public abstract class PKCS11Test { // NSS versions of each library. It is simpler to keep nss_version // for quick checking for generic testing than many if-else statements. - static double softoken3_version = -1; - static double nss3_version = -1; + static Version softoken3_version = null; + static Version nss3_version = null; static Provider pkcs11 = newPKCS11Provider(); private static String PKCS11_BASE; private static Map osMap; @@ -271,13 +271,29 @@ private static String getOsId() { } static boolean isBadNSSVersion(Provider p) { - double nssVersion = getNSSVersion(); - if (isNSS(p) && nssVersion >= 3.11 && nssVersion < 3.12) { - System.out.println("NSS 3.11 has a DER issue that recent " + - "version do not, skipping"); - return true; + Version nssVersion = getNSSVersion(); + if (isNSS(p)) { + // bad version is just between [3.11,3.12) + return nssVersion.major == 3 && 11 == nssVersion.minor; + } else { + return false; } - return false; + } + + public record Version(int major, int minor, int patch) {} + + protected static Version parseVersionString(String version) { + String [] parts = version.split("\\."); + int major = Integer.parseInt(parts[0]); + int minor = 0; + int patch = 0; + if (parts.length >= 2) { + minor = Integer.parseInt(parts[1]); + } + if (parts.length >= 3) { + patch = Integer.parseInt(parts[2]); + } + return new Version(major, minor, patch); } protected static void safeReload(String lib) { @@ -306,26 +322,26 @@ public static boolean isNSS(Provider p) { return p.getName().equalsIgnoreCase("SUNPKCS11-NSS"); } - static double getNSSVersion() { - if (nss_version == -1) + static Version getNSSVersion() { + if (nss_version == null) getNSSInfo(); return nss_version; } static ECCState getNSSECC() { - if (nss_version == -1) + if (nss_version == null) getNSSInfo(); return nss_ecc_status; } - public static double getLibsoftokn3Version() { - if (softoken3_version == -1) + public static Version getLibsoftokn3Version() { + if (softoken3_version == null) return getNSSInfo("softokn3"); return softoken3_version; } - public static double getLibnss3Version() { - if (nss3_version == -1) + public static Version getLibnss3Version() { + if (nss3_version == null) return getNSSInfo("nss3"); return nss3_version; } @@ -340,7 +356,7 @@ static void getNSSInfo() { // $Header: NSS // Version: NSS // Here, stands for NSS version. - static double getNSSInfo(String library) { + static Version getNSSInfo(String library) { // look for two types of headers in NSS libraries String nssHeader1 = "$Header: NSS"; String nssHeader2 = "Version: NSS"; @@ -349,15 +365,15 @@ static double getNSSInfo(String library) { int i = 0; Path libfile = null; - if (library.compareTo("softokn3") == 0 && softoken3_version > -1) + if (library.compareTo("softokn3") == 0 && softoken3_version != null) return softoken3_version; - if (library.compareTo("nss3") == 0 && nss3_version > -1) + if (library.compareTo("nss3") == 0 && nss3_version != null) return nss3_version; try { libfile = getNSSLibPath(); if (libfile == null) { - return 0.0; + return parseVersionString("0.0"); } try (InputStream is = Files.newInputStream(libfile)) { byte[] data = new byte[1000]; @@ -393,7 +409,7 @@ static double getNSSInfo(String library) { if (!found) { System.out.println("lib" + library + " version not found, set to 0.0: " + libfile); - nss_version = 0.0; + nss_version = parseVersionString("0.0"); return nss_version; } @@ -406,26 +422,7 @@ static double getNSSInfo(String library) { version.append(c); } - // If a "dot dot" release, strip the extra dots for double parsing - String[] dot = version.toString().split("\\."); - if (dot.length > 2) { - version = new StringBuilder(dot[0] + "." + dot[1]); - for (int j = 2; dot.length > j; j++) { - version.append(dot[j]); - } - } - - // Convert to double for easier version value checking - try { - nss_version = Double.parseDouble(version.toString()); - } catch (NumberFormatException e) { - System.out.println("===== Content start ====="); - System.out.println(s); - System.out.println("===== Content end ====="); - System.out.println("Failed to parse lib" + library + - " version. Set to 0.0"); - e.printStackTrace(); - } + nss_version = parseVersionString(version.toString()); System.out.print("library: " + library + ", version: " + version + ". "); @@ -747,7 +744,12 @@ private static Path fetchNssLib(String osId, Path libraryName) throws IOExceptio } private static Path fetchNssLib(Class clazz, Path libraryName) throws IOException { - Path p = ArtifactResolver.fetchOne(clazz); + Path p; + try { + p = ArtifactResolver.fetchOne(clazz); + } catch (IOException exc) { + throw new SkippedException("Could not find NSS", exc); + } return findNSSLibrary(p, libraryName); } @@ -794,7 +796,7 @@ protected boolean skipTest(Provider p) { private void premain(Provider p) throws Exception { if (skipTest(p)) { - return; + throw new SkippedException("See logs for details"); } // set a security manager and policy before a test case runs, diff --git a/test/jdk/sun/security/pkcs11/Provider/Absolute.java b/test/jdk/sun/security/pkcs11/Provider/Absolute.java index c298c076b30f..07a934030dbf 100644 --- a/test/jdk/sun/security/pkcs11/Provider/Absolute.java +++ b/test/jdk/sun/security/pkcs11/Provider/Absolute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2018, 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 @@ -28,6 +28,8 @@ * @summary load DLLs and launch executables using fully qualified path */ +import jtreg.SkippedException; + import java.security.InvalidParameterException; import java.security.Provider; @@ -40,12 +42,11 @@ public static void main(String[] args) throws Exception { try { Provider p = PKCS11Test.getSunPKCS11(config); if (p == null) { - System.out.println("Skipping test - no PKCS11 provider available"); + throw new SkippedException("Skipping test - no PKCS11 provider available"); } } catch (InvalidParameterException ipe) { Throwable ex = ipe.getCause(); - if (ex.getMessage().indexOf( - "Absolute path required for library value:") != -1) { + if (ex.getMessage().contains("Absolute path required for library value:")) { System.out.println("Test Passed: expected exception thrown"); } else { // rethrow diff --git a/test/jdk/sun/security/pkcs11/Provider/ConfigShortPath.java b/test/jdk/sun/security/pkcs11/Provider/ConfigShortPath.java index f229360f1afd..120f289d211b 100644 --- a/test/jdk/sun/security/pkcs11/Provider/ConfigShortPath.java +++ b/test/jdk/sun/security/pkcs11/Provider/ConfigShortPath.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -25,11 +25,17 @@ * @bug 6581254 6986789 7196009 8062170 * @summary Allow '~', '+', and quoted paths in config file * @author Valerie Peng + * @library /test/lib */ -import java.security.*; -import java.io.*; -import java.lang.reflect.*; +import jtreg.SkippedException; + +import java.io.File; +import java.io.IOException; +import java.security.InvalidParameterException; +import java.security.Provider; +import java.security.ProviderException; +import java.security.Security; public class ConfigShortPath { @@ -43,8 +49,7 @@ public class ConfigShortPath { public static void main(String[] args) throws Exception { Provider p = Security.getProvider("SunPKCS11"); if (p == null) { - System.out.println("Skipping test - no PKCS11 provider available"); - return; + throw new SkippedException("Skipping test - no PKCS11 provider available"); } String osInfo = System.getProperty("os.name", ""); @@ -65,7 +70,7 @@ public static void main(String[] args) throws Exception { if (cause.getClass().getName().equals ("sun.security.pkcs11.ConfigurationException")) { // Error occurred during parsing - if (cause.getMessage().indexOf("Unexpected") != -1) { + if (cause.getMessage().contains("Unexpected")) { throw (ProviderException) cause; } } diff --git a/test/jdk/sun/security/pkcs11/Provider/LoginISE.java b/test/jdk/sun/security/pkcs11/Provider/LoginISE.java index 5027770c5e67..d131a8572164 100644 --- a/test/jdk/sun/security/pkcs11/Provider/LoginISE.java +++ b/test/jdk/sun/security/pkcs11/Provider/LoginISE.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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,16 +21,22 @@ * questions. */ -import java.io.*; -import java.util.*; -import java.security.*; -import javax.security.auth.callback.*; +import jtreg.SkippedException; + +import java.io.IOException; +import java.security.AuthProvider; +import java.security.Provider; +import java.security.Security; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.UnsupportedCallbackException; /** * @test * @bug 8130648 * @summary make sure IllegalStateException is thrown for uninitialized * SunPKCS11 provider instance + * @library /test/lib */ public class LoginISE { @@ -38,8 +44,7 @@ public static void main(String[] args) throws Exception { Provider p = Security.getProvider("SunPKCS11"); if (p == null) { - System.out.println("No un-initialized PKCS11 provider available; skip"); - return; + throw new SkippedException("No un-initialized PKCS11 provider available; skip"); } if (!(p instanceof AuthProvider)) { throw new RuntimeException("Error: expect AuthProvider!"); diff --git a/test/jdk/sun/security/pkcs11/Secmod/AddPrivateKey.java b/test/jdk/sun/security/pkcs11/Secmod/AddPrivateKey.java index ab74358fb0f7..91226f4a2280 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/AddPrivateKey.java +++ b/test/jdk/sun/security/pkcs11/Secmod/AddPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -68,9 +68,7 @@ public static void main(String[] args) throws Exception { BASE + File.separator + args[1]); } - if (initSecmod() == false) { - return; - } + initSecmod(); String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); diff --git a/test/jdk/sun/security/pkcs11/Secmod/AddTrustedCert.java b/test/jdk/sun/security/pkcs11/Secmod/AddTrustedCert.java index 9792a80de8dc..9c33c70e8952 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/AddTrustedCert.java +++ b/test/jdk/sun/security/pkcs11/Secmod/AddTrustedCert.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2019, 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 @@ -53,9 +53,7 @@ public static void main(String[] args) throws Exception { BASE + File.separator + args[1]); } - if (initSecmod() == false) { - return; - } + initSecmod(); X509Certificate cert; try (InputStream in = new FileInputStream(BASE + SEP + "anchor.cer")) { @@ -133,10 +131,10 @@ public static void main(String[] args) throws Exception { } private static boolean improperNSSVersion(Provider p) { - double nssVersion = getNSSVersion(); - if (p.getName().equalsIgnoreCase("SunPKCS11-NSSKeyStore") - && nssVersion >= 3.28 && nssVersion < 3.35) { - return true; + Version nssVersion = getNSSVersion(); + if (p.getName().equalsIgnoreCase("SunPKCS11-NSSKeyStore")) { + return nssVersion.major() == 3 && + (nssVersion.minor() >= 28 && nssVersion.minor() < 35); } return false; diff --git a/test/jdk/sun/security/pkcs11/Secmod/Crypto.java b/test/jdk/sun/security/pkcs11/Secmod/Crypto.java index d57794f1199f..57479db6bf5c 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/Crypto.java +++ b/test/jdk/sun/security/pkcs11/Secmod/Crypto.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -41,9 +41,7 @@ public class Crypto extends SecmodTest { public static void main(String[] args) throws Exception { - if (initSecmod() == false) { - return; - } + initSecmod(); String configName = BASE + SEP + "nsscrypto.cfg"; Provider p = getSunPKCS11(configName); diff --git a/test/jdk/sun/security/pkcs11/Secmod/GetPrivateKey.java b/test/jdk/sun/security/pkcs11/Secmod/GetPrivateKey.java index f9f809f0d28f..00fbe7325d83 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/GetPrivateKey.java +++ b/test/jdk/sun/security/pkcs11/Secmod/GetPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -52,9 +52,7 @@ public static void main(String[] args) throws Exception { BASE + File.separator + args[1]); } - if (initSecmod() == false) { - return; - } + initSecmod(); String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); diff --git a/test/jdk/sun/security/pkcs11/Secmod/JksSetPrivateKey.java b/test/jdk/sun/security/pkcs11/Secmod/JksSetPrivateKey.java index 1689d4c4ed99..65693963347e 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/JksSetPrivateKey.java +++ b/test/jdk/sun/security/pkcs11/Secmod/JksSetPrivateKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -51,9 +51,7 @@ public static void main(String[] args) throws Exception { BASE + File.separator + args[1]); } - if (initSecmod() == false) { - return; - } + initSecmod(); String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); diff --git a/test/jdk/sun/security/pkcs11/Secmod/LoadKeystore.java b/test/jdk/sun/security/pkcs11/Secmod/LoadKeystore.java index ce9f8e9bb638..4bd800a49838 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/LoadKeystore.java +++ b/test/jdk/sun/security/pkcs11/Secmod/LoadKeystore.java @@ -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 @@ -48,9 +48,7 @@ public static void main(String[] args) throws Exception { BASE + File.separator + args[1]); } - if (!initSecmod()) { - return; - } + initSecmod(); String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); diff --git a/test/jdk/sun/security/pkcs11/Secmod/TestNssDbSqlite.java b/test/jdk/sun/security/pkcs11/Secmod/TestNssDbSqlite.java index 7b22a4abfc6c..57309749e93a 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/TestNssDbSqlite.java +++ b/test/jdk/sun/security/pkcs11/Secmod/TestNssDbSqlite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Red Hat, Inc. and/or its affiliates. + * Copyright (c) 2017, 2025, Red Hat, Inc. and/or its affiliates. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -46,6 +46,7 @@ import java.security.Provider; import java.security.Signature; +import jtreg.SkippedException; import sun.security.rsa.SunRsaSign; import sun.security.jca.ProviderList; import sun.security.jca.Providers; @@ -66,9 +67,7 @@ public final class TestNssDbSqlite extends SecmodTest { public static void main(String[] args) throws Exception { - if (!initialize()) { - return; - } + initializeProvider(); if (enableDebug) { System.out.println("SunPKCS11 provider: " + @@ -110,16 +109,9 @@ private static void testRetrieveKeysFromKeystore() throws Exception { } } - private static boolean initialize() throws Exception { - return initializeProvider(); - } - - private static boolean initializeProvider() throws Exception { + private static void initializeProvider() throws Exception { useSqlite(true); - if (!initSecmod()) { - System.out.println("Cannot init security module database, skipping"); - return false; - } + initSecmod(); sunPKCS11NSSProvider = getSunPKCS11(BASE + SEP + "nss-sqlite.cfg"); sunJCEProvider = new com.sun.crypto.provider.SunJCE(); @@ -135,7 +127,5 @@ private static boolean initializeProvider() throws Exception { gen.generate(2048); privateKey = gen.getPrivateKey(); certificate = gen.getSelfCertificate(new X500Name("CN=Me"), 365); - - return true; } } diff --git a/test/jdk/sun/security/pkcs11/Secmod/TrustAnchors.java b/test/jdk/sun/security/pkcs11/Secmod/TrustAnchors.java index 81863f028f9b..5b1d69ca90fa 100644 --- a/test/jdk/sun/security/pkcs11/Secmod/TrustAnchors.java +++ b/test/jdk/sun/security/pkcs11/Secmod/TrustAnchors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -44,9 +44,7 @@ public class TrustAnchors extends SecmodTest { public static void main(String[] args) throws Exception { - if (initSecmod() == false) { - return; - } + initSecmod(); // our secmod.db file says nssckbi.*so*, so NSS does not find the // *DLL* on Windows nor the *DYLIB* on Mac OSX. diff --git a/test/jdk/sun/security/pkcs11/SecmodTest.java b/test/jdk/sun/security/pkcs11/SecmodTest.java index 8201548bf9da..1979066e26ad 100644 --- a/test/jdk/sun/security/pkcs11/SecmodTest.java +++ b/test/jdk/sun/security/pkcs11/SecmodTest.java @@ -42,7 +42,7 @@ static void useSqlite(boolean b) { useSqlite = b; } - static boolean initSecmod() throws Exception { + static void initSecmod() throws Exception { useNSS(); LIBPATH = getNSSLibDir(); // load all the libraries except libnss3 into memory @@ -60,7 +60,7 @@ static boolean initSecmod() throws Exception { System.setProperty("pkcs11test.nss.db", DBDIR); } File dbdirFile = new File(DBDIR); - if (dbdirFile.exists() == false) { + if (!dbdirFile.exists()) { dbdirFile.mkdir(); } @@ -73,7 +73,6 @@ static boolean initSecmod() throws Exception { copyFile("key3.db", BASE, DBDIR); copyFile("cert8.db", BASE, DBDIR); } - return true; } private static void copyFile(String name, String srcDir, String dstDir) throws IOException { diff --git a/test/jdk/sun/security/pkcs11/Signature/TestDSAKeyLength.java b/test/jdk/sun/security/pkcs11/Signature/TestDSAKeyLength.java index d2515fa0f5a2..0ab17a31c5b0 100644 --- a/test/jdk/sun/security/pkcs11/Signature/TestDSAKeyLength.java +++ b/test/jdk/sun/security/pkcs11/Signature/TestDSAKeyLength.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2024, 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 @@ -48,13 +48,15 @@ public static void main(String[] args) throws Exception { @Override protected boolean skipTest(Provider provider) { - double version = getNSSVersion(); - String[] versionStrs = Double.toString(version).split("\\."); - int major = Integer.parseInt(versionStrs[0]); - int minor = Integer.parseInt(versionStrs[1]); - if (isNSS(provider) && (version == 0.0 || (major >= 3 && minor >= 14))) { - System.out.println("Skip testing NSS " + version); - return true; + if (isNSS(provider)) { + Version version = getNSSVersion(); + if (version == null) { + return true; + } + if (version.major() >= 3 && version.minor() >= 14){ + System.out.println("Skip testing NSS " + version); + return true; + } } return false; diff --git a/test/jdk/sun/security/pkcs11/ec/ReadCertificates.java b/test/jdk/sun/security/pkcs11/ec/ReadCertificates.java index e0700a45553a..13d857b0aedf 100644 --- a/test/jdk/sun/security/pkcs11/ec/ReadCertificates.java +++ b/test/jdk/sun/security/pkcs11/ec/ReadCertificates.java @@ -56,6 +56,7 @@ import java.util.Map; import javax.security.auth.x500.X500Principal; import jdk.test.lib.security.Providers; +import jtreg.SkippedException; public class ReadCertificates extends PKCS11Test { @@ -79,8 +80,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { if (p.getService("Signature", "SHA1withECDSA") == null) { - System.out.println("Provider does not support ECDSA, skipping..."); - return; + throw new SkippedException("Provider does not support ECDSA"); } /* diff --git a/test/jdk/sun/security/pkcs11/ec/ReadPKCS12.java b/test/jdk/sun/security/pkcs11/ec/ReadPKCS12.java index 7acd4c2dc691..46b665526b9f 100644 --- a/test/jdk/sun/security/pkcs11/ec/ReadPKCS12.java +++ b/test/jdk/sun/security/pkcs11/ec/ReadPKCS12.java @@ -55,6 +55,7 @@ import java.util.Map; import java.util.Random; import jdk.test.lib.security.Providers; +import jtreg.SkippedException; public class ReadPKCS12 extends PKCS11Test { @@ -67,8 +68,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { if (p.getService("Signature", "SHA1withECDSA") == null) { - System.out.println("Provider does not support ECDSA, skipping..."); - return; + throw new SkippedException("Provider does not support ECDSA"); } /* diff --git a/test/jdk/sun/security/pkcs11/ec/TestECDH.java b/test/jdk/sun/security/pkcs11/ec/TestECDH.java index d2a45f3842db..cce51efbea25 100644 --- a/test/jdk/sun/security/pkcs11/ec/TestECDH.java +++ b/test/jdk/sun/security/pkcs11/ec/TestECDH.java @@ -112,6 +112,7 @@ protected boolean skipTest(Provider p) { * PKCS11Test.main will remove this provider if needed */ Providers.setAt(p, 1); + System.out.println("Testing provider " + p.getName()); if (false) { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p); diff --git a/test/jdk/sun/security/pkcs11/ec/TestKeyFactory.java b/test/jdk/sun/security/pkcs11/ec/TestKeyFactory.java index 60066f118af0..eb65be21a51d 100644 --- a/test/jdk/sun/security/pkcs11/ec/TestKeyFactory.java +++ b/test/jdk/sun/security/pkcs11/ec/TestKeyFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -32,6 +32,8 @@ * @run main/othervm -Djava.security.manager=allow TestKeyFactory sm */ +import jtreg.SkippedException; + import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; @@ -127,8 +129,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { if (p.getService("KeyFactory", "EC") == null) { - System.out.println("Provider does not support EC, skipping"); - return; + throw new SkippedException("Provider does not support EC, skipping"); } int[] keyLengths = {256, 521}; KeyFactory kf = KeyFactory.getInstance("EC", p); diff --git a/test/jdk/sun/security/pkcs11/rsa/KeyWrap.java b/test/jdk/sun/security/pkcs11/rsa/KeyWrap.java index 9a44d8ff0360..301d374646ca 100644 --- a/test/jdk/sun/security/pkcs11/rsa/KeyWrap.java +++ b/test/jdk/sun/security/pkcs11/rsa/KeyWrap.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -33,6 +33,8 @@ * @run main/othervm -Djava.security.manager=allow KeyWrap sm */ +import jtreg.SkippedException; + import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.Key; @@ -55,8 +57,7 @@ public void main(Provider p) throws Exception { try { Cipher.getInstance("RSA/ECB/PKCS1Padding", p); } catch (GeneralSecurityException e) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Not supported by provider, skipping"); } KeyPair kp; try { @@ -75,8 +76,7 @@ public void main(Provider p) throws Exception { kp = new KeyPair(pub, priv); } catch (NoSuchAlgorithmException | InvalidKeyException ee) { ee.printStackTrace(); - System.out.println("Provider does not support RSA, skipping"); - return; + throw new SkippedException("Provider does not support RSA, skipping"); } } System.out.println(kp); diff --git a/test/jdk/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java b/test/jdk/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java index e57ba07741c9..d6354e81e779 100644 --- a/test/jdk/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java +++ b/test/jdk/sun/security/pkcs11/sslecc/ClientJSSEServerJSSE.java @@ -42,6 +42,7 @@ import java.security.Provider; import java.security.Security; import jdk.test.lib.security.Providers; +import jtreg.SkippedException; public class ClientJSSEServerJSSE extends PKCS11Test { @@ -60,8 +61,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider p) throws Exception { if (p.getService("KeyFactory", "EC") == null) { - System.out.println("Provider does not support EC, skipping"); - return; + throw new SkippedException("Provider does not support EC, skipping"); } Providers.setAt(p, 1); CipherTest.main(new JSSEFactory(), cmdArgs); diff --git a/test/jdk/sun/security/pkcs11/tls/TestKeyMaterial.java b/test/jdk/sun/security/pkcs11/tls/TestKeyMaterial.java index 2083dadc5b2e..ac4132ecb2f1 100644 --- a/test/jdk/sun/security/pkcs11/tls/TestKeyMaterial.java +++ b/test/jdk/sun/security/pkcs11/tls/TestKeyMaterial.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -36,7 +36,6 @@ import java.io.BufferedReader; import java.nio.file.Files; import java.nio.file.Paths; -import java.security.InvalidAlgorithmParameterException; import java.security.Provider; import java.security.ProviderException; import java.util.Arrays; @@ -46,6 +45,7 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; +import jtreg.SkippedException; import sun.security.internal.spec.TlsKeyMaterialParameterSpec; import sun.security.internal.spec.TlsKeyMaterialSpec; @@ -61,8 +61,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider provider) throws Exception { if (provider.getService("KeyGenerator", "SunTlsKeyMaterial") == null) { - System.out.println("Provider does not support algorithm, skipping"); - return; + throw new SkippedException("Provider does not support algorithm, skipping"); } try (BufferedReader reader = Files.newBufferedReader( diff --git a/test/jdk/sun/security/pkcs11/tls/TestKeyMaterialChaCha20.java b/test/jdk/sun/security/pkcs11/tls/TestKeyMaterialChaCha20.java index 51471fca65ae..b784a3127c62 100644 --- a/test/jdk/sun/security/pkcs11/tls/TestKeyMaterialChaCha20.java +++ b/test/jdk/sun/security/pkcs11/tls/TestKeyMaterialChaCha20.java @@ -35,6 +35,8 @@ import javax.crypto.SecretKey; import java.security.Provider; import java.security.NoSuchAlgorithmException; + +import jtreg.SkippedException; import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; import sun.security.internal.spec.TlsMasterSecretParameterSpec; import sun.security.internal.spec.TlsKeyMaterialParameterSpec; @@ -52,20 +54,17 @@ public void main(Provider provider) throws Exception { try { kg1 = KeyGenerator.getInstance("SunTlsRsaPremasterSecret", provider); } catch (Exception e) { - System.out.println("Skipping, SunTlsRsaPremasterSecret KeyGenerator not supported"); - return; + throw new SkippedException("Skipping, SunTlsRsaPremasterSecret KeyGenerator not supported"); } try { kg2 = KeyGenerator.getInstance("SunTls12MasterSecret", provider); } catch (Exception e) { - System.out.println("Skipping, SunTls12MasterSecret KeyGenerator not supported"); - return; + throw new SkippedException("Skipping, SunTls12MasterSecret KeyGenerator not supported"); } try { kg3 = KeyGenerator.getInstance("SunTls12KeyMaterial", provider); } catch (Exception e) { - System.out.println("Skipping, SunTls12KeyMaterial KeyGenerator not supported"); - return; + throw new SkippedException("Skipping, SunTls12KeyMaterial KeyGenerator not supported"); } kg1.init(new TlsRsaPremasterSecretParameterSpec(0x0303, 0x0303)); diff --git a/test/jdk/sun/security/pkcs11/tls/TestMasterSecret.java b/test/jdk/sun/security/pkcs11/tls/TestMasterSecret.java index 816e76697ced..d47fee98284a 100644 --- a/test/jdk/sun/security/pkcs11/tls/TestMasterSecret.java +++ b/test/jdk/sun/security/pkcs11/tls/TestMasterSecret.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -43,6 +43,8 @@ import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; + +import jtreg.SkippedException; import sun.security.internal.interfaces.TlsMasterSecret; import sun.security.internal.spec.TlsMasterSecretParameterSpec; @@ -57,8 +59,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider provider) throws Exception { if (provider.getService("KeyGenerator", "SunTlsMasterSecret") == null) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Not supported by provider, skipping"); } try (BufferedReader reader = Files.newBufferedReader( diff --git a/test/jdk/sun/security/pkcs11/tls/TestPRF.java b/test/jdk/sun/security/pkcs11/tls/TestPRF.java index d99c21d0e568..9682dc700351 100644 --- a/test/jdk/sun/security/pkcs11/tls/TestPRF.java +++ b/test/jdk/sun/security/pkcs11/tls/TestPRF.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2020, 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 @@ -41,6 +41,8 @@ import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; + +import jtreg.SkippedException; import sun.security.internal.spec.TlsPrfParameterSpec; public class TestPRF extends PKCS11Test { @@ -54,8 +56,7 @@ public static void main(String[] args) throws Exception { @Override public void main(Provider provider) throws Exception { if (provider.getService("KeyGenerator", "SunTlsPrf") == null) { - System.out.println("Provider does not support algorithm, skipping"); - return; + throw new SkippedException("Provider does not support algorithm, skipping"); } try (BufferedReader reader = Files.newBufferedReader( diff --git a/test/jdk/sun/security/pkcs11/tls/TestPremaster.java b/test/jdk/sun/security/pkcs11/tls/TestPremaster.java index ebae28c996c7..173ffe69b563 100644 --- a/test/jdk/sun/security/pkcs11/tls/TestPremaster.java +++ b/test/jdk/sun/security/pkcs11/tls/TestPremaster.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2018, 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 @@ -37,6 +37,8 @@ import java.security.InvalidAlgorithmParameterException; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; + +import jtreg.SkippedException; import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; public class TestPremaster extends PKCS11Test { @@ -49,8 +51,7 @@ public static void main(String[] args) throws Exception { public void main(Provider provider) throws Exception { if (provider.getService( "KeyGenerator", "SunTlsRsaPremasterSecret") == null) { - System.out.println("Not supported by provider, skipping"); - return; + throw new SkippedException("Not supported by provider, skipping"); } KeyGenerator kg; kg = KeyGenerator.getInstance("SunTlsRsaPremasterSecret", provider); @@ -88,8 +89,7 @@ private static void test(KeyGenerator kg, } catch (InvalidAlgorithmParameterException iape) { // S12 removed support for SSL v3.0 if (clientVersion == 0x300 || serverVersion == 0x300) { - System.out.println("Skip testing SSLv3 due to no support"); - return; + throw new SkippedException("Skip testing SSLv3 due to no support"); } // unexpected, pass it up throw iape; diff --git a/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java b/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java index a91bbac46519..a07d2d49d27e 100644 --- a/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java +++ b/test/jdk/sun/security/pkcs11/tls/tls12/FipsModeTLS12.java @@ -65,6 +65,7 @@ import javax.net.ssl.TrustManagerFactory; import jdk.test.lib.security.SecurityUtils; +import jtreg.SkippedException; import sun.security.internal.spec.TlsMasterSecretParameterSpec; import sun.security.internal.spec.TlsPrfParameterSpec; import sun.security.internal.spec.TlsRsaPremasterSecretParameterSpec; @@ -88,12 +89,11 @@ public static void main(String[] args) throws Exception { try { initialize(); } catch (Exception e) { - System.out.println("Test skipped: failure during" + - " initialization"); if (enableDebug) { System.out.println(e); } - return; + throw new SkippedException("Test skipped: failure during" + + " initialization"); } if (shouldRun()) { @@ -105,8 +105,8 @@ public static void main(String[] args) throws Exception { System.out.println("Test PASS - OK"); } else { - System.out.println("Test skipped: TLS 1.2 mechanisms" + - " not supported by current SunPKCS11 back-end"); + throw new SkippedException("Test skipped: TLS 1.2 mechanisms" + + " not supported by current SunPKCS11 back-end"); } } @@ -454,9 +454,7 @@ private static void initialize() throws Exception { disabledAlgorithms += "RSASSA-PSS"; Security.setProperty("jdk.tls.disabledAlgorithms", disabledAlgorithms); - if (initSecmod() == false) { - return; - } + initSecmod(); String configName = BASE + SEP + "nss.cfg"; sunPKCS11NSSProvider = getSunPKCS11(configName); System.out.println("SunPKCS11 provider: " + sunPKCS11NSSProvider); diff --git a/test/jdk/sun/security/ssl/SSLSocketImpl/ReuseAddr.java b/test/jdk/sun/security/ssl/SSLSocketImpl/ReuseAddr.java index f7e677bbbd05..68761f10c599 100644 --- a/test/jdk/sun/security/ssl/SSLSocketImpl/ReuseAddr.java +++ b/test/jdk/sun/security/ssl/SSLSocketImpl/ReuseAddr.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -38,7 +38,7 @@ public class ReuseAddr extends SSLSocketTemplate { - private static final int MAX_ATTEMPTS = 3; + private static final int MAX_ATTEMPTS = 15; @Override protected void doServerSide() throws Exception { @@ -65,6 +65,7 @@ public static void main(String[] args) throws Exception { System.err.println(msg); throw new AssertionError("Failed to reuse address: " + msg, x); } else { + Thread.sleep(100*i); System.out.println("Retrying..."); } } diff --git a/test/jdk/sun/security/tools/jarsigner/DefaultOptions.java b/test/jdk/sun/security/tools/jarsigner/DefaultOptions.java index 72756de6f8bd..fe8adfb89624 100644 --- a/test/jdk/sun/security/tools/jarsigner/DefaultOptions.java +++ b/test/jdk/sun/security/tools/jarsigner/DefaultOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -62,7 +62,10 @@ public static void main(String[] args) throws Throwable { keytool("-genkeypair -dname CN=CA -alias ca -keyalg rsa -ext bc:c") .shouldHaveExitValue(0); keytool("-alias a -certreq -file a.req"); - keytool("-alias ca -gencert -infile a.req -outfile a.cert"); + + // The start date is set to -1M to prevent the certificate not yet + // valid during fast enough execution. + keytool("-alias ca -gencert -infile a.req -outfile a.cert -startdate -1M"); keytool("-alias a -import -file a.cert").shouldHaveExitValue(0); Files.write(Path.of("js.conf"), List.of( diff --git a/test/jdk/sun/security/tools/keytool/i18n.java b/test/jdk/sun/security/tools/keytool/i18n.java index 4ba8c7830b72..5e049f741114 100644 --- a/test/jdk/sun/security/tools/keytool/i18n.java +++ b/test/jdk/sun/security/tools/keytool/i18n.java @@ -28,7 +28,7 @@ * @author charlie lai * @modules java.base/sun.security.tools.keytool * @library /test/lib - * @run main/manual/othervm -Duser.language=en i18n + * @run main/manual/othervm -Duser.language=en -Duser.country=USA i18n */ /* @@ -38,7 +38,7 @@ * @author charlie lai * @modules java.base/sun.security.tools.keytool * @library /test/lib - * @run main/manual/othervm -Duser.language=de i18n + * @run main/manual/othervm -Duser.language=de -Duser.country=DE i18n */ /* @@ -48,7 +48,7 @@ * @author charlie lai * @modules java.base/sun.security.tools.keytool * @library /test/lib - * @run main/manual/othervm -Duser.language=ja i18n + * @run main/manual/othervm -Duser.language=ja -Duser.country=JP i18n */ /* @@ -63,11 +63,21 @@ import jdk.test.lib.UIBuilder; -import javax.swing.*; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import javax.swing.JTextArea; +import javax.swing.JButton; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JFrame; +import java.awt.FlowLayout; +import java.awt.BorderLayout; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Locale; +import static javax.swing.BorderFactory.createEmptyBorder; + public class i18n { private static final String[][] TABLE = new String[][]{ {"-help", "All the output in this test should be in ${LANG}. " @@ -238,11 +248,12 @@ public class i18n { "Output in ${LANG}. Check keytool error: java.lang" + ".IllegalArgumentException: if -protected is " + "specified, then -storepass, -keypass, and -new " - + "must not be specified."}, + + "must not be specified."} }; private static String TEST_SRC = System.getProperty("test.src"); private static int TIMEOUT_MS = 120000; private volatile boolean failed = false; + private volatile String failureReason = ""; private volatile boolean aborted = false; private Thread currentThread = null; @@ -334,6 +345,7 @@ public boolean validate(String command, String instruction, String message) { if (failed) { System.out.println(command + ": TEST FAILED"); + System.out.println("REASON: " + failureReason); System.out.println(message); } else { System.out.println(command + ": TEST PASSED"); @@ -352,6 +364,7 @@ public void pass() { public void fail() { failed = true; + failureReason = requestFailDescription(); currentThread.interrupt(); } @@ -359,4 +372,33 @@ public void abort() { aborted = true; currentThread.interrupt(); } + + /** + * Opens a prompt to enter a failure reason to be filled by the tester + */ + public static String requestFailDescription() { + + final JDialog dialogWindow = new JDialog(new JFrame(), "Failure Description", true); + final JTextArea reasonTextArea = new JTextArea(5, 20); + + final JButton okButton = new JButton("OK"); + okButton.addActionListener(e -> dialogWindow.setVisible(false)); + + final JPanel okayBtnPanel = new JPanel( + new FlowLayout(FlowLayout.CENTER, 4, 0)); + okayBtnPanel.setBorder(createEmptyBorder(4, 0, 0, 0)); + okayBtnPanel.add(okButton); + + final JPanel mainPanel = new JPanel(new BorderLayout()); + mainPanel.add(new JScrollPane(reasonTextArea), BorderLayout.CENTER); + mainPanel.add(okayBtnPanel, BorderLayout.SOUTH); + + dialogWindow.add(mainPanel); + dialogWindow.pack(); + dialogWindow.setVisible(true); + + dialogWindow.dispose(); + + return reasonTextArea.getText(); + } } diff --git a/test/jdk/sun/security/util/RegisteredDomain/ParseNames.java b/test/jdk/sun/security/util/RegisteredDomain/ParseNames.java index 904f672ba401..f3811511e530 100644 --- a/test/jdk/sun/security/util/RegisteredDomain/ParseNames.java +++ b/test/jdk/sun/security/util/RegisteredDomain/ParseNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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,7 +23,7 @@ /* * @test - * @bug 8228969 8244087 8255266 8302182 8331864 + * @bug 8228969 8244087 8255266 8302182 8331864 8357062 * @modules java.base/sun.security.util * @summary unit test for RegisteredDomain */ diff --git a/test/jdk/sun/security/util/RegisteredDomain/tests.dat b/test/jdk/sun/security/util/RegisteredDomain/tests.dat index 7fe95c979ea8..7d395c62a742 100644 --- a/test/jdk/sun/security/util/RegisteredDomain/tests.dat +++ b/test/jdk/sun/security/util/RegisteredDomain/tests.dat @@ -72,9 +72,9 @@ w.foo.公司.cn 公司.cn foo.公司.cn www.foo.com com foo.com z.www.foo.com com foo.com com com null -ar.com ar.com null -site.ar.com ar.com site.ar.com -w.site.ar.com ar.com site.ar.com +us.com us.com null +site.us.com us.com site.us.com +w.site.us.com us.com site.us.com # fj (no longer *.fj) foo.gov.fj gov.fj foo.gov.fj @@ -109,6 +109,10 @@ p.w.foo.kawasaki.jp foo.kawasaki.jp w.foo.kawasaki.jp city.kawasaki.jp kawasaki.jp city.kawasaki.jp w.city.kawasaki.jp kawasaki.jp city.kawasaki.jp +# kr +ai.kr ai.kr null +foo.ai.kr ai.kr foo.ai.kr + # kw www.example.kw kw example.kw www.example.com.kw com.kw example.com.kw @@ -151,6 +155,7 @@ w.s.k12.oh.us k12.oh.us s.k12.oh.us s.k12.oh.us k12.oh.us s.k12.oh.us s.pvt.k12.ma.us pvt.k12.ma.us s.pvt.k12.ma.us w.s.pvt.k12.ma.us pvt.k12.ma.us s.pvt.k12.ma.us +kids.us us kids.us # vn site.com.vn com.vn site.com.vn diff --git a/test/jdk/sun/security/validator/CertReplace.java b/test/jdk/sun/security/validator/CertReplace.java index e858cc7657c1..42885b73e96e 100644 --- a/test/jdk/sun/security/validator/CertReplace.java +++ b/test/jdk/sun/security/validator/CertReplace.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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,29 +21,186 @@ * questions. */ -/* - * This test is called by certreplace.sh - */ - import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; import java.security.KeyStore; +import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.Arrays; import java.util.ArrayList; import java.util.List; + +import jdk.test.lib.SecurityTools; +import jdk.test.lib.security.CertUtils; +import jdk.test.lib.security.KeyStoreUtils; import sun.security.validator.Validator; +/* + * @test id=certreplace + * @bug 6948803 + * @summary CertPath validation regression caused by SHA1 replacement root and MD2 disable feature + * @library /test/lib + * @modules java.base/sun.security.validator + * + * @run main CertReplace certreplace.jks certreplace.certs + */ + +/* + * @test id=samedn + * @bug 6958869 + * @summary Regression: PKIXValidator fails when multiple trust anchors have same dn + * @library /test/lib + * @modules java.base/sun.security.validator + * + * @run main CertReplace samedn.jks samedn1.certs + * @run main CertReplace samedn.jks samedn2.certs + */ + public class CertReplace { + private static final String SAMEDN_JKS = "samedn.jks"; + private static final String CERTREPLACE_JKS = "certreplace.jks"; + private static final String PASSWORD = "changeit"; + private static final char[] PASSWORD_CHAR_ARR = PASSWORD.toCharArray(); + + /** + * This method creates certs for the Cert Replace test + * + * @throws Exception + */ + private static void certReplace() throws Exception { + + final String ktBaseParameters = "-storepass " + PASSWORD + " " + + "-keypass " + PASSWORD + " " + + "-keystore " + CERTREPLACE_JKS + " " + + "-keyalg rsa "; + + final Path keystoreFilePath = Paths.get(CERTREPLACE_JKS); + Files.deleteIfExists(keystoreFilePath); + + // 1. Generate 3 aliases in a keystore: ca, int, user + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias ca -dname CN=CA -keyalg rsa -sigalg md2withrsa -ext bc"); + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias int -dname CN=Int -keyalg rsa"); + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias user -dname CN=User -keyalg rsa"); + + final KeyStore keyStore = KeyStoreUtils.loadKeyStore(CERTREPLACE_JKS, PASSWORD); + + // 2. Signing: ca -> int -> user + + SecurityTools.keytool(ktBaseParameters + + "-certreq -alias int -file int.req"); + SecurityTools.keytool(ktBaseParameters + + "-gencert -rfc -alias ca -ext bc -infile int.req " + + "-outfile int.cert"); + + //putting the certificate in the keystore + try (final FileInputStream certInputStream = new FileInputStream("int.cert")) { + final Certificate[] certs = new Certificate[]{ + CertUtils.getCertFromStream( + certInputStream + ) + }; + + final PrivateKey privateKey = (PrivateKey) keyStore.getKey("int", PASSWORD_CHAR_ARR); + keyStore.setKeyEntry("int", privateKey, PASSWORD_CHAR_ARR, certs); + keyStore.store(new FileOutputStream(CERTREPLACE_JKS), PASSWORD_CHAR_ARR); + } + + SecurityTools.keytool(ktBaseParameters + + "-certreq -alias user -file user.req"); + SecurityTools.keytool(ktBaseParameters + + "-gencert -rfc -alias int " + + "-infile user.req " + + "-outfile certreplace.certs"); // this will create certreplace.certs which is later appended + + // 3. Create the certchain file + final Path certPath = Paths.get("certreplace.certs"); + + Files.write(certPath, Files.readAllBytes(Path.of("int.cert")), StandardOpenOption.APPEND); + + final String outputCa = SecurityTools.keytool(ktBaseParameters + + "-export -rfc -alias ca").getOutput(); + Files.write(certPath, outputCa.getBytes(), StandardOpenOption.APPEND); + + // 4. Upgrade ca from MD2withRSA to SHA256withRSA, remove other aliases and make this keystore the cacerts file + keyStore.deleteEntry("int"); + keyStore.deleteEntry("user"); + keyStore.store(new FileOutputStream(CERTREPLACE_JKS), PASSWORD_CHAR_ARR); + + SecurityTools.keytool(ktBaseParameters + + "-selfcert -alias ca"); + } + + /** + * This method creates certs for the Same DN test + * + * @throws Exception + */ + private static void sameDn() throws Exception { + + final String ktBaseParameters = "-storepass " + PASSWORD + " " + + "-keypass " + PASSWORD + " " + + "-keystore " + SAMEDN_JKS + " " + + "-keyalg rsa "; + + final Path keystoreFilePath = Paths.get(SAMEDN_JKS); + Files.deleteIfExists(keystoreFilePath); + + // 1. Generate 3 aliases in a keystore: ca1, ca2, user. The CAs' startdate + // is set to one year ago so that they are expired now + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias ca1 -dname CN=CA -keyalg rsa " + + "-sigalg md5withrsa -ext bc -startdate -1y"); + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias ca2 -dname CN=CA -keyalg rsa " + + "-sigalg sha1withrsa -ext bc -startdate -1y"); + SecurityTools.keytool(ktBaseParameters + + "-genkeypair -alias user -dname CN=User -keyalg rsa"); + + // 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 + // Automatically saves the certs to the certs files + + SecurityTools.keytool(ktBaseParameters + + "-certreq -alias user -file user.req"); + SecurityTools.keytool(ktBaseParameters + + "-gencert -rfc -alias ca1 " + + "-startdate -1M -infile user.req -outfile samedn1.certs"); + SecurityTools.keytool(ktBaseParameters + + "-gencert -rfc -alias ca2 " + + "-startdate -1M -infile user.req -outfile samedn2.certs"); + + // 3. Remove user for cacerts + final KeyStore keyStore = KeyStoreUtils.loadKeyStore(SAMEDN_JKS, PASSWORD); + keyStore.deleteEntry("user"); + keyStore.store(new FileOutputStream(CERTREPLACE_JKS), PASSWORD_CHAR_ARR); + } + /** * @param args {cacerts keystore, cert chain} */ public static void main(String[] args) throws Exception { + if (args[0].equals(CERTREPLACE_JKS)) { + certReplace(); + } else if (args[0].equals(SAMEDN_JKS)) { + sameDn(); + } else { + throw new RuntimeException("Not recognised test " + args[0]); + } + KeyStore ks = KeyStore.getInstance("JKS"); - ks.load(new FileInputStream(args[0]), "changeit".toCharArray()); + try (final FileInputStream certInputStream = new FileInputStream(args[0])) { + ks.load(certInputStream, PASSWORD_CHAR_ARR); + } Validator v = Validator.getInstance (Validator.TYPE_PKIX, Validator.VAR_GENERIC, ks); X509Certificate[] chain = createPath(args[1]); @@ -57,9 +214,10 @@ public static void main(String[] args) throws Exception { public static X509Certificate[] createPath(String chain) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); List list = new ArrayList(); - for (Certificate c: cf.generateCertificates( - new FileInputStream(chain))) { - list.add((X509Certificate)c); + try (final FileInputStream certInputStream = new FileInputStream(chain)) { + for (Certificate c : cf.generateCertificates(certInputStream)) { + list.add((X509Certificate) c); + } } return (X509Certificate[]) list.toArray(new X509Certificate[0]); } diff --git a/test/jdk/sun/security/validator/certreplace.sh b/test/jdk/sun/security/validator/certreplace.sh deleted file mode 100644 index 79c973280927..000000000000 --- a/test/jdk/sun/security/validator/certreplace.sh +++ /dev/null @@ -1,88 +0,0 @@ -# -# 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 -# 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 6948803 -# @summary CertPath validation regression caused by SHA1 replacement root -# and MD2 disable feature -# @modules java.base/sun.security.validator -# - -if [ "${TESTSRC}" = "" ] ; then - TESTSRC="." -fi -if [ "${TESTJAVA}" = "" ] ; then - JAVAC_CMD=`which javac` - TESTJAVA=`dirname $JAVAC_CMD`/.. - COMPILEJAVA="${TESTJAVA}" -fi - -# set platform-dependent variables -OS=`uname -s` -case "$OS" in - Windows_* ) - FS="\\" - ;; - * ) - FS="/" - ;; -esac - -KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit \ - -keypass changeit -keystore certreplace.jks -keyalg rsa" -JAVAC=$COMPILEJAVA${FS}bin${FS}javac -JAVA=$TESTJAVA${FS}bin${FS}java - -rm -rf certreplace.jks 2> /dev/null - -# 1. Generate 3 aliases in a keystore: ca, int, user - -$KT -genkeypair -alias ca -dname CN=CA -keyalg rsa -sigalg md2withrsa -ext bc -$KT -genkeypair -alias int -dname CN=Int -keyalg rsa -$KT -genkeypair -alias user -dname CN=User -keyalg rsa - -# 2. Signing: ca -> int -> user - -$KT -certreq -alias int | $KT -gencert -rfc -alias ca -ext bc \ - | $KT -import -alias int -$KT -certreq -alias user | $KT -gencert -rfc -alias int \ - | $KT -import -alias user - -# 3. Create the certchain file - -$KT -export -alias user -rfc > certreplace.certs -$KT -export -rfc -alias int >> certreplace.certs -$KT -export -rfc -alias ca >> certreplace.certs - -# 4. Upgrade ca from MD2withRSA to SHA256withRSA, remove other aliases and -# make this keystore the cacerts file - -$KT -selfcert -alias ca -$KT -delete -alias int -$KT -delete -alias user - -# 5. Build and run test - -EXTRAOPTS="--add-exports java.base/sun.security.validator=ALL-UNNAMED" -$JAVAC ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . ${TESTSRC}${FS}CertReplace.java -$JAVA ${TESTVMOPTS} ${TESTJAVAOPTS} ${EXTRAOPTS} CertReplace certreplace.jks certreplace.certs diff --git a/test/jdk/sun/security/validator/samedn.sh b/test/jdk/sun/security/validator/samedn.sh deleted file mode 100644 index 912bbcd40c7c..000000000000 --- a/test/jdk/sun/security/validator/samedn.sh +++ /dev/null @@ -1,86 +0,0 @@ -# -# 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 -# 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 6958869 -# @summary regression: PKIXValidator fails when multiple trust anchors -# have same dn -# @modules java.base/sun.security.validator -# - -if [ "${TESTSRC}" = "" ] ; then - TESTSRC="." -fi -if [ "${TESTJAVA}" = "" ] ; then - JAVAC_CMD=`which javac` - TESTJAVA=`dirname $JAVAC_CMD`/.. - COMPILEJAVA="${TESTJAVA}" -fi - -# set platform-dependent variables -OS=`uname -s` -case "$OS" in - Windows_* ) - FS="\\" - ;; - * ) - FS="/" - ;; -esac - -KT="$TESTJAVA${FS}bin${FS}keytool ${TESTTOOLVMOPTS} -storepass changeit \ - -keypass changeit -keystore samedn.jks -keyalg rsa" -JAVAC=$COMPILEJAVA${FS}bin${FS}javac -JAVA=$TESTJAVA${FS}bin${FS}java - -rm -rf samedn.jks 2> /dev/null - -# 1. Generate 3 aliases in a keystore: ca1, ca2, user. The CAs' startdate -# is set to one year ago so that they are expired now - -$KT -genkeypair -alias ca1 -dname CN=CA -keyalg rsa -sigalg md5withrsa -ext bc -startdate -1y -$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. 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 -startdate -1M > samedn1.certs -$KT -certreq -alias user | $KT -gencert -rfc -alias ca2 -startdate -1M > samedn2.certs - -# 3. Append the ca file - -$KT -export -rfc -alias ca1 >> samedn1.certs -$KT -export -rfc -alias ca2 >> samedn2.certs - -# 4. Remove user for cacerts - -$KT -delete -alias user - -# 5. Build and run test. Make sure the CA certs are ignored for validity check. -# Check both, one of them might be dropped out of map in old codes. - -EXTRAOPTS="--add-exports java.base/sun.security.validator=ALL-UNNAMED" -$JAVAC ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} ${EXTRAOPTS} -d . ${TESTSRC}${FS}CertReplace.java -$JAVA ${TESTVMOPTS} ${TESTJAVAOPTS} ${EXTRAOPTS} CertReplace samedn.jks samedn1.certs || exit 1 -$JAVA ${TESTVMOPTS} ${TESTJAVAOPTS} ${EXTRAOPTS} CertReplace samedn.jks samedn2.certs || exit 2 diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java index 70a727d157b3..626ebaf12641 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TKit.java @@ -41,6 +41,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -505,9 +506,9 @@ public static RuntimeException throwUnknownPlatformError() { public static RuntimeException throwSkippedException(String reason) { trace("Skip the test: " + reason); - RuntimeException ex = ThrowingSupplier.toSupplier( - () -> (RuntimeException) Class.forName("jtreg.SkippedException").getConstructor( - String.class).newInstance(reason)).get(); + RuntimeException ex = ThrowingSupplier.toSupplier(() -> { + return JtregSkippedExceptionClass.INSTANCE.getConstructor(String.class).newInstance(reason); + }).get(); currentTest.notifySkipped(ex); throw ex; @@ -1074,4 +1075,29 @@ static Set tokenizeConfigProperty(String propertyName) { VERBOSE_TEST_SETUP = isNonOf.test(Set.of("init", "i")); } } + + private static final class JtregSkippedExceptionClass extends ClassLoader { + @SuppressWarnings("unchecked") + JtregSkippedExceptionClass() { + super(TKit.class.getClassLoader()); + + final byte[] bytes = Base64.getDecoder().decode( + // Base64-encoded "jtreg/SkippedException.class" file + // emitted by jdk8's javac from "$OPEN_JDK/test/lib/jtreg/SkippedException.java" + "yv66vgAAADQAFQoABAARCgAEABIHABMHABQBABBzZXJpYWxWZXJzaW9uVUlEAQABSgEADUNvbnN0" + + "YW50VmFsdWUFErH6BHk+kr0BAAY8aW5pdD4BACooTGphdmEvbGFuZy9TdHJpbmc7TGphdmEvbGFu" + + "Zy9UaHJvd2FibGU7KVYBAARDb2RlAQAPTGluZU51bWJlclRhYmxlAQAVKExqYXZhL2xhbmcvU3Ry" + + "aW5nOylWAQAKU291cmNlRmlsZQEAFVNraXBwZWRFeGNlcHRpb24uamF2YQwACgALDAAKAA4BABZq" + + "dHJlZy9Ta2lwcGVkRXhjZXB0aW9uAQAaamF2YS9sYW5nL1J1bnRpbWVFeGNlcHRpb24AMQADAAQA" + + "AAABABoABQAGAAEABwAAAAIACAACAAEACgALAAEADAAAACMAAwADAAAAByorLLcAAbEAAAABAA0A" + + "AAAKAAIAAAAiAAYAIwABAAoADgABAAwAAAAiAAIAAgAAAAYqK7cAArEAAAABAA0AAAAKAAIAAAAm" + + "AAUAJwABAA8AAAACABA"); + + clazz = (Class)defineClass("jtreg.SkippedException", bytes, 0, bytes.length); + } + + private final Class clazz; + + static final Class INSTANCE = new JtregSkippedExceptionClass().clazz; + } } diff --git a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java index 787ac67b915b..9a80ca4d0899 100644 --- a/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java +++ b/test/langtools/jdk/javadoc/doclet/testLinkOption/TestRedirectLinks.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -26,40 +26,36 @@ * @bug 8190312 * @key intermittent * @summary test redirected URLs for -link - * @library /tools/lib ../../lib - * @library /test/lib + * @library /tools/lib ../../lib /test/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.javadoc/jdk.javadoc.internal.api * jdk.javadoc/jdk.javadoc.internal.tool * @build toolbox.ToolBox toolbox.JavacTask javadoc.tester.* * @build jtreg.SkippedException - * @build jdk.test.lib.Platform + * @build jdk.test.lib.Platform jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.URIBuilder * @run main TestRedirectLinks */ import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; import java.time.Duration; import java.time.Instant; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManagerFactory; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; @@ -67,6 +63,8 @@ import com.sun.net.httpserver.HttpsServer; import javadoc.tester.JavadocTester; +import jdk.test.lib.net.SimpleSSLContext; +import jdk.test.lib.net.URIBuilder; import toolbox.JavacTask; import toolbox.ToolBox; @@ -74,6 +72,9 @@ import jtreg.SkippedException; public class TestRedirectLinks extends JavadocTester { + // represents the HTTP response body length when the response contains no body + private static final int NO_RESPONSE_BODY = -1; + /** * The entry point of the test. * @param args the array of command line arguments. @@ -207,17 +208,28 @@ public void testWithServers() throws Exception { // start web servers // use loopback address to avoid any issues if proxy is in use - InetAddress localHost = InetAddress.getLoopbackAddress(); + InetAddress loopback = InetAddress.getLoopbackAddress(); try { - oldServer = HttpServer.create(new InetSocketAddress(localHost, 0), 0); - String oldURL = "http:/" + oldServer.getAddress(); + oldServer = HttpServer.create(new InetSocketAddress(loopback, 0), 0); + String oldURL = URIBuilder.newBuilder() + .scheme("http") + .loopback() + .port(oldServer.getAddress().getPort()) + .build().toString(); oldServer.createContext("/", this::handleOldRequest); out.println("Starting old server (" + oldServer.getClass().getSimpleName() + ") on " + oldURL); oldServer.start(); SSLContext sslContext = new SimpleSSLContext().get(); - newServer = HttpsServer.create(new InetSocketAddress(localHost, 0), 0); - String newURL = "https:/" + newServer.getAddress(); + if (sslContext == null) { + throw new AssertionError("Could not create a SSLContext"); + } + newServer = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); + String newURL = URIBuilder.newBuilder() + .scheme("https") + .loopback() + .port(newServer.getAddress().getPort()) + .build().toString(); newServer.setHttpsConfigurator(new HttpsConfigurator(sslContext)); newServer.createContext("/", this::handleNewRequest); out.println("Starting new server (" + newServer.getClass().getSimpleName() + ") on " + newURL); @@ -241,7 +253,7 @@ public void testWithServers() throws Exception { javadoc("-d", "api", "--module-source-path", src.toString(), "--module-path", libModules.toString(), - "-link", "http:/" + oldServer.getAddress(), + "-link", oldURL, "--module", "mC", "-Xdoclint:none"); @@ -282,10 +294,19 @@ private void handleOldRequest(HttpExchange x) throws IOException { + x.getRequestMethod() + " " + x.getRequestURI()); String newProtocol = (newServer instanceof HttpsServer) ? "https" : "http"; - String redirectTo = newProtocol + ":/" + newServer.getAddress() + x.getRequestURI(); + String redirectTo; + try { + redirectTo = URIBuilder.newBuilder().scheme(newProtocol) + .host(newServer.getAddress().getAddress()) + .port(newServer.getAddress().getPort()) + .path(x.getRequestURI().getPath()) + .build().toString(); + } catch (URISyntaxException e) { + throw new IOException(e); + } out.println(" redirect to: " + redirectTo); x.getResponseHeaders().add("Location", redirectTo); - x.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, 0); + x.sendResponseHeaders(HttpURLConnection.HTTP_MOVED_PERM, NO_RESPONSE_BODY); x.getResponseBody().close(); } @@ -306,64 +327,8 @@ private void handleNewRequest(HttpExchange x) throws IOException { responseStream.write(bytes); } } else { - x.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0); + x.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, NO_RESPONSE_BODY); x.getResponseBody().close(); } } - - /** - * Creates a simple usable SSLContext for an HttpsServer using - * a default keystore in the test tree. - *

- * This class is based on - * test/jdk/java/net/httpclient/whitebox/java.net.http/jdk/internal/net/http/SimpleSSLContext.java - */ - static class SimpleSSLContext { - - private final SSLContext ssl; - - /** - * Loads default keystore. - */ - SimpleSSLContext() throws Exception { - Path p = Path.of(System.getProperty("test.src", ".")).toAbsolutePath(); - while (!Files.exists(p.resolve("TEST.ROOT"))) { - p = p.getParent(); - if (p == null) { - throw new IOException("can't find TEST.ROOT"); - } - } - - System.err.println("Test suite root: " + p); - Path testKeys = p.resolve("../lib/jdk/test/lib/net/testkeys").normalize(); - if (!Files.exists(testKeys)) { - throw new IOException("can't find testkeys"); - } - System.err.println("Test keys: " + testKeys); - - try (InputStream fis = Files.newInputStream(testKeys)) { - ssl = init(fis); - } - } - - private SSLContext init(InputStream i) throws Exception { - char[] passphrase = "passphrase".toCharArray(); - KeyStore ks = KeyStore.getInstance("PKCS12"); - ks.load(i, passphrase); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); - kmf.init(ks, passphrase); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); - tmf.init(ks); - - SSLContext ssl = SSLContext.getInstance("TLS"); - ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - return ssl; - } - - SSLContext get() { - return ssl; - } - } } diff --git a/test/langtools/jdk/javadoc/tool/EnablePreviewOption.java b/test/langtools/jdk/javadoc/tool/EnablePreviewOption.java index 971a2dd546fb..5b01f5077231 100644 --- a/test/langtools/jdk/javadoc/tool/EnablePreviewOption.java +++ b/test/langtools/jdk/javadoc/tool/EnablePreviewOption.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8199196 * @summary Test --enable-preview option in javadoc diff --git a/test/langtools/jdk/javadoc/tool/ReleaseOption.java b/test/langtools/jdk/javadoc/tool/ReleaseOption.java index dfee8726f30b..5a7955099ca0 100644 --- a/test/langtools/jdk/javadoc/tool/ReleaseOption.java +++ b/test/langtools/jdk/javadoc/tool/ReleaseOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, 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 @@ -34,7 +34,7 @@ import static jdk.javadoc.internal.tool.Main.Result.*; -/** +/* * @test * @bug 8086737 * @summary Test --release option in javadoc diff --git a/test/langtools/jdk/javadoc/tool/T4696488.java b/test/langtools/jdk/javadoc/tool/T4696488.java index b48c7fac93d2..715f738f53b7 100644 --- a/test/langtools/jdk/javadoc/tool/T4696488.java +++ b/test/langtools/jdk/javadoc/tool/T4696488.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 4696488 * @summary javadoc doesn't handle UNC paths for destination directory diff --git a/test/langtools/jdk/javadoc/tool/T4994049/T4994049.java b/test/langtools/jdk/javadoc/tool/T4994049/T4994049.java index 47fb2aa179ed..247db2732cc4 100644 --- a/test/langtools/jdk/javadoc/tool/T4994049/T4994049.java +++ b/test/langtools/jdk/javadoc/tool/T4994049/T4994049.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2019, 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,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 4994049 * @summary Unit test for SourcePosition.column with respect to tab expansion diff --git a/test/langtools/jdk/javadoc/tool/T6551367.java b/test/langtools/jdk/javadoc/tool/T6551367.java index 875c91a1cf15..815b0b121e4e 100644 --- a/test/langtools/jdk/javadoc/tool/T6551367.java +++ b/test/langtools/jdk/javadoc/tool/T6551367.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2019, 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,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 6551367 * @summary javadoc throws ClassCastException when an link tag tries to reference constructor. diff --git a/test/langtools/jdk/javadoc/tool/TestScriptInComment.java b/test/langtools/jdk/javadoc/tool/TestScriptInComment.java index 3eaa47a36d56..638e4c180597 100644 --- a/test/langtools/jdk/javadoc/tool/TestScriptInComment.java +++ b/test/langtools/jdk/javadoc/tool/TestScriptInComment.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2020, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8138725 8226765 * @summary test --allow-script-in-comments diff --git a/test/langtools/jdk/javadoc/tool/modules/CommandLineFiles.java b/test/langtools/jdk/javadoc/tool/modules/CommandLineFiles.java index 006a6489f8d3..229d729bf402 100644 --- a/test/langtools/jdk/javadoc/tool/modules/CommandLineFiles.java +++ b/test/langtools/jdk/javadoc/tool/modules/CommandLineFiles.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8176539 * @summary Test use case when all java files are listed diff --git a/test/langtools/jdk/javadoc/tool/modules/FilterOptions.java b/test/langtools/jdk/javadoc/tool/modules/FilterOptions.java index 8fd9b26cc12e..e510ea83bc41 100644 --- a/test/langtools/jdk/javadoc/tool/modules/FilterOptions.java +++ b/test/langtools/jdk/javadoc/tool/modules/FilterOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8159305 8167383 * @summary Tests elements filtering options diff --git a/test/langtools/jdk/javadoc/tool/modules/PackageOptions.java b/test/langtools/jdk/javadoc/tool/modules/PackageOptions.java index b6e16dc592d4..2c6624ca19aa 100644 --- a/test/langtools/jdk/javadoc/tool/modules/PackageOptions.java +++ b/test/langtools/jdk/javadoc/tool/modules/PackageOptions.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8159305 * @summary Test modules with packages and subpackages filtering diff --git a/test/langtools/jdk/javadoc/tool/modules/PatchModules.java b/test/langtools/jdk/javadoc/tool/modules/PatchModules.java index 10101a33ec64..ec9e6b3b8940 100644 --- a/test/langtools/jdk/javadoc/tool/modules/PatchModules.java +++ b/test/langtools/jdk/javadoc/tool/modules/PatchModules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8175346 * @summary Test patch module options diff --git a/test/langtools/jdk/javadoc/tool/modules/ReleaseOptions.java b/test/langtools/jdk/javadoc/tool/modules/ReleaseOptions.java index 2e0d4778401e..ce86d073e330 100644 --- a/test/langtools/jdk/javadoc/tool/modules/ReleaseOptions.java +++ b/test/langtools/jdk/javadoc/tool/modules/ReleaseOptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8175346 8175277 * @summary Test release option interactions diff --git a/test/langtools/jdk/javadoc/tool/nonConstExprs/Test.java b/test/langtools/jdk/javadoc/tool/nonConstExprs/Test.java index 889945b236d0..cba4792f1660 100644 --- a/test/langtools/jdk/javadoc/tool/nonConstExprs/Test.java +++ b/test/langtools/jdk/javadoc/tool/nonConstExprs/Test.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8010310 * @summary Error processing sources with -private diff --git a/test/langtools/jdk/javadoc/tool/parser/7091528/T7091528.java b/test/langtools/jdk/javadoc/tool/parser/7091528/T7091528.java index 39a726e3261c..598b1b63c022 100644 --- a/test/langtools/jdk/javadoc/tool/parser/7091528/T7091528.java +++ b/test/langtools/jdk/javadoc/tool/parser/7091528/T7091528.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 7091528 8029145 8037484 * @summary ensures javadoc parses unique source files and ignores all class files diff --git a/test/langtools/jdk/jshell/AnalysisTest.java b/test/langtools/jdk/jshell/AnalysisTest.java index f6cd5bf9efb5..478301f3fd59 100644 --- a/test/langtools/jdk/jshell/AnalysisTest.java +++ b/test/langtools/jdk/jshell/AnalysisTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,14 +25,14 @@ * @test * @summary Test SourceCodeAnalysis * @build KullaTesting TestingInputStream - * @run testng AnalysisTest + * @run junit AnalysisTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class AnalysisTest extends KullaTesting { + @Test public void testSource() { assertAnalyze("int x=3//test", "int x=3;//test", "", true); assertAnalyze("int x=3 ;//test", "int x=3 ;//test", "", true); @@ -41,6 +41,7 @@ public void testSource() { assertAnalyze("int ff; int v // hi", "int ff;", " int v // hi", true); } + @Test public void testSourceSlashStar() { assertAnalyze("/*zoo*/int x=3 /*test*/", "/*zoo*/int x=3; /*test*/", "", true); assertAnalyze("/*zoo*/int x=3 ;/*test*/", "/*zoo*/int x=3 ;/*test*/", "", true); @@ -49,11 +50,13 @@ public void testSourceSlashStar() { assertAnalyze("int ff; int v /*hgjghj*/", "int ff;", " int v /*hgjghj*/", true); } + @Test public void testIncomplete() { assertAnalyze("void m() { //erer", null, "void m() { //erer\n", false); assertAnalyze("int m=//", null, "int m=//\n", false); } + @Test public void testExpression() { assertAnalyze("45//test", "45//test", "", true); assertAnalyze("45;//test", "45;//test", "", true); diff --git a/test/langtools/jdk/jshell/AnalyzeSnippetTest.java b/test/langtools/jdk/jshell/AnalyzeSnippetTest.java index 3e2e1a839e2b..e1a9efb820ed 100644 --- a/test/langtools/jdk/jshell/AnalyzeSnippetTest.java +++ b/test/langtools/jdk/jshell/AnalyzeSnippetTest.java @@ -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 @@ -26,7 +26,7 @@ * @bug 8182270 * @summary test non-eval Snippet analysis * @build KullaTesting TestingInputStream - * @run testng AnalyzeSnippetTest + * @run junit AnalyzeSnippetTest */ import java.io.ByteArrayOutputStream; @@ -34,15 +34,12 @@ import java.util.List; import jdk.jshell.Snippet; import jdk.jshell.DeclarationSnippet; -import org.testng.annotations.Test; import jdk.jshell.JShell; import jdk.jshell.MethodSnippet; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import jdk.jshell.ErroneousSnippet; import jdk.jshell.ExpressionSnippet; import jdk.jshell.ImportSnippet; @@ -52,14 +49,16 @@ import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; import static jdk.jshell.Snippet.SubKind.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class AnalyzeSnippetTest { JShell state; SourceCodeAnalysis sca; - @BeforeMethod + @BeforeEach public void setUp() { state = JShell.builder() .out(new PrintStream(new ByteArrayOutputStream())) @@ -69,7 +68,7 @@ public void setUp() { sca = state.sourceCodeAnalysis(); } - @AfterMethod + @AfterEach public void tearDown() { if (state != null) { state.close(); @@ -78,55 +77,61 @@ public void tearDown() { sca = null; } + @Test public void testImport() { ImportSnippet sn = (ImportSnippet) assertSnippet("import java.util.List;", SubKind.SINGLE_TYPE_IMPORT_SUBKIND); - assertEquals(sn.name(), "List"); + assertEquals("List", sn.name()); sn = (ImportSnippet) assertSnippet("import static java.nio.file.StandardOpenOption.CREATE;", SubKind.SINGLE_STATIC_IMPORT_SUBKIND); assertTrue(sn.isStatic()); } + @Test public void testClass() { TypeDeclSnippet sn = (TypeDeclSnippet) assertSnippet("class C {}", SubKind.CLASS_SUBKIND); - assertEquals(sn.name(), "C"); + assertEquals("C", sn.name()); sn = (TypeDeclSnippet) assertSnippet("enum EE {A, B , C}", SubKind.ENUM_SUBKIND); } + @Test public void testMethod() { MethodSnippet sn = (MethodSnippet) assertSnippet("int m(int x) { return x + x; }", SubKind.METHOD_SUBKIND); - assertEquals(sn.name(), "m"); - assertEquals(sn.signature(), "(int)int"); + assertEquals("m", sn.name()); + assertEquals("(int)int", sn.signature()); } + @Test public void testVar() { VarSnippet sn = (VarSnippet) assertSnippet("int i;", SubKind.VAR_DECLARATION_SUBKIND); - assertEquals(sn.name(), "i"); - assertEquals(sn.typeName(), "int"); + assertEquals("i", sn.name()); + assertEquals("int", sn.typeName()); sn = (VarSnippet) assertSnippet("int jj = 6;", SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND); sn = (VarSnippet) assertSnippet("2 + 2", SubKind.TEMP_VAR_EXPRESSION_SUBKIND); } + @Test public void testExpression() { state.eval("int aa = 10;"); ExpressionSnippet sn = (ExpressionSnippet) assertSnippet("aa", SubKind.VAR_VALUE_SUBKIND); - assertEquals(sn.name(), "aa"); - assertEquals(sn.typeName(), "int"); + assertEquals("aa", sn.name()); + assertEquals("int", sn.typeName()); sn = (ExpressionSnippet) assertSnippet("aa;", SubKind.VAR_VALUE_SUBKIND); - assertEquals(sn.name(), "aa"); - assertEquals(sn.typeName(), "int"); + assertEquals("aa", sn.name()); + assertEquals("int", sn.typeName()); sn = (ExpressionSnippet) assertSnippet("aa = 99", SubKind.ASSIGNMENT_SUBKIND); } + @Test public void testStatement() { StatementSnippet sn = (StatementSnippet) assertSnippet("System.out.println(33)", SubKind.STATEMENT_SUBKIND); @@ -134,6 +139,7 @@ public void testStatement() { SubKind.STATEMENT_SUBKIND); } + @Test public void testErroneous() { ErroneousSnippet sn = (ErroneousSnippet) assertSnippet("+++", SubKind.UNKNOWN_SUBKIND); diff --git a/test/langtools/jdk/jshell/BadExecutionControlSpecTest.java b/test/langtools/jdk/jshell/BadExecutionControlSpecTest.java index a4f4158a5c74..f7b34a0e1942 100644 --- a/test/langtools/jdk/jshell/BadExecutionControlSpecTest.java +++ b/test/langtools/jdk/jshell/BadExecutionControlSpecTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -29,7 +29,7 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool - * @run testng BadExecutionControlSpecTest + * @run junit BadExecutionControlSpecTest */ import java.io.ByteArrayInputStream; @@ -38,12 +38,11 @@ import java.io.PrintStream; import java.util.Collections; import java.util.List; -import org.testng.annotations.Test; import jdk.jshell.spi.ExecutionControl; import jdk.jshell.spi.ExecutionEnv; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class BadExecutionControlSpecTest { private static void assertIllegal(String spec) throws Throwable { try { @@ -80,6 +79,7 @@ public void closeDown() { } } + @Test public void syntaxTest() throws Throwable { assertIllegal(":launch(true)"); assertIllegal("jdi:launch(true"); @@ -87,6 +87,7 @@ public void syntaxTest() throws Throwable { assertIllegal("jdi:,"); } + @Test public void notFoundTest() throws Throwable { assertIllegal("fruitbats"); assertIllegal("jdi:baz(true)"); diff --git a/test/langtools/jdk/jshell/ClassMembersTest.java b/test/langtools/jdk/jshell/ClassMembersTest.java index 25360770ab3e..6e188e7b8eb2 100644 --- a/test/langtools/jdk/jshell/ClassMembersTest.java +++ b/test/langtools/jdk/jshell/ClassMembersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -26,7 +26,7 @@ * @bug 8139829 * @summary Test access to members of user defined class. * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng/timeout=600 ClassMembersTest + * @run junit/timeout=600 ClassMembersTest */ import java.lang.annotation.RetentionPolicy; @@ -36,22 +36,26 @@ import javax.tools.Diagnostic; import jdk.jshell.SourceCodeAnalysis; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; import jdk.jshell.TypeDeclSnippet; import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.Status.VALID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ClassMembersTest extends KullaTesting { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("local")); } - @Test(dataProvider = "memberTestCase") + @ParameterizedTest + @MethodSource("memberTestCaseGenerator") public void memberTest(AccessModifier accessModifier, CodeChunk codeChunk, Static isStaticMember, Static isStaticReference) { MemberTestCase testCase = new MemberTestCase(accessModifier, codeChunk, isStaticMember, isStaticReference); assertEval(testCase.generateSource()); @@ -78,7 +82,8 @@ private List parseCode(String input) { return list; } - @Test(dataProvider = "memberTestCase") + @ParameterizedTest + @MethodSource("memberTestCaseGenerator") public void extendsMemberTest(AccessModifier accessModifier, CodeChunk codeChunk, Static isStaticMember, Static isStaticReference) { MemberTestCase testCase = new ExtendsMemberTestCase(accessModifier, codeChunk, isStaticMember, isStaticReference); String input = testCase.generateSource(); @@ -151,7 +156,8 @@ public void enumTest() { new ExpectedDiagnostic("compiler.err.non-static.cant.be.ref", 0, 8, 1, -1, -1, Diagnostic.Kind.ERROR)); } - @Test(dataProvider = "retentionPolicyTestCase") + @ParameterizedTest + @MethodSource("retentionPolicyTestCaseGenerator") public void annotationTest(RetentionPolicy policy) { assertEval("import java.lang.annotation.*;"); String annotationSource = @@ -174,7 +180,6 @@ public void annotationTest(RetentionPolicy policy) { assertEval("C.Inner.class.getAnnotationsByType(A.class).length > 0;", isRuntimeVisible); } - @DataProvider(name = "retentionPolicyTestCase") public Object[][] retentionPolicyTestCaseGenerator() { List list = new ArrayList<>(); for (RetentionPolicy policy : RetentionPolicy.values()) { @@ -183,7 +188,6 @@ public Object[][] retentionPolicyTestCaseGenerator() { return list.toArray(new Object[list.size()][]); } - @DataProvider(name = "memberTestCase") public Object[][] memberTestCaseGenerator() { List list = new ArrayList<>(); for (AccessModifier accessModifier : AccessModifier.values()) { diff --git a/test/langtools/jdk/jshell/ClassPathTest.java b/test/langtools/jdk/jshell/ClassPathTest.java index b9c862743890..6c2320ffac27 100644 --- a/test/langtools/jdk/jshell/ClassPathTest.java +++ b/test/langtools/jdk/jshell/ClassPathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -30,20 +30,20 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng ClassPathTest + * @run junit ClassPathTest */ import java.nio.file.Path; import java.nio.file.Paths; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ClassPathTest extends KullaTesting { private final Compiler compiler = new Compiler(); private final Path outDir = Paths.get("class_path_test"); + @Test public void testDirectory() { compiler.compile(outDir, "package pkg; public class TestDirectory { }"); assertDeclareFail("import pkg.TestDirectory;", "compiler.err.doesnt.exist"); @@ -52,6 +52,7 @@ public void testDirectory() { assertEval("new pkg.TestDirectory();"); } + @Test public void testJar() { compiler.compile(outDir, "package pkg; public class TestJar { }"); String jarName = "test.jar"; @@ -62,6 +63,7 @@ public void testJar() { assertEval("new pkg.TestJar();"); } + @Test public void testAmbiguousDirectory() { Path p1 = outDir.resolve("dir1"); compiler.compile(p1, @@ -82,6 +84,7 @@ public void testAmbiguousDirectory() { assertEval("new p.TestAmbiguous();", "first"); } + @Test public void testAmbiguousJar() { Path p1 = outDir.resolve("dir1"); compiler.compile(p1, @@ -104,11 +107,13 @@ public void testAmbiguousJar() { assertEval("new p.TestAmbiguous();", "first"); } + @Test public void testEmptyClassPath() { addToClasspath(""); assertEval("new java.util.ArrayList();"); } + @Test public void testUnknown() { addToClasspath(compiler.getPath(outDir.resolve("UNKNOWN"))); assertDeclareFail("new Unknown();", "compiler.err.cant.resolve.location"); diff --git a/test/langtools/jdk/jshell/ClassesTest.java b/test/langtools/jdk/jshell/ClassesTest.java index 8c17c8072f8d..4e1e297d077b 100644 --- a/test/langtools/jdk/jshell/ClassesTest.java +++ b/test/langtools/jdk/jshell/ClassesTest.java @@ -26,7 +26,7 @@ * @bug 8145239 8129559 8080354 8189248 8010319 8246353 8247456 8282160 8292755 8319532 * @summary Tests for EvaluationState.classes * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng ClassesTest + * @run junit ClassesTest */ import java.util.ArrayList; @@ -37,8 +37,6 @@ import jdk.jshell.Snippet; import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import jdk.jshell.Diag; import jdk.jshell.Snippet.Status; @@ -51,16 +49,22 @@ import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.Status.NONEXISTENT; import static jdk.jshell.Snippet.SubKind.*; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -@Test +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ClassesTest extends KullaTesting { + @Test public void noClasses() { assertNumberOfActiveClasses(0); } + @Test public void testSignature1() { TypeDeclSnippet c1 = classKey(assertEval("class A extends B {}", added(RECOVERABLE_NOT_DEFINED))); assertTypeDeclSnippet(c1, "A", RECOVERABLE_NOT_DEFINED, CLASS_SUBKIND, 1, 0); @@ -82,6 +86,7 @@ public void testSignature1() { assertTypeDeclSnippet(c5, "A", RECOVERABLE_NOT_DEFINED, CLASS_SUBKIND, 1, 0); } + @Test public void testSignature2() { TypeDeclSnippet c1 = (TypeDeclSnippet) assertDeclareFail("class A { void f() { return g(); } }", "compiler.err.prob.found.req"); assertTypeDeclSnippet(c1, "A", REJECTED, CLASS_SUBKIND, 0, 2); @@ -92,27 +97,32 @@ public void testSignature2() { ste(c2, RECOVERABLE_DEFINED, DROPPED, true, null)); } + @Test public void classDeclaration() { assertEval("class A { }"); assertClasses(clazz(KullaTesting.ClassType.CLASS, "A")); } + @Test public void interfaceDeclaration() { assertEval("interface A { }"); assertClasses(clazz(KullaTesting.ClassType.INTERFACE, "A")); } + @Test public void annotationDeclaration() { assertEval("@interface A { }"); assertClasses(clazz(KullaTesting.ClassType.ANNOTATION, "A")); } + @Test public void enumDeclaration() { assertEval("enum A { }"); assertClasses(clazz(KullaTesting.ClassType.ENUM, "A")); } + @Test public void classesDeclaration() { assertEval("interface A { }"); assertEval("class B implements A { }"); @@ -128,6 +138,7 @@ public void classesDeclaration() { assertActiveKeys(); } + @Test public void classesRedeclaration1() { Snippet a = classKey(assertEval("class A { }")); Snippet b = classKey(assertEval("interface B { }")); @@ -149,6 +160,7 @@ public void classesRedeclaration1() { assertActiveKeys(); } + @Test public void classesRedeclaration2() { assertEval("class A { }"); assertClasses(clazz(KullaTesting.ClassType.CLASS, "A")); @@ -180,6 +192,7 @@ public void classesRedeclaration2() { } //8154496: test3 update: sig change should false + @Test public void classesRedeclaration3() { Snippet a = classKey(assertEval("class A { }")); assertClasses(clazz(KullaTesting.ClassType.CLASS, "A")); @@ -201,6 +214,7 @@ public void classesRedeclaration3() { assertActiveKeys(); } + @Test public void classesCyclic1() { Snippet b = classKey(assertEval("class B extends A { }", added(RECOVERABLE_NOT_DEFINED))); @@ -221,11 +235,12 @@ public void classesCyclic1() { diags = diagsA; assertTrue(diagsB.isEmpty()); } - assertEquals(diags.size(), 1, "Expected one error"); - assertEquals(diags.get(0).getCode(), "compiler.err.cyclic.inheritance", "Expected cyclic inheritance error"); + assertEquals(1, diags.size(), "Expected one error"); + assertEquals("compiler.err.cyclic.inheritance", diags.get(0).getCode(), "Expected cyclic inheritance error"); assertActiveKeys(); } + @Test public void classesCyclic2() { Snippet d = classKey(assertEval("class D extends E { }", added(RECOVERABLE_NOT_DEFINED))); assertEval("class E { D d; }", @@ -234,6 +249,7 @@ public void classesCyclic2() { assertActiveKeys(); } + @Test public void classesCyclic3() { Snippet outer = classKey(assertEval("class Outer { class Inner extends Foo { } }", added(RECOVERABLE_NOT_DEFINED))); @@ -247,6 +263,7 @@ public void classesCyclic3() { assertActiveKeys(); } + @Test public void classesIgnoredModifiers() { assertEval("public interface A { }"); assertEval("static class B implements A { }"); @@ -254,6 +271,7 @@ public void classesIgnoredModifiers() { assertActiveKeys(); } + @Test public void classesIgnoredModifiersAnnotation() { assertEval("public @interface X { }"); assertEval("@X public interface A { }"); @@ -262,6 +280,7 @@ public void classesIgnoredModifiersAnnotation() { assertActiveKeys(); } + @Test public void classesIgnoredModifiersOtherModifiers() { assertEval("strictfp public interface A { }"); assertEval("strictfp static class B implements A { }"); @@ -269,6 +288,7 @@ public void classesIgnoredModifiersOtherModifiers() { assertActiveKeys(); } + @Test public void ignoreModifierSpaceIssue() { assertEval("interface I { void f(); } "); // there should not be a space between 'I' and '{' to reproduce the failure @@ -277,7 +297,6 @@ public void ignoreModifierSpaceIssue() { assertActiveKeys(); } - @DataProvider(name = "innerClasses") public Object[][] innerClasses() { List list = new ArrayList<>(); for (ClassType outerClassType : ClassType.values()) { @@ -288,7 +307,8 @@ public Object[][] innerClasses() { return list.toArray(new Object[list.size()][]); } - @Test(dataProvider = "innerClasses") + @ParameterizedTest + @MethodSource("innerClasses") public void innerClasses(ClassType outerClassType, ClassType innerClassType) { String source = outerClassType + " A {" + (outerClassType == ClassType.ENUM ? ";" : "") + @@ -299,6 +319,7 @@ public void innerClasses(ClassType outerClassType, ClassType innerClassType) { assertActiveKeys(); } + @Test public void testInnerClassesCrash() { Snippet a = classKey(assertEval("class A { class B extends A {} }")); Snippet a2 = classKey(assertEval("class A { interface I1 extends I2 {} interface I2 {} }", @@ -309,20 +330,23 @@ public void testInnerClassesCrash() { ste(a2, VALID, OVERWRITTEN, false, MAIN_SNIPPET)); } + @Test public void testInnerClassesCrash1() { assertEval("class A { class B extends A {} B getB() { return new B();} }"); - assertEquals(varKey(assertEval("A a = new A();")).name(), "a"); + assertEquals("a", varKey(assertEval("A a = new A();")).name()); VarSnippet variableKey = varKey(assertEval("a.getB();")); - assertEquals(variableKey.typeName(), "A.B"); + assertEquals("A.B", variableKey.typeName()); } + @Test public void testInnerClassesCrash2() { assertEval("class A { interface I1 extends I2 {} interface I2 {} I1 x; }"); - assertEquals(varKey(assertEval("A a = new A();")).name(), "a"); + assertEquals("a", varKey(assertEval("A a = new A();")).name()); VarSnippet variableKey = varKey(assertEval("a.x;")); - assertEquals(variableKey.typeName(), "A.I1"); + assertEquals("A.I1", variableKey.typeName()); } + @Test public void testCircular() { assertEval("import java.util.function.Supplier;"); TypeDeclSnippet aClass = @@ -342,6 +366,7 @@ public void testCircular() { assertEval("new A()"); } + @Test public void testCircular8282160() { TypeDeclSnippet classKey = classKey(assertEval(""" class B { @@ -360,6 +385,7 @@ public void run() {} ste(classKey, Status.RECOVERABLE_NOT_DEFINED, Status.VALID, true, null)); } + @Test public void testDefaultMethodInInterface() { assertEvalFail(""" interface C { @@ -374,6 +400,7 @@ public void run() { """); } + @Test public void testNonSealed() { assertAnalyze("non-sealed class C extends B {}int i;", "non-sealed class C extends B {}", diff --git a/test/langtools/jdk/jshell/CommandCompletionTest.java b/test/langtools/jdk/jshell/CommandCompletionTest.java index 3a818a74e1e5..ef02e1359734 100644 --- a/test/langtools/jdk/jshell/CommandCompletionTest.java +++ b/test/langtools/jdk/jshell/CommandCompletionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -32,7 +32,7 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build ReplToolTesting TestingInputStream Compiler - * @run testng CommandCompletionTest + * @run junit CommandCompletionTest */ import java.io.IOException; @@ -46,16 +46,16 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.testng.SkipException; -import org.testng.annotations.Test; import jdk.internal.jshell.tool.JShellTool; import jdk.internal.jshell.tool.JShellToolBuilder; import jdk.jshell.SourceCodeAnalysis.Suggestion; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; public class CommandCompletionTest extends ReplToolTesting { @@ -94,7 +94,7 @@ public void assertCompletion(boolean after, String code, boolean isSmart, String public void assertCompletion(String code, boolean isSmart, String... expected) { List completions = computeCompletions(code, isSmart); List expectedL = Arrays.asList(expected); - assertEquals(completions, expectedL, "Command: " + code + ", output: " + + assertEquals(expectedL, completions, "Command: " + code + ", output: " + completions.toString() + ", expected: " + expectedL.toString()); } @@ -356,9 +356,7 @@ public void testUserHome() throws IOException { .map(file -> file.getFileName().toString().replace(" ", "\\ ")) .orElse(null); } - if (selectedFile == null) { - throw new SkipException("No suitable file(s) found for this test in " + home); - } + Assumptions.assumeFalse(selectedFile == null, "No suitable file(s) found for this test in " + home); try (Stream content = Files.list(home)) { completions = content.filter(CLASSPATH_FILTER) .filter(file -> file.getFileName().toString().startsWith(selectedFile.replace("\\ ", " "))) diff --git a/test/langtools/jdk/jshell/CompilerOptionsTest.java b/test/langtools/jdk/jshell/CompilerOptionsTest.java index 1b4f5a8002dc..e4c9332d5aa6 100644 --- a/test/langtools/jdk/jshell/CompilerOptionsTest.java +++ b/test/langtools/jdk/jshell/CompilerOptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,28 +26,29 @@ * @bug 8159635 * @summary Test setting compiler options * @build KullaTesting TestingInputStream - * @run testng CompilerOptionsTest + * @run junit CompilerOptionsTest */ import javax.tools.Diagnostic; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; import static jdk.jshell.Snippet.Status.VALID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class CompilerOptionsTest extends KullaTesting { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(b -> b.compilerOptions("-source", "8", "-Xlint:cast,-options")); } + @Test public void testLint() { assertDeclareWarn1("String s = (String)\"hello\";", new ExpectedDiagnostic("compiler.warn.redundant.cast", 11, 26, 11, -1, -1, Diagnostic.Kind.WARNING)); } + @Test public void testSourceVersion() { assertEval("import java.util.ArrayList;", added(VALID)); // Diamond with anonymous classes allowed in 9 diff --git a/test/langtools/jdk/jshell/CompletenessStressTest.java b/test/langtools/jdk/jshell/CompletenessStressTest.java index 167ba716b10b..4b20ae93d467 100644 --- a/test/langtools/jdk/jshell/CompletenessStressTest.java +++ b/test/langtools/jdk/jshell/CompletenessStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -64,12 +64,12 @@ import jdk.jshell.SourceCodeAnalysis; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; import static java.lang.Integer.max; import static java.lang.Integer.min; import static jdk.jshell.SourceCodeAnalysis.Completeness.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; public class CompletenessStressTest extends KullaTesting { public final static String JDK_ROOT_SRC_PROP = "jdk.root.src"; @@ -99,7 +99,6 @@ public File[] getDirectoriesToTest() { }; } - @DataProvider(name = "crawler") public Object[][] dataProvider() throws IOException { File[] srcDirs = getDirectoriesToTest(); List list = new ArrayList<>(); @@ -121,7 +120,8 @@ public Object[][] dataProvider() throws IOException { return list.toArray(new String[list.size()][]); } - @Test(dataProvider = "crawler") + @ParameterizedTest + @MethodSource("dataProvider") public void testFile(String fileName) throws IOException { File file = getSourceFile(fileName); final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); diff --git a/test/langtools/jdk/jshell/CompletenessTest.java b/test/langtools/jdk/jshell/CompletenessTest.java index 79d819656891..d638b3e86262 100644 --- a/test/langtools/jdk/jshell/CompletenessTest.java +++ b/test/langtools/jdk/jshell/CompletenessTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -26,7 +26,7 @@ * @bug 8149524 8131024 8165211 8080071 8130454 8167343 8129559 8114842 8182268 8223782 8235474 8246774 8276149 * @summary Test SourceCodeAnalysis * @build KullaTesting TestingInputStream - * @run testng CompletenessTest + * @run junit CompletenessTest */ import java.util.Map; @@ -35,13 +35,11 @@ import javax.lang.model.SourceVersion; import jdk.jshell.JShell; -import org.testng.annotations.Test; import jdk.jshell.SourceCodeAnalysis.Completeness; import static jdk.jshell.SourceCodeAnalysis.Completeness.*; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.Test; -@Test public class CompletenessTest extends KullaTesting { // Add complete units that end with semicolon to complete_with_semi (without @@ -282,30 +280,37 @@ private void assertStatus(String[] ins, Completeness status) { } } + @Test public void test_complete() { assertStatus(complete, COMPLETE); } + @Test public void test_expression() { assertStatus(expression, COMPLETE); } + @Test public void test_complete_with_semi() { assertStatus(complete_with_semi, COMPLETE_WITH_SEMI); } + @Test public void test_considered_incomplete() { assertStatus(considered_incomplete, CONSIDERED_INCOMPLETE); } + @Test public void test_definitely_incomplete() { assertStatus(definitely_incomplete, DEFINITELY_INCOMPLETE); } + @Test public void test_unknown() { assertStatus(definitely_incomplete, DEFINITELY_INCOMPLETE); } + @Test public void testCompleted_complete_with_semi() { for (String in : complete_with_semi) { String input = in + ";"; @@ -313,6 +318,7 @@ public void testCompleted_complete_with_semi() { } } + @Test public void testCompleted_expression_with_semi() { for (String in : expression) { String input = in + ";"; @@ -320,6 +326,7 @@ public void testCompleted_expression_with_semi() { } } + @Test public void testCompleted_considered_incomplete() { for (String in : considered_incomplete) { String input = in + ";"; @@ -336,12 +343,14 @@ private void assertSourceByStatus(String first) { } } + @Test public void testCompleteSource_complete() { for (String input : complete) { assertSourceByStatus(input); } } + @Test public void testCompleteSource_complete_with_semi() { for (String in : complete_with_semi) { String input = in + ";"; @@ -349,6 +358,7 @@ public void testCompleteSource_complete_with_semi() { } } + @Test public void testCompleteSource_expression() { for (String in : expression) { String input = in + ";"; @@ -356,6 +366,7 @@ public void testCompleteSource_expression() { } } + @Test public void testCompleteSource_considered_incomplete() { for (String in : considered_incomplete) { String input = in + ";"; @@ -363,15 +374,18 @@ public void testCompleteSource_considered_incomplete() { } } + @Test public void testTrailingSlash() { assertStatus("\"abc\\", UNKNOWN, "\"abc\\"); } + @Test public void testOpenComment() { assertStatus("int xx; /* hello", DEFINITELY_INCOMPLETE, null); assertStatus("/** test", DEFINITELY_INCOMPLETE, null); } + @Test public void testTextBlocks() { assertStatus("\"\"\"", DEFINITELY_INCOMPLETE, null); assertStatus("\"\"\"broken", DEFINITELY_INCOMPLETE, null); @@ -389,6 +403,7 @@ public void testTextBlocks() { assertStatus("\"\"\"\n\\{0}", DEFINITELY_INCOMPLETE, null); } + @Test public void testMiscSource() { assertStatus("if (t) if ", DEFINITELY_INCOMPLETE, "if (t) if"); //Bug assertStatus("int m() {} dfd", COMPLETE, "int m() {}"); diff --git a/test/langtools/jdk/jshell/CompletionSuggestionTest.java b/test/langtools/jdk/jshell/CompletionSuggestionTest.java index dda5e9f9f060..73b06a045d16 100644 --- a/test/langtools/jdk/jshell/CompletionSuggestionTest.java +++ b/test/langtools/jdk/jshell/CompletionSuggestionTest.java @@ -32,7 +32,7 @@ * jdk.jshell/jdk.jshell:open * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng CompletionSuggestionTest + * @run junit CompletionSuggestionTest */ import java.io.IOException; @@ -50,18 +50,19 @@ import java.util.jar.JarOutputStream; import jdk.jshell.Snippet; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.Status.OVERWRITTEN; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class CompletionSuggestionTest extends KullaTesting { private final Compiler compiler = new Compiler(); private final Path outDir = Paths.get("completion_suggestion_test"); + @Test public void testMemberExpr() { assertEval("class Test { static void test() { } }"); assertCompletion("Test.t|", "test()"); @@ -111,16 +112,19 @@ public void testMemberExpr() { assertCompletion("\"\"\"\n\"\"\".leng|", "length()"); } + @Test public void testStartOfExpression() { assertEval("int ccTest = 0;"); assertCompletion("System.err.println(cc|", "ccTest"); assertCompletion("for (int i = cc|", "ccTest"); } + @Test public void testParameter() { assertCompletion("class C{void method(int num){num|", "num"); } + @Test public void testPrimitive() { Set primitives = new HashSet<>(Arrays.asList("boolean", "char", "byte", "short", "int", "long", "float", "double")); Set onlyVoid = new HashSet<>(Collections.singletonList("void")); @@ -154,6 +158,7 @@ public void testPrimitive() { assertCompletion("class A(Arrays.asList("Object", "Void")), @@ -166,6 +171,7 @@ public void testEmpty() { new HashSet<>(Arrays.asList("$REPL00DOESNOTMATTER"))); } + @Test public void testSmartCompletion() { assertEval("int ccTest1 = 0;"); assertEval("int ccTest2 = 0;"); @@ -198,6 +204,7 @@ public void testSmartCompletion() { assertCompletion("new Klass(|", true, "ccTest1", "ccTest2"); } + @Test public void testSmartCompletionInOverriddenMethodInvocation() { assertEval("int ccTest1 = 0;"); assertEval("int ccTest2 = 0;"); @@ -208,6 +215,7 @@ public void testSmartCompletionInOverriddenMethodInvocation() { assertCompletion("new Extend().method(|", true, "ccTest1", "ccTest2"); } + @Test public void testSmartCompletionForBoxedType() { assertEval("int ccTest1 = 0;"); assertEval("Integer ccTest2 = 0;"); @@ -223,6 +231,7 @@ public void testSmartCompletionForBoxedType() { assertCompletion("method3(|", true, "ccTest1", "ccTest2", "ccTest3", "method1(", "method2(", "method3("); } + @Test public void testNewClass() { assertCompletion("String str = new Strin|", "String(", "StringBuffer(", "StringBuilder(", "StringIndexOutOfBoundsException("); assertCompletion("String str = new java.lang.Strin|", "String(", "StringBuffer(", "StringBuilder(", "StringIndexOutOfBoundsException("); @@ -243,6 +252,7 @@ public void testNewClass() { assertCompletion("new String(I.A|", "A"); } + @Test public void testFullyQualified() { assertCompletion("Optional opt = java.u|", "util."); assertCompletionIncludesExcludes("Optional opt = java.util.O|", new HashSet<>(Collections.singletonList("Optional")), Collections.emptySet()); @@ -271,15 +281,18 @@ public void testFullyQualified() { assertCompletion("p1.p3.|", "Test"); } + @Test public void testCheckAccessibility() { assertCompletion("java.util.regex.Pattern.co|", "compile("); } + @Test public void testCompletePackages() { assertCompletion("java.u|", "util."); assertCompletionIncludesExcludes("jav|", new HashSet<>(Arrays.asList("java.", "javax.")), Collections.emptySet()); } + @Test public void testImports() { assertCompletion("import java.u|", "util."); assertCompletionIncludesExcludes("import jav|", new HashSet<>(Arrays.asList("java.", "javax.")), Collections.emptySet()); @@ -298,10 +311,12 @@ public void testImports() { new HashSet<>(Arrays.asList("class"))); } + @Test public void testImportStart() { assertCompletionIncludesExcludes("import c|", Set.of("com."), Set.of()); } + @Test public void testBrokenClassFile() throws Exception { Compiler compiler = new Compiler(); Path testOutDir = Paths.get("CompletionTestBrokenClassFile"); @@ -311,6 +326,7 @@ public void testBrokenClassFile() throws Exception { assertCompletion("import inner.|"); } + @Test public void testDocumentation() throws Exception { dontReadParameterNamesFromClassFile(); assertSignature("System.getProperty(|", @@ -339,6 +355,7 @@ public void testDocumentation() throws Exception { assertSignature("field.FieldTest.R|", "field.FieldTest.R(java.lang.String s, E e)"); } + @Test public void testMethodsWithNoArguments() throws Exception { dontReadParameterNamesFromClassFile(); assertSignature("System.out.println(|", @@ -354,11 +371,13 @@ public void testMethodsWithNoArguments() throws Exception { "void java.io.PrintStream.println(Object)"); } + @Test public void testErroneous() { assertCompletion("Undefined.|"); assertSignature("does.not.exist|"); } + @Test public void testClinit() { assertEval("enum E{;}"); assertEval("class C{static{}}"); @@ -366,6 +385,7 @@ public void testClinit() { assertCompletionIncludesExcludes("C.|", Collections.emptySet(), new HashSet<>(Collections.singletonList(""))); } + @Test public void testMethodHeaderContext() { assertCompletion("private void f(Runn|", "Runnable"); assertCompletion("void f(Runn|", "Runnable"); @@ -377,6 +397,7 @@ public void testMethodHeaderContext() { assertCompletion("void f(Object o1) throws HogeHoge.|", true, "HogeHogeException"); } + @Test public void testTypeVariables() { assertCompletion("class A { public void test() { TY|", "TYPE"); assertCompletion("class A { public static void test() { TY|"); @@ -384,6 +405,7 @@ public void testTypeVariables() { assertCompletion("class A { public static void test() { TY|", "TYPE"); } + @Test public void testGeneric() { assertEval("import java.util.concurrent.*;"); assertCompletion("java.util.Listf(T... ts)", "void f(A a)"); } + @Test public void testClass() { assertSignature("String|", "java.lang.String"); } + @Test public void testDocumentationOfUserDefinedConstructors() { Snippet a = classKey(assertEval("class A {}")); assertSignature("new A(|", "A()"); @@ -519,6 +547,7 @@ public void testDocumentationOfUserDefinedConstructors() { assertSignature("new A(|", "A(T a)", "A(int i)", " A(T t, U u)"); } + @Test public void testDocumentationOfOverriddenMethods() throws Exception { dontReadParameterNamesFromClassFile(); assertSignature("\"\".wait(|", @@ -534,6 +563,7 @@ public void testDocumentationOfOverriddenMethods() throws Exception { assertSignature("new Extend().method(|", "void Extend.method()"); } + @Test public void testDocumentationOfInvisibleMethods() { assertSignature("Object.wait(|"); assertSignature("\"\".indexOfSupplementary(|"); @@ -545,12 +575,14 @@ public void testDocumentationOfInvisibleMethods() { assertSignature("new A().method(|"); } + @Test public void testDocumentationOfInvisibleConstructors() { assertSignature("new Compiler(|"); assertEval("class A { private A() {} }"); assertSignature("new A(|"); } + @Test public void testDocumentationWithBoxing() { assertEval("int primitive = 0;"); assertEval("Integer boxed = 0;"); @@ -567,6 +599,7 @@ public void testDocumentationWithBoxing() { "void method(Object n, int o)"); } + @Test public void testDocumentationWithGenerics() { class TestDocumentationWithGenerics { private final Function codeFacotry; @@ -621,6 +654,7 @@ void assertDoc(String generics, String expectedGenerics) { }); } + @Test public void testVarArgs() { assertEval("int i = 0;"); assertEval("class Foo1 { static void m(int... i) { } } "); @@ -646,6 +680,7 @@ public void testVarArgs() { assertCompletion("Foo4.m(ia, |", true, "str"); } + @Test public void testConstructorAsMemberOf() { assertEval("class Baz { Baz(X x) { } } "); assertEval("String str = null;"); @@ -657,6 +692,7 @@ public void testConstructorAsMemberOf() { assertCompletion("Foo.m(new Baz<>(|", true, "str"); } + @Test public void testIntersection() { assertEval(" Z get() { return null; }"); assertEval("var v = get();"); @@ -666,6 +702,7 @@ public void testIntersection() { assertCompletion("Number r = |", true); } + @Test public void testAnonymous() { assertEval("var v = new Runnable() { public void run() { } public int length() { return 0; } };"); assertCompletionIncludesExcludes("v.|", true, Set.of("run()", "length()"), Set.of()); @@ -673,10 +710,12 @@ public void testAnonymous() { assertCompletion("CharSequence r = |", true); } + @Test public void testCompletionInAnonymous() { assertCompletionIncludesExcludes("new Undefined() { int i = \"\".l|", Set.of("length()"), Set.of()); } + @Test public void testMemberReferences() { assertEval("class C {" + " public static String stat() { return null; }" + @@ -700,6 +739,7 @@ public void testMemberReferences() { assertCompletion("FI2 fi = C::|", true, "statConvert1", "statConvert3"); } + @Test public void testBrokenLambdaCompletion() { assertEval("interface Consumer { public void consume(T t); }"); assertEval("interface Function { public R convert(T t); }"); @@ -721,7 +761,7 @@ public void testBrokenLambdaCompletion() { assertCompletion("String s = m8(x -> {x.tri|", "trim()"); } - @BeforeMethod + @BeforeEach public void setUp() { setUp(builder -> builder.executionEngine("local")); @@ -753,7 +793,8 @@ private void dontReadParameterNamesFromClassFile() throws Exception { keepParameterNames.set(getAnalysis(), new String[0]); } - @Test(enabled = false) //TODO 8171829 + @Test //TODO 8171829 + @Disabled public void testBrokenClassFile2() throws IOException { Path broken = outDir.resolve("broken"); compiler.compile(broken, @@ -776,6 +817,7 @@ public void testBrokenClassFile2() throws IOException { assertCompletion("Broke|", "BrokenA", "BrokenC"); } + @Test public void testStatements() { assertEval("String s = \"\";"); assertCompletion("if (s.conta|", (Boolean) null, "contains("); @@ -788,11 +830,13 @@ public void testStatements() { assertCompletion("for (var v : s.conta|", (Boolean) null, "contains("); } + @Test public void testRecord() { assertCompletion("record R() implements Ru|", true, "Runnable"); } //JDK-8296789 + @Test public void testParentMembers() { assertEval("var sb=new StringBuilder();"); assertCompletionIncludesExcludes("sb.|", true, Set.of("capacity()", "setLength("), Set.of("maybeLatin1")); diff --git a/test/langtools/jdk/jshell/ComputeFQNsTest.java b/test/langtools/jdk/jshell/ComputeFQNsTest.java index 68bb530f311e..8e7f5a1d8897 100644 --- a/test/langtools/jdk/jshell/ComputeFQNsTest.java +++ b/test/langtools/jdk/jshell/ComputeFQNsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -31,7 +31,7 @@ * jdk.jshell/jdk.jshell:open * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng ComputeFQNsTest + * @run junit ComputeFQNsTest */ import java.io.Writer; @@ -41,15 +41,16 @@ import java.util.Arrays; import jdk.jshell.SourceCodeAnalysis.QualifiedNames; -import static org.testng.Assert.*; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class ComputeFQNsTest extends KullaTesting { private final Compiler compiler = new Compiler(); private final Path outDir = Paths.get("ComputeFQNsTest"); + @Test public void testAddImport() throws Exception { compiler.compile(outDir, "package test1; public class FQNTestClass { }", "package test2; public class FQNTestClass { }"); String jarName = "test.jar"; @@ -77,7 +78,8 @@ public void testAddImport() throws Exception { assertInferredFQNs("class X { ArrayList", "ArrayList".length(), false, "java.util.ArrayList"); } - @Test(enabled = false) //TODO 8161165 + @Test //TODO 8161165 + @Disabled public void testSuspendIndexing() throws Throwable { compiler.compile(outDir, "package test; public class FQNTest { }"); String jarName = "test.jar"; @@ -127,8 +129,8 @@ public void testSuspendIndexing() throws Throwable { QualifiedNames candidates = getAnalysis().listQualifiedNames(code, code.length()); - assertEquals(candidates.getNames(), Arrays.asList(), "Input: " + code + ", candidates=" + candidates.getNames()); - assertEquals(candidates.isUpToDate(), false, "Input: " + code + ", up-to-date=" + candidates.isUpToDate()); + assertEquals(Arrays.asList(), candidates.getNames(), "Input: " + code + ", candidates=" + candidates.getNames()); + assertEquals(false, candidates.isUpToDate(), "Input: " + code + ", up-to-date=" + candidates.isUpToDate()); Files.delete(continueMarkFile); @@ -136,7 +138,7 @@ public void testSuspendIndexing() throws Throwable { candidates = getAnalysis().listQualifiedNames(code, code.length()); - assertEquals(candidates.getNames(), Arrays.asList("test.FQNTest"), "Input: " + code + ", candidates=" + candidates.getNames()); + assertEquals(Arrays.asList("test.FQNTest"), candidates.getNames(), "Input: " + code + ", candidates=" + candidates.getNames()); assertEquals(true, candidates.isUpToDate(), "Input: " + code + ", up-to-date=" + candidates.isUpToDate()); } diff --git a/test/langtools/jdk/jshell/ConsoleTest.java b/test/langtools/jdk/jshell/ConsoleTest.java index c6ddddac44b0..aaffbc1d1cb9 100644 --- a/test/langtools/jdk/jshell/ConsoleTest.java +++ b/test/langtools/jdk/jshell/ConsoleTest.java @@ -26,7 +26,7 @@ * @bug 8298425 * @summary Verify behavior of System.console() * @build KullaTesting TestingInputStream - * @run testng ConsoleTest + * @run junit ConsoleTest */ import java.io.IOError; @@ -43,8 +43,8 @@ import jdk.jshell.JShell; import jdk.jshell.JShellConsole; -import org.testng.annotations.Test; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; public class ConsoleTest extends KullaTesting { @@ -60,7 +60,7 @@ public Charset charset() { console = new ThrowingJShellConsole() { @Override public String readLine(String prompt) throws IOError { - assertEquals(prompt, "expected"); + assertEquals("expected", prompt); return "AB"; } }; @@ -68,7 +68,7 @@ public String readLine(String prompt) throws IOError { console = new ThrowingJShellConsole() { @Override public char[] readPassword(String prompt) throws IOError { - assertEquals(prompt, "expected"); + assertEquals("expected", prompt); return "AB".toCharArray(); } }; @@ -116,7 +116,7 @@ public void flush() { console = new ThrowingJShellConsole() { @Override public String readLine(String prompt) throws IOError { - assertEquals(prompt, "expected"); + assertEquals("expected", prompt); return "AB"; } }; @@ -144,7 +144,32 @@ public void close() throws IOException {} int count = 1_000; assertEval("for (int i = 0; i < " + count + "; i++) System.console().writer().write(\"A\");"); String expected = "A".repeat(count); - assertEquals(sb.toString(), expected); + assertEquals(expected, sb.toString()); + } + + @Test + public void testConsoleUnicodeWritingTest() { + StringBuilder sb = new StringBuilder(); + console = new ThrowingJShellConsole() { + @Override + public PrintWriter writer() { + return new PrintWriter(new Writer() { + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + sb.append(cbuf, off, len); + } + @Override + public void flush() throws IOException {} + @Override + public void close() throws IOException {} + }); + } + }; + int count = 384; // 128-255, 384-511, 640-767, ... (JDK-8355371) + String testStr = "\u30A2"; // Japanese katakana (A2 >= 80) (JDK-8354910) + assertEval("System.console().writer().write(\"" + testStr + "\".repeat(" + count + "))"); + String expected = testStr.repeat(count); + assertEquals(expected, sb.toString()); } @Test @@ -180,7 +205,7 @@ public void close() throws IOException {} """.replace("${repeats}", "" + repeats) .replace("${output}", "" + output)); String expected = "A".repeat(repeats * output); - assertEquals(sb.toString(), expected); + assertEquals(expected, sb.toString()); } @Override diff --git a/test/langtools/jdk/jshell/CustomInputToolBuilder.java b/test/langtools/jdk/jshell/CustomInputToolBuilder.java index 523981b3d915..f6fdf97ae1ee 100644 --- a/test/langtools/jdk/jshell/CustomInputToolBuilder.java +++ b/test/langtools/jdk/jshell/CustomInputToolBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -27,7 +27,7 @@ * @summary Verify JavaShellToolBuilder uses provided inputs * @modules jdk.jshell * @build KullaTesting TestingInputStream - * @run testng CustomInputToolBuilder + * @run junit CustomInputToolBuilder */ import java.io.ByteArrayInputStream; @@ -38,15 +38,14 @@ import java.util.HashMap; import java.util.List; import jdk.jshell.tool.JavaShellToolBuilder; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertTrue; - -@Test public class CustomInputToolBuilder extends KullaTesting { private static final String TEST_JDK = "test.jdk"; + @Test public void checkCustomInput() throws Exception { String testJdk = System.getProperty(TEST_JDK); try { @@ -102,6 +101,7 @@ private void doTest(boolean interactiveTerminal, String code, String... expected } } + @Test public void checkInteractiveTerminal() throws Exception { String testJdk = System.getProperty(TEST_JDK); try { diff --git a/test/langtools/jdk/jshell/DropTest.java b/test/langtools/jdk/jshell/DropTest.java index e277d1cbeea4..1501d391a4d9 100644 --- a/test/langtools/jdk/jshell/DropTest.java +++ b/test/langtools/jdk/jshell/DropTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -26,20 +26,20 @@ * @bug 8081431 8080069 8167128 8199623 * @summary Test of JShell#drop(). * @build KullaTesting TestingInputStream - * @run testng DropTest + * @run junit DropTest */ import jdk.jshell.DeclarationSnippet; import jdk.jshell.Snippet; import jdk.jshell.MethodSnippet; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.*; +import org.junit.jupiter.api.Test; -@Test public class DropTest extends KullaTesting { + @Test public void testDrop() { Snippet var = varKey(assertEval("int x;")); Snippet method = methodKey(assertEval("int mu() { return x * 4; }")); @@ -88,6 +88,7 @@ public void testDrop() { assertActiveKeys(); } + @Test public void testDropImport() { Snippet imp = importKey(assertEval("import java.util.*;")); Snippet decl = varKey( @@ -101,11 +102,13 @@ public void testDropImport() { assertDeclareFail("list;", "compiler.err.cant.resolve.location"); } + @Test public void testDropStatement() { Snippet x = key(assertEval("if (true);")); assertDrop(x, ste(x, VALID, DROPPED, true, null)); } + @Test public void testDropVarToMethod() { Snippet x = varKey(assertEval("int x;")); DeclarationSnippet method = methodKey(assertEval("double mu() { return x * 4; }")); @@ -123,6 +126,7 @@ public void testDropVarToMethod() { assertActiveKeys(); } + @Test public void testDropMethodToMethod() { Snippet a = methodKey(assertEval("double a() { return 2; }")); DeclarationSnippet b = methodKey(assertEval("double b() { return a() * 10; }")); @@ -139,6 +143,7 @@ public void testDropMethodToMethod() { assertActiveKeys(); } + @Test public void testDropClassToMethod() { Snippet c = classKey(assertEval("class C { int f() { return 7; } }")); DeclarationSnippet m = methodKey(assertEval("int m() { return new C().f(); }")); @@ -150,6 +155,7 @@ public void testDropClassToMethod() { assertActiveKeys(); } + @Test public void testDropVarToClass() { Snippet x = varKey(assertEval("int x;")); DeclarationSnippet a = classKey(assertEval("class A { double a = 4 * x; }")); @@ -165,6 +171,7 @@ public void testDropVarToClass() { assertActiveKeys(); } + @Test public void testDropMethodToClass() { Snippet x = methodKey(assertEval("int x() { return 0; }")); DeclarationSnippet a = classKey(assertEval("class A { double a = 4 * x(); }")); @@ -179,6 +186,7 @@ public void testDropMethodToClass() { assertActiveKeys(); } + @Test public void testDropClassToClass() { Snippet a = classKey(assertEval("class A {}")); Snippet b = classKey(assertEval("class B extends A {}")); @@ -204,6 +212,7 @@ public void testDropClassToClass() { assertActiveKeys(); } + @Test public void testDropNoUpdate() { String as1 = "class A {}"; String as2 = "class A extends java.util.ArrayList {}"; @@ -228,6 +237,7 @@ public void testDropNoUpdate() { } // 8199623 + @Test public void testTwoForkedDrop() { MethodSnippet p = methodKey(assertEval("void p() throws Exception { ((String) null).toString(); }")); MethodSnippet n = methodKey(assertEval("void n() throws Exception { try { p(); } catch (Exception ex) { throw new RuntimeException(\"bar\", ex); }}")); diff --git a/test/langtools/jdk/jshell/EditorTestBase.java b/test/langtools/jdk/jshell/EditorTestBase.java index 422d07ba1c8f..a384c09fcb13 100644 --- a/test/langtools/jdk/jshell/EditorTestBase.java +++ b/test/langtools/jdk/jshell/EditorTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -25,10 +25,10 @@ import java.util.concurrent.Executors; import java.util.function.Consumer; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public abstract class EditorTestBase extends ReplToolTesting { @@ -61,11 +61,11 @@ void assertEditOutput(boolean after, String cmd, Consumer checkOutput, A } void assertEditInput(boolean after, String cmd, String input, Action action) { - assertEditInput(after, cmd, s -> assertEquals(s, input, "Input"), action); + assertEditInput(after, cmd, s -> assertEquals(input, s, "Input"), action); } void assertEditOutput(boolean after, String cmd, String output, Action action) { - assertEditOutput(after, cmd, s -> assertEquals(s.trim(), output.trim(), "command"), action); + assertEditOutput(after, cmd, s -> assertEquals(output.trim(), s.trim(), "command"), action); } @Test @@ -219,16 +219,15 @@ public void testEditMethod2() { @Test public void testNoArguments() { - testEditor( - a -> assertVariable(a, "int", "a"), + testEditor(a -> assertVariable(a, "int", "a"), a -> assertMethod(a, "void f() {}", "()void", "f"), a -> assertClass(a, "class A {}", "class", "A"), a -> assertEditInput(a, "/ed", s -> { String[] ss = s.split("\n"); - assertEquals(ss.length, 3, "Expected 3 lines: " + s); - assertEquals(ss[0], "int a;"); - assertEquals(ss[1], "void f() {}"); - assertEquals(ss[2], "class A {}"); + assertEquals(3, ss.length, "Expected 3 lines: " + s); + assertEquals("int a;", ss[0]); + assertEquals("void f() {}", ss[1]); + assertEquals("class A {}", ss[2]); }, this::exit) ); } @@ -263,7 +262,8 @@ public void testAccept() { ); } - @Test(enabled = false) // TODO JDK-8191875 + @Test // TODO JDK-8191875 + @Disabled public void testStatementMush() { testEditor( a -> assertCommand(a, "System.out.println(\"Hello\")", diff --git a/test/langtools/jdk/jshell/EmptyTest.java b/test/langtools/jdk/jshell/EmptyTest.java index 6e838432220f..937ab04cb2d9 100644 --- a/test/langtools/jdk/jshell/EmptyTest.java +++ b/test/langtools/jdk/jshell/EmptyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -25,34 +25,39 @@ * @test * @summary null test * @build KullaTesting TestingInputStream - * @run testng EmptyTest + * @run junit EmptyTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class EmptyTest extends KullaTesting { + @Test public void testEmpty() { assertEvalEmpty(""); } + @Test public void testSpace() { assertEvalEmpty(" "); } + @Test public void testSemicolon() { assertEval(";", ""); } + @Test public void testSlashStarComment() { assertEvalEmpty("/*test*/"); } + @Test public void testSlashStarCommentSemicolon() { assertEval("/*test*/;", ""); } + @Test public void testSlashComment() { assertEvalEmpty("// test"); } diff --git a/test/langtools/jdk/jshell/ErrorRecoveryTest.java b/test/langtools/jdk/jshell/ErrorRecoveryTest.java index f07db23f977b..5e4f2e9656c5 100644 --- a/test/langtools/jdk/jshell/ErrorRecoveryTest.java +++ b/test/langtools/jdk/jshell/ErrorRecoveryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -31,17 +31,17 @@ * jdk.jshell/jdk.internal.jshell.tool * @library /tools/lib * @build KullaTesting TestingInputStream ExpectedDiagnostic toolbox.ToolBox Compiler - * @run testng ErrorRecoveryTest + * @run junit ErrorRecoveryTest */ -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.NONEXISTENT; import static jdk.jshell.Snippet.Status.RECOVERABLE_NOT_DEFINED; import static jdk.jshell.Snippet.Status.REJECTED; +import org.junit.jupiter.api.Test; -@Test public class ErrorRecoveryTest extends KullaTesting { + @Test public void testExceptionErrors() { assertEval("import java.lang.annotation.Repeatable;"); assertEval(""" @@ -51,6 +51,7 @@ public void testExceptionErrors() { ste(MAIN_SNIPPET, NONEXISTENT, RECOVERABLE_NOT_DEFINED, false, null)); } + @Test public void testBrokenName() { assertEval("int strictfp = 0;", DiagCheck.DIAG_ERROR, @@ -58,6 +59,7 @@ public void testBrokenName() { ste(MAIN_SNIPPET, NONEXISTENT, REJECTED, false, null)); } + @Test public void testBooleanPatternExpression() { assertEval("Number n = 0;"); assertEval("if (!n instanceof Integer i) {}", diff --git a/test/langtools/jdk/jshell/ErrorTranslationTest.java b/test/langtools/jdk/jshell/ErrorTranslationTest.java index 4db2ff65469b..235f4443004c 100644 --- a/test/langtools/jdk/jshell/ErrorTranslationTest.java +++ b/test/langtools/jdk/jshell/ErrorTranslationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * 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 @@ * jdk.jshell/jdk.internal.jshell.tool * @library /tools/lib * @build KullaTesting TestingInputStream ExpectedDiagnostic toolbox.ToolBox Compiler - * @run testng ErrorTranslationTest + * @run junit ErrorTranslationTest */ import java.nio.file.Path; @@ -41,15 +41,15 @@ import javax.tools.Diagnostic; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -@Test public class ErrorTranslationTest extends ReplToolTesting { - @Test(enabled = false) // TODO 8080353 + @Test // TODO 8080353 + @Disabled public void testErrors() { test( a -> assertDiagnostic(a, "abstract void f();", newExpectedDiagnostic(0, 8, 0, -1, -1, Diagnostic.Kind.ERROR)), @@ -60,6 +60,7 @@ public void testErrors() { ); } + @Test public void testlvtiErrors() { test( a -> assertDiagnostic(a, "var broken = () -> {};", newExpectedDiagnostic(0, 22, 0, -1, -1, Diagnostic.Kind.ERROR)), @@ -67,13 +68,15 @@ public void testlvtiErrors() { ); } + @Test public void testExceptionErrors() { test( a -> assertDiagnostic(a, "try { } catch (IllegalStateException | java.io.IOException ex) { }", newExpectedDiagnostic(39, 58, -1, -1, -1, Diagnostic.Kind.ERROR)) ); } - @Test(enabled = false) // TODO 8132147 + @Test // TODO 8132147 + @Disabled public void stressTest() { Compiler compiler = new Compiler(); Path oome = compiler.getPath("OOME.repl"); @@ -115,11 +118,11 @@ private Consumer assertDiagnostic(String expectedSource, ExpectedDiagnos throw new AssertionError("Not enough lines: " + s); } String kind = getKind(expectedDiagnostic.getKind()); - assertEquals(lines[0], kind); + assertEquals(kind, lines[0]); boolean found = false; for (int i = 0; i < lines.length; i++) { if (lines[i].endsWith(expectedSource)) { - assertEquals(lines[i + 1], expectedMarkingLine, "Input: " + expectedSource + ", marking line: "); + assertEquals(expectedMarkingLine, lines[i + 1], "Input: " + expectedSource + ", marking line: "); found = true; } } diff --git a/test/langtools/jdk/jshell/ExceptionMessageTest.java b/test/langtools/jdk/jshell/ExceptionMessageTest.java index fe8eec577392..c329afeb35e8 100644 --- a/test/langtools/jdk/jshell/ExceptionMessageTest.java +++ b/test/langtools/jdk/jshell/ExceptionMessageTest.java @@ -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 @@ -25,7 +25,7 @@ * @test * @bug 8185108 * @summary Test exception().getMessage() in events returned by eval() - * @run testng ExceptionMessageTest + * @run junit ExceptionMessageTest * @key intermittent */ @@ -42,22 +42,23 @@ import jdk.jshell.spi.ExecutionControlProvider; import jdk.jshell.spi.ExecutionEnv; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class ExceptionMessageTest { + @Test public void testDefaultEC() { doTestCases(new JdiExecutionControlProvider(), "default"); } + @Test public void testLocalEC() { doTestCases(new LocalExecutionControlProvider(), "local"); } + @Test public void testDirectEC() { doTestCases(new ExecutionControlProvider() { public ExecutionControl generate(ExecutionEnv env, Map param) throws Throwable { @@ -85,11 +86,11 @@ private void doTestCases(ExecutionControlProvider ec, String label) { private void doTest(JShell jshell, String label, String code, String expected) { List result = jshell.eval(code); - assertEquals(result.size(), 1, "Expected only one event"); + assertEquals(1, result.size(), "Expected only one event"); SnippetEvent evt = result.get(0); Exception exc = evt.exception(); String out = exc.getMessage(); - assertEquals(out, expected, "Exception message not as expected: " + + assertEquals(expected, out, "Exception message not as expected: " + label + " -- " + code); } } diff --git a/test/langtools/jdk/jshell/ExceptionsTest.java b/test/langtools/jdk/jshell/ExceptionsTest.java index 765c3696f072..f7273b2a6fcd 100644 --- a/test/langtools/jdk/jshell/ExceptionsTest.java +++ b/test/langtools/jdk/jshell/ExceptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, 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 @@ -31,7 +31,7 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng ExceptionsTest + * @run junit ExceptionsTest */ import java.io.IOException; @@ -46,16 +46,16 @@ import java.nio.file.Path; import java.nio.file.Paths; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.*; - -@Test public class ExceptionsTest extends KullaTesting { private final Compiler compiler = new Compiler(); private final Path outDir = Paths.get("test_class_path"); + @Test public void throwUncheckedException() { String message = "error_message"; SnippetEvent cr = assertEvalException("throw new RuntimeException(\"" + message + "\");"); @@ -64,6 +64,7 @@ public void throwUncheckedException() { newStackTraceElement("", "", cr.snippet(), 1))); } + @Test public void throwCheckedException() { String message = "error_message"; SnippetEvent cr = assertEvalException("throw new Exception(\"" + message + "\");"); @@ -72,6 +73,7 @@ public void throwCheckedException() { newStackTraceElement("", "", cr.snippet(), 1))); } + @Test public void throwFromStaticMethodOfClass() { String message = "error_message"; Snippet s1 = methodKey(assertEval("void f() { throw new RuntimeException(\"" + message + "\"); }")); @@ -84,6 +86,7 @@ public void throwFromStaticMethodOfClass() { newStackTraceElement("", "", cr3.snippet(), 1))); } + @Test public void throwFromStaticMethodOfInterface() { String message = "error_message"; Snippet s1 = methodKey(assertEval("void f() { throw new RuntimeException(\"" + message + "\"); }")); @@ -96,6 +99,7 @@ public void throwFromStaticMethodOfInterface() { newStackTraceElement("", "", cr3.snippet(), 1))); } + @Test public void throwChained() { String message1 = "error_message1"; String message2 = "error_message2"; @@ -122,6 +126,7 @@ public void throwChained() { newStackTraceElement("", "", cr4.snippet(), 1))); } + @Test public void throwChainedUnresolved() { String message1 = "error_message1"; String message2 = "error_message2"; @@ -144,6 +149,7 @@ public void throwChainedUnresolved() { newStackTraceElement("", "", cr4.snippet(), 1))); } + @Test public void throwFromConstructor() { String message = "error_message"; Snippet s1 = methodKey(assertEval("void f() { throw new RuntimeException(\"" + message + "\"); }")); @@ -156,6 +162,7 @@ public void throwFromConstructor() { newStackTraceElement("", "", cr3.snippet(), 1))); } + @Test public void throwFromDefaultMethodOfInterface() { String message = "error_message"; Snippet s1 = methodKey(assertEval("void f() { throw new RuntimeException(\"" + message + "\"); }")); @@ -168,6 +175,7 @@ public void throwFromDefaultMethodOfInterface() { newStackTraceElement("", "", cr3.snippet(), 1))); } + @Test public void throwFromLambda() { String message = "lambda"; Snippet s1 = varKey(assertEval( @@ -182,6 +190,7 @@ public void throwFromLambda() { newStackTraceElement("", "", cr2.snippet(), 1))); } + @Test public void throwFromAnonymousClass() { String message = "anonymous"; Snippet s1 = varKey(assertEval( @@ -198,6 +207,7 @@ public void throwFromAnonymousClass() { newStackTraceElement("", "", cr2.snippet(), 1))); } + @Test public void throwFromLocalClass() { String message = "local"; Snippet s1 = methodKey(assertEval( @@ -219,6 +229,7 @@ public void throwFromLocalClass() { } // test 8210527 + @Test public void throwFromWithoutSource() { String message = "show this"; SnippetEvent se = assertEvalException("java.lang.reflect.Proxy.newProxyInstance(" + @@ -232,6 +243,7 @@ public void throwFromWithoutSource() { } // test 8210527 + @Test public void throwFromNoSource() { Path path = outDir.resolve("fail"); compiler.compile(path, @@ -250,6 +262,7 @@ public void throwFromNoSource() { } // test 8212167 + @Test public void throwLineFormat1() { SnippetEvent se = assertEvalException( "if (true) { \n" + @@ -261,6 +274,7 @@ public void throwLineFormat1() { newStackTraceElement("", "", se.snippet(), 3))); } + @Test public void throwLineFormat3() { Snippet sp = methodKey(assertEval( "int p() \n" + @@ -292,13 +306,15 @@ public void throwLineFormat3() { newStackTraceElement("", "", se.snippet(), 1))); } - @Test(enabled = false) // TODO 8129427 + @Test // TODO 8129427 + @Disabled public void outOfMemory() { assertEval("import java.util.*;"); assertEval("List list = new ArrayList<>();"); assertExecuteException("while (true) { list.add(new byte[10000]); }", OutOfMemoryError.class); } + @Test public void stackOverflow() { assertEval("void f() { f(); }"); assertExecuteException("f();", StackOverflowError.class); @@ -361,11 +377,11 @@ private void assertExceptionMatch(Throwable exception, String source, ExceptionI EvalException ex = (EvalException) exception; String actualException = ex.getExceptionClassName(); String expectedException = exceptionInfo.exception.getCanonicalName(); - assertEquals(actualException, expectedException, + assertEquals(expectedException, actualException, String.format("Given \"%s\" expected exception: %s, got: %s%nStack trace:%n%s", source, expectedException, actualException, getStackTrace(ex))); if (exceptionInfo.message != null) { - assertEquals(ex.getMessage(), exceptionInfo.message, + assertEquals(exceptionInfo.message, ex.getMessage(), String.format("Given \"%s\" expected message: %s, got: %s", source, exceptionInfo.message, ex.getMessage())); } @@ -395,7 +411,7 @@ private void assertAnyExceptionMatch(Throwable exception, AnyExceptionInfo excep "Expected UnresolvedReferenceException: " + exception); UnresolvedExceptionInfo uei = (UnresolvedExceptionInfo) exceptionInfo; UnresolvedReferenceException ure = (UnresolvedReferenceException) exception; - assertEquals(ure.getSnippet(), uei.sn); + assertEquals(uei.sn, ure.getSnippet()); assertStackMatch(ure, "", exceptionInfo); } } @@ -405,20 +421,20 @@ private void assertStackTrace(StackTraceElement[] actual, StackTraceElement[] ex if (actual == null || expected == null) { fail(message); } else { - assertEquals(actual.length, expected.length, message + " : arrays do not have the same size"); + assertEquals(expected.length, actual.length, message + " : arrays do not have the same size"); for (int i = 0; i < actual.length; ++i) { StackTraceElement actualElement = actual[i]; StackTraceElement expectedElement = expected[i]; - assertEquals(actualElement.getClassName(), expectedElement.getClassName(), message + " : class names [" + i + "]"); + assertEquals(expectedElement.getClassName(), actualElement.getClassName(), message + " : class names [" + i + "]"); String expectedMethodName = expectedElement.getMethodName(); if (expectedMethodName.startsWith("lambda$")) { assertTrue(actualElement.getMethodName().startsWith("lambda$"), message + " : method names"); } else { - assertEquals(actualElement.getMethodName(), expectedElement.getMethodName(), message + " : method names [" + i + "]"); + assertEquals(expectedElement.getMethodName(), actualElement.getMethodName(), message + " : method names [" + i + "]"); } - assertEquals(actualElement.getFileName(), expectedElement.getFileName(), message + " : file names [" + i + "]"); + assertEquals(expectedElement.getFileName(), actualElement.getFileName(), message + " : file names [" + i + "]"); if (expectedElement.getLineNumber() >= 0) { - assertEquals(actualElement.getLineNumber(), expectedElement.getLineNumber(), message + " : line numbers [" + i + "]" + assertEquals(expectedElement.getLineNumber(), actualElement.getLineNumber(), message + " : line numbers [" + i + "]" + " -- actual: " + actualElement.getLineNumber() + ", expected: " + expectedElement.getLineNumber() + " -- in: " + actualElement.getClassName()); } diff --git a/test/langtools/jdk/jshell/ExecutionControlSpecTest.java b/test/langtools/jdk/jshell/ExecutionControlSpecTest.java index 920310bb1e55..14661030cf06 100644 --- a/test/langtools/jdk/jshell/ExecutionControlSpecTest.java +++ b/test/langtools/jdk/jshell/ExecutionControlSpecTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -34,20 +34,20 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting Compiler - * @run testng ExecutionControlSpecTest + * @run junit ExecutionControlSpecTest */ import java.nio.file.Path; import java.nio.file.Paths; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class ExecutionControlSpecTest extends KullaTesting { ClassLoader ccl; - @BeforeMethod + @BeforeEach @Override public void setUp() { String mod = "my.ec"; @@ -86,7 +86,7 @@ public void setUp() { setUp(builder -> builder.executionEngine("prefixing")); } - @AfterMethod + @AfterEach @Override public void tearDown() { super.tearDown(); diff --git a/test/langtools/jdk/jshell/ExecutionControlTestBase.java b/test/langtools/jdk/jshell/ExecutionControlTestBase.java index 20336c902cff..a63e1b16569f 100644 --- a/test/langtools/jdk/jshell/ExecutionControlTestBase.java +++ b/test/langtools/jdk/jshell/ExecutionControlTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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,11 +23,11 @@ import javax.tools.Diagnostic; -import org.testng.annotations.Test; import jdk.jshell.VarSnippet; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.SubKind.*; +import org.junit.jupiter.api.Test; public class ExecutionControlTestBase extends KullaTesting { diff --git a/test/langtools/jdk/jshell/ExpectedDiagnostic.java b/test/langtools/jdk/jshell/ExpectedDiagnostic.java index 2416c9875b83..1fe96200e3c6 100644 --- a/test/langtools/jdk/jshell/ExpectedDiagnostic.java +++ b/test/langtools/jdk/jshell/ExpectedDiagnostic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -24,7 +24,7 @@ import javax.tools.Diagnostic; import jdk.jshell.Diag; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ExpectedDiagnostic { @@ -79,16 +79,16 @@ public Diagnostic.Kind getKind() { public void assertDiagnostic(Diag diagnostic) { String code = diagnostic.getCode(); - assertEquals(code, this.code, "Expected error: " + this.code + ", got: " + code); - assertEquals(diagnostic.isError(), kind == Diagnostic.Kind.ERROR); + assertEquals(this.code, code, "Expected error: " + this.code + ", got: " + code); + assertEquals(kind == Diagnostic.Kind.ERROR, diagnostic.isError()); if (startPosition != -1) { - assertEquals(diagnostic.getStartPosition(), startPosition, "Start position"); + assertEquals(startPosition, diagnostic.getStartPosition(), "Start position"); } if (endPosition != -1) { - assertEquals(diagnostic.getEndPosition(), endPosition, "End position"); + assertEquals(endPosition, diagnostic.getEndPosition(), "End position"); } if (position != -1) { - assertEquals(diagnostic.getPosition(), position, "Position"); + assertEquals(position, diagnostic.getPosition(), "Position"); } } } diff --git a/test/langtools/jdk/jshell/ExternalEditorTest.java b/test/langtools/jdk/jshell/ExternalEditorTest.java index 607637e207c4..cf1ae4f1ae2d 100644 --- a/test/langtools/jdk/jshell/ExternalEditorTest.java +++ b/test/langtools/jdk/jshell/ExternalEditorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, 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 @@ -27,7 +27,7 @@ * @bug 8143955 8080843 8163816 8143006 8169828 8171130 8162989 8210808 * @modules jdk.jshell/jdk.internal.jshell.tool * @build ReplToolTesting CustomEditor EditorTestBase - * @run testng ExternalEditorTest + * @run junit ExternalEditorTest * @key intermittent */ @@ -47,15 +47,17 @@ import java.util.concurrent.Future; import java.util.function.Consumer; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import org.junit.jupiter.api.AfterAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ExternalEditorTest extends EditorTestBase { private static Path executionScript; @@ -133,21 +135,19 @@ public void testEditor(boolean defaultStartup, String[] args, ReplTest... tests) @Test public void testStatementSemicolonAddition() { - testEditor( - a -> assertCommand(a, "if (true) {}", ""), + testEditor(a -> assertCommand(a, "if (true) {}", ""), a -> assertCommand(a, "if (true) {} else {}", ""), a -> assertCommand(a, "Object o", "o ==> null"), a -> assertCommand(a, "if (true) o = new Object() { int x; }", ""), a -> assertCommand(a, "if (true) o = new Object() { int y; }", ""), a -> assertCommand(a, "System.err.flush()", ""), // test still ; for expression statement a -> assertEditOutput(a, "/ed", "", () -> { - assertEquals(getSource(), - "if (true) {}\n" + + assertEquals( "if (true) {}\n" + "if (true) {} else {}\n" + "Object o;\n" + "if (true) o = new Object() { int x; };\n" + "if (true) o = new Object() { int y; };\n" + - "System.err.flush();\n"); + "System.err.flush();\n", getSource()); exit(); }) ); @@ -173,7 +173,7 @@ private static boolean isWindows() { return System.getProperty("os.name").startsWith("Windows"); } - @BeforeClass + @BeforeAll public static void setUpExternalEditorTest() throws IOException { listener = new ServerSocket(0); listener.setSoTimeout(30000); @@ -250,7 +250,8 @@ public void setUnknownEditor() { ); } - @Test(enabled = false) // TODO 8159229 + @Test // TODO 8159229 + @Disabled public void testRemoveTempFile() { test(new String[]{"--no-startup"}, a -> assertCommandCheckOutput(a, "/set editor " + executionScript, @@ -264,7 +265,7 @@ public void testRemoveTempFile() { ); } - @AfterClass + @AfterAll public static void shutdown() throws IOException { executorShutdown(); if (listener != null) { diff --git a/test/langtools/jdk/jshell/FailOverDirectExecutionControlTest.java b/test/langtools/jdk/jshell/FailOverDirectExecutionControlTest.java index 99457ea2ce6d..c43ec747ffac 100644 --- a/test/langtools/jdk/jshell/FailOverDirectExecutionControlTest.java +++ b/test/langtools/jdk/jshell/FailOverDirectExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -34,7 +34,7 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting ExecutionControlTestBase Compiler - * @run testng FailOverDirectExecutionControlTest + * @run junit FailOverDirectExecutionControlTest * @key intermittent */ @@ -48,16 +48,15 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; import jdk.jshell.execution.FailOverExecutionControlProvider; import jdk.jshell.spi.ExecutionControlProvider; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import org.junit.jupiter.api.AfterEach; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class FailOverDirectExecutionControlTest extends ExecutionControlTestBase { ClassLoader ccl; @@ -93,7 +92,7 @@ public void close() throws SecurityException { } - @BeforeMethod + @BeforeEach @Override public void setUp() { logger = Logger.getLogger("jdk.jshell.execution"); @@ -134,7 +133,7 @@ public void setUp() { setUp(builder -> builder.executionEngine(provider, pm)); } - @AfterMethod + @AfterEach @Override public void tearDown() { super.tearDown(); @@ -144,11 +143,12 @@ public void tearDown() { } @Override + @Test public void variables() { super.variables(); - assertEquals(logged.get(Level.FINEST).size(), 1); - assertEquals(logged.get(Level.FINE).size(), 2); - assertEquals(logged.get(Level.WARNING).size(), 2); + assertEquals(1, logged.get(Level.FINEST).size()); + assertEquals(2, logged.get(Level.FINE).size()); + assertEquals(2, logged.get(Level.WARNING).size()); assertNull(logged.get(Level.SEVERE)); String log = logged.get(Level.WARNING).get(0); assertTrue(log.contains("Failure failover -- 0 = alwaysFailing"), log); diff --git a/test/langtools/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java b/test/langtools/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java index 31011960880d..2e53b11b95a0 100644 --- a/test/langtools/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java +++ b/test/langtools/jdk/jshell/FailOverExecutionControlDyingLaunchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -28,17 +28,15 @@ * @modules jdk.jshell/jdk.jshell.execution * jdk.jshell/jdk.jshell.spi * @build KullaTesting ExecutionControlTestBase DyingRemoteAgent - * @run testng FailOverExecutionControlDyingLaunchTest + * @run junit FailOverExecutionControlDyingLaunchTest * @key intermittent */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class FailOverExecutionControlDyingLaunchTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine( diff --git a/test/langtools/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java b/test/langtools/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java index 9958b7a3284e..0de985b7a28e 100644 --- a/test/langtools/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java +++ b/test/langtools/jdk/jshell/FailOverExecutionControlHangingLaunchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -28,16 +28,14 @@ * @modules jdk.jshell/jdk.jshell.execution * jdk.jshell/jdk.jshell.spi * @build KullaTesting ExecutionControlTestBase - * @run testng FailOverExecutionControlHangingLaunchTest + * @run junit FailOverExecutionControlHangingLaunchTest */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class FailOverExecutionControlHangingLaunchTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine( diff --git a/test/langtools/jdk/jshell/FailOverExecutionControlHangingListenTest.java b/test/langtools/jdk/jshell/FailOverExecutionControlHangingListenTest.java index 4f29bfe9c7a8..6d61bcb0322f 100644 --- a/test/langtools/jdk/jshell/FailOverExecutionControlHangingListenTest.java +++ b/test/langtools/jdk/jshell/FailOverExecutionControlHangingListenTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -28,18 +28,16 @@ * @modules jdk.jshell/jdk.jshell.execution * jdk.jshell/jdk.jshell.spi * @build KullaTesting ExecutionControlTestBase - * @run testng FailOverExecutionControlHangingListenTest + * @run junit FailOverExecutionControlHangingListenTest * @key intermittent */ import java.net.InetAddress; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class FailOverExecutionControlHangingListenTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { String loopback = InetAddress.getLoopbackAddress().getHostAddress(); diff --git a/test/langtools/jdk/jshell/FailOverExecutionControlTest.java b/test/langtools/jdk/jshell/FailOverExecutionControlTest.java index 80dc56d72c48..579029af4c0e 100644 --- a/test/langtools/jdk/jshell/FailOverExecutionControlTest.java +++ b/test/langtools/jdk/jshell/FailOverExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -28,16 +28,14 @@ * @modules jdk.jshell/jdk.jshell.execution * jdk.jshell/jdk.jshell.spi * @build KullaTesting ExecutionControlTestBase - * @run testng FailOverExecutionControlTest + * @run junit FailOverExecutionControlTest */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class FailOverExecutionControlTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("failover:0(expectedFailureNonExistent1), 1(expectedFailureNonExistent2), " diff --git a/test/langtools/jdk/jshell/FileManagerTest.java b/test/langtools/jdk/jshell/FileManagerTest.java index 9e4f063da9dd..c8c6a7dded71 100644 --- a/test/langtools/jdk/jshell/FileManagerTest.java +++ b/test/langtools/jdk/jshell/FileManagerTest.java @@ -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 @@ -25,7 +25,7 @@ * @test 8173845 * @summary test custom file managers * @build KullaTesting TestingInputStream - * @run testng FileManagerTest + * @run junit FileManagerTest */ @@ -37,12 +37,10 @@ import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.StandardJavaFileManager; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertTrue; - -@Test public class FileManagerTest extends KullaTesting { boolean encountered; @@ -100,12 +98,13 @@ public Iterable getLocation(Location location) { } - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(b -> b.fileManager(fm -> new MyFileManager(fm))); } + @Test public void testSnippetMemberAssignment() { assertEval("java.lang.reflect.Array.get(new String[1], 0) == null"); assertTrue(encountered, "java.lang.reflect not encountered"); diff --git a/test/langtools/jdk/jshell/ForwardReferenceImportTest.java b/test/langtools/jdk/jshell/ForwardReferenceImportTest.java index 4e66eaa2196d..4459a424092f 100644 --- a/test/langtools/jdk/jshell/ForwardReferenceImportTest.java +++ b/test/langtools/jdk/jshell/ForwardReferenceImportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -25,18 +25,18 @@ * @test 8173232 * @summary Test of forward referencing of snippets (related to import). * @build KullaTesting TestingInputStream - * @run testng ForwardReferenceImportTest + * @run junit ForwardReferenceImportTest */ import jdk.jshell.Snippet; import jdk.jshell.DeclarationSnippet; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.*; +import org.junit.jupiter.api.Test; -@Test public class ForwardReferenceImportTest extends KullaTesting { + @Test public void testImportDeclare() { Snippet singleImport = importKey(assertEval("import java.util.List;", added(VALID))); Snippet importOnDemand = importKey(assertEval("import java.util.*;", added(VALID))); @@ -57,6 +57,7 @@ public void testImportDeclare() { assertActiveKeys(); } + @Test public void testForwardSingleImportMethodToMethod() { DeclarationSnippet string = methodKey(assertEval("String string() { return format(\"string\"); }", added(RECOVERABLE_DEFINED))); @@ -76,6 +77,7 @@ public void testForwardSingleImportMethodToMethod() { assertActiveKeys(); } + @Test public void testForwardImportMethodOnDemandToMethod() { DeclarationSnippet string = methodKey(assertEval("String string() { return format(\"string\"); }", added(RECOVERABLE_DEFINED))); @@ -95,6 +97,7 @@ public void testForwardImportMethodOnDemandToMethod() { assertActiveKeys(); } + @Test public void testForwardSingleImportFieldToMethod() { DeclarationSnippet pi = methodKey(assertEval("double pi() { return PI; }", added(RECOVERABLE_DEFINED))); @@ -114,6 +117,7 @@ public void testForwardSingleImportFieldToMethod() { assertActiveKeys(); } + @Test public void testForwardImportFieldOnDemandToMethod() { DeclarationSnippet pi = methodKey(assertEval("double pi() { return PI; }", added(RECOVERABLE_DEFINED))); @@ -133,6 +137,7 @@ public void testForwardImportFieldOnDemandToMethod() { assertActiveKeys(); } + @Test public void testForwardSingleImportMethodToClass1() { Snippet a = classKey(assertEval("class A { String s = format(\"%d\", 10); }", added(RECOVERABLE_DEFINED))); @@ -153,6 +158,7 @@ public void testForwardSingleImportMethodToClass1() { ste(a, RECOVERABLE_DEFINED, VALID, false, format)); } + @Test public void testForwardSingleImportMethodToClass2() { Snippet a = classKey(assertEval("class A { String s() { return format(\"%d\", 10); } }", added(RECOVERABLE_DEFINED))); @@ -173,6 +179,7 @@ public void testForwardSingleImportMethodToClass2() { ste(a, RECOVERABLE_DEFINED, VALID, false, format)); } + @Test public void testForwardSingleImportClassToClass1() { Snippet a = classKey(assertEval("class A { static List list; }", added(RECOVERABLE_NOT_DEFINED))); @@ -195,6 +202,7 @@ public void testForwardSingleImportClassToClass1() { ste(a, RECOVERABLE_NOT_DEFINED, VALID, true, list)); } + @Test public void testForwardSingleImportClassToClass2() { Snippet clsA = classKey(assertEval("class A extends ArrayList { }", added(RECOVERABLE_NOT_DEFINED))); @@ -219,6 +227,7 @@ public void testForwardSingleImportClassToClass2() { ste(clsA, RECOVERABLE_NOT_DEFINED, VALID, true, arraylist)); } + @Test public void testForwardImportOnDemandMethodToClass1() { Snippet a = classKey(assertEval("class A { String s = format(\"%d\", 10); }", added(RECOVERABLE_DEFINED))); @@ -241,6 +250,7 @@ public void testForwardImportOnDemandMethodToClass1() { assertEval("x.s;", "\"10\""); } + @Test public void testForwardImportOnDemandMethodToClass2() { Snippet a = classKey(assertEval("class A { String s() { return format(\"%d\", 10); } }", added(RECOVERABLE_DEFINED))); @@ -261,6 +271,7 @@ public void testForwardImportOnDemandMethodToClass2() { ste(a, RECOVERABLE_DEFINED, VALID, false, format)); } + @Test public void testForwardImportOnDemandClassToClass1() { Snippet a = classKey(assertEval("class A { static List list; }", added(RECOVERABLE_NOT_DEFINED))); @@ -282,6 +293,7 @@ public void testForwardImportOnDemandClassToClass1() { ste(a, RECOVERABLE_NOT_DEFINED, VALID, true, list)); } + @Test public void testForwardImportOnDemandClassToClass2() { Snippet clsA = classKey(assertEval("class A extends ArrayList { }", added(RECOVERABLE_NOT_DEFINED))); @@ -305,6 +317,7 @@ public void testForwardImportOnDemandClassToClass2() { ste(vara, RECOVERABLE_NOT_DEFINED, VALID, true, clsA)); } + @Test public void testForwardSingleImportFieldToClass1() { Snippet a = classKey(assertEval("class A { static double pi() { return PI; } }", added(RECOVERABLE_DEFINED))); @@ -326,6 +339,7 @@ public void testForwardSingleImportFieldToClass1() { ste(a, RECOVERABLE_DEFINED, VALID, false, list)); } + @Test public void testForwardSingleImportFieldToClass2() { Snippet a = classKey(assertEval("class A { static double pi = PI; }", added(RECOVERABLE_DEFINED))); @@ -347,6 +361,7 @@ public void testForwardSingleImportFieldToClass2() { ste(a, RECOVERABLE_DEFINED, VALID, true, list)); } + @Test public void testForwardImportOnDemandFieldToClass1() { Snippet a = classKey(assertEval("class A { static double pi() { return PI; } }", added(RECOVERABLE_DEFINED))); @@ -368,6 +383,7 @@ public void testForwardImportOnDemandFieldToClass1() { ste(a, RECOVERABLE_DEFINED, VALID, false, list)); } + @Test public void testForwardImportOnDemandFieldToClass2() { Snippet a = classKey(assertEval("class A { static double pi = PI; }", added(RECOVERABLE_DEFINED))); diff --git a/test/langtools/jdk/jshell/ForwardReferenceTest.java b/test/langtools/jdk/jshell/ForwardReferenceTest.java index a010e9ed31a1..841b1f60a8ec 100644 --- a/test/langtools/jdk/jshell/ForwardReferenceTest.java +++ b/test/langtools/jdk/jshell/ForwardReferenceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -25,7 +25,7 @@ * @test 8173232 8010319 * @summary Test of forward referencing of snippets. * @build KullaTesting TestingInputStream - * @run testng ForwardReferenceTest + * @run junit ForwardReferenceTest */ import java.util.List; @@ -33,17 +33,17 @@ import jdk.jshell.MethodSnippet; import jdk.jshell.VarSnippet; import jdk.jshell.DeclarationSnippet; -import org.testng.annotations.Test; import jdk.jshell.SnippetEvent; import jdk.jshell.UnresolvedReferenceException; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static jdk.jshell.Snippet.Status.*; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class ForwardReferenceTest extends KullaTesting { + @Test public void testOverwriteMethodForwardReferenceClass() { Snippet k1 = methodKey(assertEval("int q(Boo b) { return b.x; }", added(RECOVERABLE_NOT_DEFINED))); @@ -56,6 +56,7 @@ public void testOverwriteMethodForwardReferenceClass() { assertActiveKeys(); } + @Test public void testOverwriteMethodForwardReferenceClassImport() { MethodSnippet k1 = methodKey(assertEval("int ff(List lis) { return lis.size(); }", added(RECOVERABLE_NOT_DEFINED))); @@ -68,6 +69,7 @@ public void testOverwriteMethodForwardReferenceClassImport() { assertActiveKeys(); } + @Test public void testForwardVarToMethod() { DeclarationSnippet t = methodKey(assertEval("int t() { return x; }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(t, RECOVERABLE_DEFINED, "variable x"); @@ -87,6 +89,7 @@ public void testForwardVarToMethod() { assertActiveKeys(); } + @Test public void testForwardMethodToMethod() { Snippet t = methodKey(assertEval("int t() { return f(); }", added(RECOVERABLE_DEFINED))); Snippet f = methodKey(assertEval("int f() { return g(); }", @@ -109,6 +112,7 @@ public void testForwardMethodToMethod() { assertActiveKeys(); } + @Test public void testForwardClassToMethod() { DeclarationSnippet t = methodKey(assertEval("int t() { return new A().f(); }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(t, RECOVERABLE_DEFINED, "class A"); @@ -133,6 +137,7 @@ public void testForwardClassToMethod() { assertActiveKeys(); } + @Test public void testForwardVarToClass() { DeclarationSnippet a = classKey(assertEval("class A { int f() { return g; } }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(a, RECOVERABLE_DEFINED, "variable g"); @@ -150,6 +155,7 @@ public void testForwardVarToClass() { assertActiveKeys(); } + @Test public void testForwardVarToClassGeneric() { DeclarationSnippet a = classKey(assertEval("class A { final T x; A(T v) { this.x = v; } ; T get() { return x; } int core() { return g; } }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(a, RECOVERABLE_DEFINED, "variable g"); @@ -159,9 +165,9 @@ public void testForwardVarToClassGeneric() { SnippetEvent ste = events.get(0); Snippet assn = ste.snippet(); DeclarationSnippet unsn = ((UnresolvedReferenceException) ste.exception()).getSnippet(); - assertEquals(unsn.name(), "A", "Wrong with unresolved"); - assertEquals(getState().unresolvedDependencies(unsn).count(), 1, "Wrong size unresolved"); - assertEquals(getState().diagnostics(unsn).count(), 0L, "Expected no diagnostics"); + assertEquals("A", unsn.name(), "Wrong with unresolved"); + assertEquals(1, getState().unresolvedDependencies(unsn).count(), "Wrong size unresolved"); + assertEquals(0L, getState().diagnostics(unsn).count(), "Expected no diagnostics"); Snippet g = varKey(assertEval("int g = 10;", "10", added(VALID), @@ -174,6 +180,7 @@ public void testForwardVarToClassGeneric() { assertActiveKeys(); } + @Test public void testForwardVarToClassExtendsImplements() { DeclarationSnippet ik = classKey(assertEval("interface I { default int ii() { return 1; } }", added(VALID))); DeclarationSnippet jk = classKey(assertEval("interface J { default int jj() { return 2; } }", added(VALID))); @@ -200,6 +207,7 @@ public void testForwardVarToClassExtendsImplements() { assertActiveKeys(); } + @Test public void testForwardVarToInterface() { DeclarationSnippet i = classKey(assertEval("interface I { default int f() { return x; } }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(i, RECOVERABLE_DEFINED, "variable x"); @@ -215,6 +223,7 @@ public void testForwardVarToInterface() { assertActiveKeys(); } + @Test public void testForwardVarToEnum() { DeclarationSnippet a = classKey(assertEval("enum E { Q, W, E; float ff() { return fff; } }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(a, RECOVERABLE_DEFINED, "variable fff"); @@ -232,6 +241,7 @@ public void testForwardVarToEnum() { assertActiveKeys(); } + @Test public void testForwardMethodToClass() { DeclarationSnippet a = classKey(assertEval("class A { int f() { return g(); } }", added(RECOVERABLE_DEFINED))); assertUnresolvedDependencies1(a, RECOVERABLE_DEFINED, "method g()"); @@ -251,6 +261,7 @@ public void testForwardMethodToClass() { assertActiveKeys(); } + @Test public void testForwardClassToClass1() { Snippet a = classKey(assertEval("class A { B b = new B(); }", added(RECOVERABLE_NOT_DEFINED))); assertDeclareFail("new A().b;", "compiler.err.cant.resolve.location"); @@ -269,6 +280,7 @@ public void testForwardClassToClass1() { assertActiveKeys(); } + @Test public void testForwardClassToClass2() { Snippet a = classKey(assertEval("class A extends B { }", added(RECOVERABLE_NOT_DEFINED))); assertDeclareFail("new A();", "compiler.err.cant.resolve.location"); @@ -287,6 +299,7 @@ public void testForwardClassToClass2() { assertActiveKeys(); } + @Test public void testForwardClassToClass3() { Snippet a = classKey(assertEval("interface A extends B { static int f() { return 10; } }", added(RECOVERABLE_NOT_DEFINED))); assertDeclareFail("A.f();", "compiler.err.cant.resolve.location"); @@ -305,12 +318,14 @@ public void testForwardClassToClass3() { assertActiveKeys(); } + @Test public void testForwardVariable() { assertEval("int f() { return x; }", added(RECOVERABLE_DEFINED)); assertEvalUnresolvedException("f();", "f", 1, 0); assertActiveKeys(); } + @Test public void testLocalClassInUnresolved() { Snippet f = methodKey(assertEval("void f() { class A {} g(); }", added(RECOVERABLE_DEFINED))); assertEval("void g() {}", diff --git a/test/langtools/jdk/jshell/GetResourceTest.java b/test/langtools/jdk/jshell/GetResourceTest.java index f8b2b1af2279..dfba8ed588be 100644 --- a/test/langtools/jdk/jshell/GetResourceTest.java +++ b/test/langtools/jdk/jshell/GetResourceTest.java @@ -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 @@ -27,18 +27,18 @@ * @summary Check that ClassLoader.getResource works as expected in the JShell agent. * @modules jdk.jshell * @build KullaTesting TestingInputStream - * @run testng GetResourceTest + * @run junit GetResourceTest */ import jdk.jshell.Snippet; import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.Status.VALID; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class GetResourceTest extends KullaTesting { + @Test public void checkGetResource() { assertEval("import java.util.Arrays;"); assertEval("boolean match(byte[] data, byte[] snippet) {\n" + @@ -57,6 +57,7 @@ public void checkGetResource() { assertEval("test()", "true"); } + @Test public void checkRedefine() { assertEval("import java.util.Arrays;"); assertEval("boolean match(byte[] data, byte[] snippet) {\n" + @@ -85,6 +86,7 @@ public void checkRedefine() { assertEval("test()", "true"); } + @Test public void checkResourceSize() { assertEval("import java.net.*;"); assertEval("boolean test() throws Exception {\n" + @@ -97,6 +99,7 @@ public void checkResourceSize() { assertEval("test()", "true"); } + @Test public void checkTimestampCheck() { assertEval("import java.net.*;"); assertEval("import java.time.*;"); @@ -138,6 +141,7 @@ public void checkTimestampCheck() { assertEval("nue[0] == nue[2]", "true"); } + @Test public void checkFieldAccess() { assertEval("import java.net.*;"); assertEval("Class c = new Object() {}.getClass().getEnclosingClass();"); @@ -154,6 +158,7 @@ public void checkFieldAccess() { assertEval("connection.getHeaderField(3) == null", "true"); } + @Test public void checkGetResources() { assertEval("import java.net.*;"); assertEval("Class c = new Object() {}.getClass().getEnclosingClass();"); diff --git a/test/langtools/jdk/jshell/HighlightUITest.java b/test/langtools/jdk/jshell/HighlightUITest.java index ede22e8f0107..22403d5ae7e0 100644 --- a/test/langtools/jdk/jshell/HighlightUITest.java +++ b/test/langtools/jdk/jshell/HighlightUITest.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8274148 * @summary Check the UI behavior of snippet highligting @@ -35,18 +35,18 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @compile HighlightUITest.java - * @run testng HighlightUITest + * @run junit HighlightUITest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class HighlightUITest extends UITesting { public HighlightUITest() { super(true); } + @Test public void testHighlight() throws Exception { System.setProperty("test.enable.highlighter", "true"); doRunTest((inputSink, out) -> { diff --git a/test/langtools/jdk/jshell/HistoryTest.java b/test/langtools/jdk/jshell/HistoryTest.java index a07523d54cb2..923d064c18ae 100644 --- a/test/langtools/jdk/jshell/HistoryTest.java +++ b/test/langtools/jdk/jshell/HistoryTest.java @@ -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 @@ -28,7 +28,7 @@ * @modules jdk.internal.le/jdk.internal.org.jline.reader * jdk.jshell/jdk.internal.jshell.tool:+open * @build HistoryTest - * @run testng HistoryTest + * @run junit HistoryTest */ import java.lang.reflect.Field; @@ -37,12 +37,12 @@ import java.util.logging.Level; import java.util.logging.Logger; -import org.testng.annotations.Test; import jdk.internal.jshell.tool.JShellTool; import jdk.internal.jshell.tool.JShellToolBuilder; import jdk.internal.org.jline.reader.History; -import static org.testng.Assert.*; -import org.testng.annotations.BeforeMethod; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HistoryTest extends ReplToolTesting { @@ -180,16 +180,16 @@ public void testReadExistingHistory() { } assertCommand(a, "/exit", ""); }); - assertEquals(prefsMap.get("HISTORY_LINE_00"), "/debug 0"); - assertEquals(prefsMap.get("HISTORY_LINE_01"), "void test() {\\"); - assertEquals(prefsMap.get("HISTORY_LINE_02"), " System.err.println(1);\\"); - assertEquals(prefsMap.get("HISTORY_LINE_03"), " System.err.println(`\\\\\\\\\\"); - assertEquals(prefsMap.get("HISTORY_LINE_04"), " \\\\\\"); - assertEquals(prefsMap.get("HISTORY_LINE_05"), "`);\\"); - assertEquals(prefsMap.get("HISTORY_LINE_06"), "} //test"); - assertEquals(prefsMap.get("HISTORY_LINE_07"), "/debug 0"); - assertEquals(prefsMap.get("HISTORY_LINE_08"), "int i"); - assertEquals(prefsMap.get("HISTORY_LINE_09"), "/exit"); + assertEquals("/debug 0", prefsMap.get("HISTORY_LINE_00")); + assertEquals("void test() {\\", prefsMap.get("HISTORY_LINE_01")); + assertEquals(" System.err.println(1);\\", prefsMap.get("HISTORY_LINE_02")); + assertEquals(" System.err.println(`\\\\\\\\\\", prefsMap.get("HISTORY_LINE_03")); + assertEquals(" \\\\\\", prefsMap.get("HISTORY_LINE_04")); + assertEquals("`);\\", prefsMap.get("HISTORY_LINE_05")); + assertEquals("} //test", prefsMap.get("HISTORY_LINE_06")); + assertEquals("/debug 0", prefsMap.get("HISTORY_LINE_07")); + assertEquals("int i", prefsMap.get("HISTORY_LINE_08")); + assertEquals("/exit", prefsMap.get("HISTORY_LINE_09")); System.err.println("prefsMap: " + prefsMap); } @@ -204,10 +204,10 @@ private History getHistory() throws Exception { private void previousAndAssert(History history, String expected) { assertTrue(history.previous()); - assertEquals(history.current().toString(), expected); + assertEquals(expected, history.current().toString()); } - @BeforeMethod + @BeforeEach public void setUp() { super.setUp(); System.setProperty("jshell.test.allow.incomplete.inputs", "false"); diff --git a/test/langtools/jdk/jshell/HistoryUITest.java b/test/langtools/jdk/jshell/HistoryUITest.java index 42e242fe1e6e..aa10010e270a 100644 --- a/test/langtools/jdk/jshell/HistoryUITest.java +++ b/test/langtools/jdk/jshell/HistoryUITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8178077 8232856 * @summary Check the UI behavior of editing history. @@ -35,18 +35,18 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @compile HistoryUITest.java - * @run testng HistoryUITest + * @run junit HistoryUITest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class HistoryUITest extends UITesting { public HistoryUITest() { super(true); } + @Test public void testPrevNextSnippet() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("void test1() {\nSystem.err.println(1);\n}\n"); @@ -78,6 +78,7 @@ public void testPrevNextSnippet() throws Exception { }); } + @Test public void testReRun() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("System.err.println(\"RAN\");\n"); diff --git a/test/langtools/jdk/jshell/IOTest.java b/test/langtools/jdk/jshell/IOTest.java index 112b956fec31..988b73ec071e 100644 --- a/test/langtools/jdk/jshell/IOTest.java +++ b/test/langtools/jdk/jshell/IOTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,28 +25,29 @@ * @test * @summary Test input/output * @build KullaTesting TestingInputStream - * @run testng IOTest + * @run junit IOTest */ -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; - -@Test public class IOTest extends KullaTesting { String LINE_SEPARATOR = System.getProperty("line.separator"); + @Test public void testOutput() { assertEval("System.out.println(\"Test\");"); - assertEquals(getOutput(), "Test" + LINE_SEPARATOR); + assertEquals("Test" + LINE_SEPARATOR, getOutput()); } + @Test public void testErrorOutput() { assertEval("System.err.println(\"Oops\");"); - assertEquals(getErrorOutput(), "Oops" + LINE_SEPARATOR); + assertEquals("Oops" + LINE_SEPARATOR, getErrorOutput()); } + @Test public void testInput() { setInput("x"); assertEval("(char)System.in.read();", "'x'"); diff --git a/test/langtools/jdk/jshell/IdGeneratorTest.java b/test/langtools/jdk/jshell/IdGeneratorTest.java index e8a38dfe7f05..521c87b02657 100644 --- a/test/langtools/jdk/jshell/IdGeneratorTest.java +++ b/test/langtools/jdk/jshell/IdGeneratorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * 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 * @summary Test custom id generators * @build KullaTesting TestingInputStream - * @run testng IdGeneratorTest + * @run junit IdGeneratorTest */ import java.io.ByteArrayOutputStream; @@ -38,12 +38,10 @@ import jdk.jshell.SnippetEvent; import jdk.jshell.UnresolvedReferenceException; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -@Test public class IdGeneratorTest { public JShell.Builder getBuilder() { @@ -57,6 +55,7 @@ public JShell.Builder getBuilder() { .executionEngine(Presets.TEST_DEFAULT_EXECUTION); } + @Test public void testTempNameGenerator() { JShell.Builder builder = getBuilder().tempVariableNameGenerator(new Supplier() { int count = 0; @@ -69,11 +68,12 @@ public String get() { try (JShell jShell = builder.build()) { for (int i = 0; i < 3; ++i) { VarSnippet v = (VarSnippet) jShell.eval("2 + " + (i + 1)).get(0).snippet(); - assertEquals("temp" + (i + 1), v.name(), "Custom id: "); + assertEquals(v.name(), "temp" + (i + 1), "Custom id: "); } } } + @Test public void testResetTempNameGenerator() { JShell.Builder builder = getBuilder().tempVariableNameGenerator(() -> { throw new AssertionError("Should not be called"); @@ -83,6 +83,7 @@ public void testResetTempNameGenerator() { } } + @Test public void testIdGenerator() { JShell.Builder builder = getBuilder().idGenerator(((snippet, id) -> "custom" + id)); try (JShell jShell = builder.build()) { @@ -99,6 +100,7 @@ private void checkIds(List events) { } } + @Test public void testIdInException() { JShell.Builder builder = getBuilder().idGenerator(((snippet, id) -> "custom" + id)); try (JShell jShell = builder.build()) { @@ -116,6 +118,7 @@ public void testIdInException() { } } + @Test public void testResetIdGenerator() { JShell.Builder builder = getBuilder().idGenerator((sn, id) -> { throw new AssertionError("Should not be called"); diff --git a/test/langtools/jdk/jshell/IgnoreTest.java b/test/langtools/jdk/jshell/IgnoreTest.java index 023b5c99ac89..4350ce0cac30 100644 --- a/test/langtools/jdk/jshell/IgnoreTest.java +++ b/test/langtools/jdk/jshell/IgnoreTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, 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 @@ -26,20 +26,20 @@ * @bug 8129559 8246353 8247456 * @summary Test the ignoring of comments and certain modifiers * @build KullaTesting TestingInputStream - * @run testng IgnoreTest + * @run junit IgnoreTest */ -import org.testng.annotations.Test; import jdk.jshell.MethodSnippet; import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.SubKind.*; +import org.junit.jupiter.api.Test; -@Test public class IgnoreTest extends KullaTesting { + @Test public void testComment() { assertVarKeyMatch("//t1\n int//t2\n x//t3\n =//t4\n 12//t5\n ;//t6\n", true, "x", VAR_DECLARATION_WITH_INITIALIZER_SUBKIND, "int", added(VALID)); @@ -58,6 +58,7 @@ public void testComment() { false, "f", METHOD_SUBKIND, added(VALID)); } + @Test public void testVarModifier() { VarSnippet x1 = varKey(assertEval("public int x1;")); assertVariableDeclSnippet(x1, "x1", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0); @@ -71,6 +72,7 @@ public void testVarModifier() { assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0); } + @Test public void testVarModifierAnnotation() { assertEval("@interface A { int value() default 0; }"); VarSnippet x1 = varKey(assertEval("@A public int x1;")); @@ -85,6 +87,7 @@ public void testVarModifierAnnotation() { assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0); } + @Test public void testVarModifierOtherModifier() { VarSnippet x1 = varKey(assertEval("volatile public int x1;")); assertVariableDeclSnippet(x1, "x1", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0); @@ -98,12 +101,14 @@ public void testVarModifierOtherModifier() { assertVariableDeclSnippet(x5, "x5", "int", VALID, VAR_DECLARATION_SUBKIND, 0, 0); } + @Test public void testMisplacedIgnoredModifier() { assertEvalFail("int public y;"); assertEvalFail("String private x;"); assertEvalFail("(protected 34);"); } + @Test public void testMethodModifier() { MethodSnippet m4 = methodKey(assertEval("static void m4() {}")); assertMethodDeclSnippet(m4, "m4", "()void", VALID, 0, 0); @@ -111,6 +116,7 @@ public void testMethodModifier() { assertMethodDeclSnippet(m5, "m5", "()void", VALID, 0, 0); } + @Test public void testMethodModifierAnnotation() { assertEval("@interface A { int value() default 0; }"); MethodSnippet m4 = methodKey(assertEval("@A static void m4() {}")); @@ -119,6 +125,7 @@ public void testMethodModifierAnnotation() { assertMethodDeclSnippet(m5, "m5", "()void", VALID, 0, 0); } + @Test public void testClassModifier() { TypeDeclSnippet c4 = classKey(assertEval("static class C4 {}")); assertTypeDeclSnippet(c4, "C4", VALID, CLASS_SUBKIND, 0, 0); @@ -126,6 +133,7 @@ public void testClassModifier() { assertTypeDeclSnippet(c5, "C5", VALID, CLASS_SUBKIND, 0, 0); } + @Test public void testInsideModifier() { assertEval("import static java.lang.reflect.Modifier.*;"); assertEval("class C {" diff --git a/test/langtools/jdk/jshell/IllegalArgumentExceptionTest.java b/test/langtools/jdk/jshell/IllegalArgumentExceptionTest.java index 3ba5910e8b59..f43778bb4655 100644 --- a/test/langtools/jdk/jshell/IllegalArgumentExceptionTest.java +++ b/test/langtools/jdk/jshell/IllegalArgumentExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,7 +25,7 @@ * @test * @summary Testing IllegalArgumentException. * @build KullaTesting TestingInputStream IllegalArgumentExceptionTest - * @run testng IllegalArgumentExceptionTest + * @run junit IllegalArgumentExceptionTest */ import java.util.function.Consumer; @@ -33,12 +33,10 @@ import jdk.jshell.DeclarationSnippet; import jdk.jshell.Snippet; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; - -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static jdk.jshell.Snippet.Status.VALID; +import org.junit.jupiter.api.Test; -@Test public class IllegalArgumentExceptionTest extends KullaTesting { private void testIllegalArgumentException(Consumer action) { @@ -54,22 +52,27 @@ private void testIllegalArgumentException(Consumer action) { } } + @Test public void testVarValue() { testIllegalArgumentException((key) -> getState().varValue((VarSnippet) key)); } + @Test public void testStatus() { testIllegalArgumentException((key) -> getState().status(key)); } + @Test public void testDrop() { testIllegalArgumentException((key) -> getState().drop(key)); } + @Test public void testUnresolved() { testIllegalArgumentException((key) -> getState().unresolvedDependencies((DeclarationSnippet) key)); } + @Test public void testDiagnostics() { testIllegalArgumentException((key) -> getState().diagnostics(key)); } diff --git a/test/langtools/jdk/jshell/ImportTest.java b/test/langtools/jdk/jshell/ImportTest.java index e09490052cff..a3d61ed691b9 100644 --- a/test/langtools/jdk/jshell/ImportTest.java +++ b/test/langtools/jdk/jshell/ImportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -23,14 +23,14 @@ /* * @test - * @bug 8141415 + * @bug 8141415 8129418 * @summary Test imports * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap * @library /tools/lib * @build KullaTesting TestingInputStream toolbox.Task.ExpectedDiagnostic - * @run testng ImportTest + * @run junit ImportTest */ import java.nio.file.Path; @@ -39,7 +39,6 @@ import javax.tools.Diagnostic; import jdk.jshell.Snippet; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.Status.OVERWRITTEN; @@ -47,10 +46,13 @@ import static jdk.jshell.Snippet.SubKind.SINGLE_STATIC_IMPORT_SUBKIND; import static jdk.jshell.Snippet.SubKind.TYPE_IMPORT_ON_DEMAND_SUBKIND; import static jdk.jshell.Snippet.SubKind.STATIC_IMPORT_ON_DEMAND_SUBKIND; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; -@Test public class ImportTest extends KullaTesting { + @Test public void testImport() { assertImportKeyMatch("import java.util.List;", "List", SINGLE_TYPE_IMPORT_SUBKIND, added(VALID)); assertImportKeyMatch("import java.util.ArrayList;", "ArrayList", SINGLE_TYPE_IMPORT_SUBKIND, added(VALID)); @@ -59,6 +61,7 @@ public void testImport() { assertEval("list.size();", "1"); } + @Test public void testImportOnDemand() { assertImportKeyMatch("import java.util.*;", "java.util.*", TYPE_IMPORT_ON_DEMAND_SUBKIND, added(VALID)); assertEval("List list = new ArrayList<>();"); @@ -66,40 +69,46 @@ public void testImportOnDemand() { assertEval("list.size();", "1"); } + @Test public void testImportStatic() { assertImportKeyMatch("import static java.lang.Math.PI;", "PI", SINGLE_STATIC_IMPORT_SUBKIND, added(VALID)); assertEval("Double.valueOf(PI).toString().substring(0, 16).equals(\"3.14159265358979\");", "true"); } + @Test public void testImportStaticOnDemand() { assertImportKeyMatch("import static java.lang.Math.*;", "java.lang.Math.*", STATIC_IMPORT_ON_DEMAND_SUBKIND, added(VALID)); assertEval("abs(cos(PI / 2)) < 0.00001;", "true"); } - @Test(enabled = false) // TODO 8129418 + @Test public void testUnknownPackage() { assertDeclareFail("import unknown.qqq;", new ExpectedDiagnostic("compiler.err.doesnt.exist", 7, 18, 14, -1, -1, Diagnostic.Kind.ERROR)); assertDeclareFail("import unknown.*;", - new ExpectedDiagnostic("compiler.err.doesnt.exist", 7, 15, 7, -1, -1, Diagnostic.Kind.ERROR)); + new ExpectedDiagnostic("compiler.err.doesnt.exist", 7, 14, 7, -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void testBogusImportIgnoredInFuture() { assertDeclareFail("import unknown.qqq;", "compiler.err.doesnt.exist"); assertDeclareFail("import unknown.*;", "compiler.err.doesnt.exist"); assertEval("2 + 2;"); } + @Test public void testBadImport() { assertDeclareFail("import static java.lang.reflect.Modifier;", new ExpectedDiagnostic("compiler.err.cant.resolve.location", 14, 31, 23, -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void testBadSyntaxImport() { assertDeclareFail("import not found.*;", new ExpectedDiagnostic("compiler.err.expected", 10, 10, 10, -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void testImportRedefinition() { Compiler compiler = new Compiler(); Path path = Paths.get("testImport"); @@ -140,6 +149,7 @@ public void testImportRedefinition() { assertEval("new ArrayList();", "MyInnerList"); } + @Test public void testImportMemberRedefinition() { Compiler compiler = new Compiler(); Path path = Paths.get("testImport"); @@ -164,6 +174,7 @@ public void testImportMemberRedefinition() { assertEval("method();", "\"A\""); } + @Test public void testImportWithComment() { assertImportKeyMatch("import java.util.List;//comment", "List", SINGLE_TYPE_IMPORT_SUBKIND, added(VALID)); assertEval("List l = null;"); diff --git a/test/langtools/jdk/jshell/InaccessibleExpressionTest.java b/test/langtools/jdk/jshell/InaccessibleExpressionTest.java index 9e6c95fd3f71..db82067d3dea 100644 --- a/test/langtools/jdk/jshell/InaccessibleExpressionTest.java +++ b/test/langtools/jdk/jshell/InaccessibleExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -29,23 +29,21 @@ * jdk.jdeps/com.sun.tools.javap * @library /tools/lib * @build KullaTesting Compiler - * @run testng InaccessibleExpressionTest + * @run junit InaccessibleExpressionTest */ import java.nio.file.Path; import java.nio.file.Paths; -import org.testng.annotations.BeforeMethod; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; - -@Test public class InaccessibleExpressionTest extends KullaTesting { - @BeforeMethod + @BeforeEach @Override public void setUp() { Path path = Paths.get("eit"); @@ -76,20 +74,22 @@ public void setUp() { .compilerOptions("--class-path", tpath)); } + @Test public void testExternal() { assertEval("import static priv.GetPriv.*;"); VarSnippet down = varKey(assertEval("down()", "Packp")); - assertEquals(down.typeName(), "priv.Packp"); + assertEquals("priv.Packp", down.typeName()); assertEval(down.name() + ".get()", "5"); VarSnippet list = varKey(assertEval("list()", "[]")); - assertEquals(list.typeName(), "priv.MyList"); + assertEquals("priv.MyList", list.typeName()); assertEval(list.name() + ".size()", "0"); VarSnippet one = varKey(assertEval("priv()", "One")); - assertEquals(one.typeName(), "priv.GetPriv.Count"); + assertEquals("priv.GetPriv.Count", one.typeName()); assertEval("var v = down();", "Packp"); assertDeclareFail("v.toString()", "compiler.err.not.def.access.class.intf.cant.access"); } + @Test public void testInternal() { assertEval( "class Top {" + @@ -98,7 +98,7 @@ public void testInternal() { " }" + " Inner n = new Inner(); }"); VarSnippet n = varKey(assertEval("new Top().n", "Inner")); - assertEquals(n.typeName(), "Top.Inner"); + assertEquals("Top.Inner", n.typeName()); } } diff --git a/test/langtools/jdk/jshell/IndentUITest.java b/test/langtools/jdk/jshell/IndentUITest.java index 6858277a179f..a771b9b10318 100644 --- a/test/langtools/jdk/jshell/IndentUITest.java +++ b/test/langtools/jdk/jshell/IndentUITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 8241950 8247932 * @summary Check the UI behavior of indentation @@ -35,18 +35,18 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @compile IndentUITest.java - * @run testng IndentUITest + * @run junit IndentUITest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class IndentUITest extends UITesting { public IndentUITest() { super(true); } + @Test public void testIdent() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("void test1() {\nSystem.err.println(1);\n}\n"); diff --git a/test/langtools/jdk/jshell/InferTypeTest.java b/test/langtools/jdk/jshell/InferTypeTest.java index 080697666a29..a1455306f45e 100644 --- a/test/langtools/jdk/jshell/InferTypeTest.java +++ b/test/langtools/jdk/jshell/InferTypeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -30,14 +30,14 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap * @build KullaTesting TestingInputStream toolbox.ToolBox Compiler - * @run testng InferTypeTest + * @run junit InferTypeTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class InferTypeTest extends KullaTesting { + @Test public void testTypeInference() { assertInferredType("1", "int"); assertEval("import java.util.*;"); diff --git a/test/langtools/jdk/jshell/JShellQueryTest.java b/test/langtools/jdk/jshell/JShellQueryTest.java index 352e639a29c4..e487c294f3b1 100644 --- a/test/langtools/jdk/jshell/JShellQueryTest.java +++ b/test/langtools/jdk/jshell/JShellQueryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,21 +26,21 @@ * @bug 8143964 * @summary test queries to the JShell that return Streams * @build KullaTesting - * @run testng JShellQueryTest + * @run junit JShellQueryTest */ import jdk.jshell.Snippet; -import org.testng.annotations.Test; import jdk.jshell.ImportSnippet; import jdk.jshell.MethodSnippet; import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; import static java.util.stream.Collectors.joining; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -@Test public class JShellQueryTest extends KullaTesting { + @Test public void testSnippets() { assertStreamMatch(getState().snippets()); VarSnippet sx = varKey(assertEval("int x = 5;")); @@ -54,6 +54,7 @@ public void testSnippets() { assertStreamMatch(getState().snippets(), sx, sfoo, smm, svv, sc, si, simp); } + @Test public void testVars() { assertStreamMatch(getState().variables()); VarSnippet sx = varKey(assertEval("int x = 5;")); @@ -67,6 +68,7 @@ public void testVars() { assertStreamMatch(getState().variables(), sx, sfoo); } + @Test public void testMethods() { assertStreamMatch(getState().methods()); VarSnippet sx = varKey(assertEval("int x = 5;")); @@ -79,6 +81,7 @@ public void testMethods() { assertStreamMatch(getState().methods(), smm, svv); } + @Test public void testTypes() { assertStreamMatch(getState().types()); VarSnippet sx = varKey(assertEval("int x = 5;")); @@ -91,6 +94,7 @@ public void testTypes() { assertStreamMatch(getState().types(), sc, si); } + @Test public void testImports() { assertStreamMatch(getState().imports()); VarSnippet sx = varKey(assertEval("int x = 5;")); @@ -103,6 +107,7 @@ public void testImports() { assertStreamMatch(getState().imports(), simp); } + @Test public void testDiagnostics() { Snippet sx = varKey(assertEval("int x = 5;")); assertStreamMatch(getState().diagnostics(sx)); @@ -110,9 +115,10 @@ public void testDiagnostics() { String res = getState().diagnostics(broken) .map(d -> d.getCode()) .collect(joining("+")); - assertEquals(res, "compiler.err.cant.resolve.location.args+compiler.err.prob.found.req"); + assertEquals("compiler.err.cant.resolve.location.args+compiler.err.prob.found.req", res); } + @Test public void testUnresolvedDependencies() { VarSnippet sx = varKey(assertEval("int x = 5;")); assertStreamMatch(getState().unresolvedDependencies(sx)); diff --git a/test/langtools/jdk/jshell/JShellStateClosedTest.java b/test/langtools/jdk/jshell/JShellStateClosedTest.java index 2f8d12156671..62044dc1f2f1 100644 --- a/test/langtools/jdk/jshell/JShellStateClosedTest.java +++ b/test/langtools/jdk/jshell/JShellStateClosedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,7 +25,7 @@ * @test 8164277 * @summary Testing IllegalStateException. * @build KullaTesting TestingInputStream JShellStateClosedTest - * @run testng JShellStateClosedTest + * @run junit JShellStateClosedTest */ import java.util.function.Consumer; @@ -36,11 +36,9 @@ import jdk.jshell.Snippet; import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.fail; - -@Test public class JShellStateClosedTest extends KullaTesting { private void testStateClosedException(Runnable action) { @@ -53,6 +51,7 @@ private void testStateClosedException(Runnable action) { } } + @Test public void testClasses() { TypeDeclSnippet sc = classKey(assertEval("class C { }")); TypeDeclSnippet si = classKey(assertEval("interface I { }")); @@ -60,6 +59,7 @@ public void testClasses() { assertStreamMatch(getState().types(), sc, si); } + @Test public void testVariables() { VarSnippet sx = varKey(assertEval("int x = 5;")); VarSnippet sfoo = varKey(assertEval("String foo;")); @@ -67,6 +67,7 @@ public void testVariables() { assertStreamMatch(getState().variables(), sx, sfoo); } + @Test public void testMethods() { MethodSnippet smm = methodKey(assertEval("int mm() { return 6; }")); MethodSnippet svv = methodKey(assertEval("void vv() { }")); @@ -74,12 +75,14 @@ public void testMethods() { assertStreamMatch(getState().methods(), smm, svv); } + @Test public void testImports() { ImportSnippet simp = importKey(assertEval("import java.lang.reflect.*;")); getState().close(); assertStreamMatch(getState().imports(), simp); } + @Test public void testSnippets() { VarSnippet sx = varKey(assertEval("int x = 5;")); VarSnippet sfoo = varKey(assertEval("String foo;")); @@ -92,6 +95,7 @@ public void testSnippets() { assertStreamMatch(getState().snippets(), sx, sfoo, smm, svv, sc, si, simp); } + @Test public void testEval() { testStateClosedException(() -> getState().eval("int a;")); } @@ -117,22 +121,27 @@ private void testStateClosedWithoutException(Consumer action) { } } + @Test public void testStatus() { testStateClosedWithoutException((key) -> getState().status(key)); } + @Test public void testVarValue() { testStateClosedException((key) -> getState().varValue((VarSnippet) key)); } + @Test public void testDrop() { testStateClosedException((key) -> getState().drop(key)); } + @Test public void testUnresolved() { testStateClosedWithoutException((key) -> getState().unresolvedDependencies((DeclarationSnippet) key)); } + @Test public void testDiagnostics() { testStateClosedWithoutException((key) -> getState().diagnostics(key)); } diff --git a/test/langtools/jdk/jshell/JavadocTest.java b/test/langtools/jdk/jshell/JavadocTest.java index 184921adf9a9..463c23a4f31a 100644 --- a/test/langtools/jdk/jshell/JavadocTest.java +++ b/test/langtools/jdk/jshell/JavadocTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -31,7 +31,7 @@ * jdk.jshell/jdk.jshell:open * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng JavadocTest + * @run junit JavadocTest */ import java.io.IOException; @@ -43,13 +43,13 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class JavadocTest extends KullaTesting { private final Compiler compiler = new Compiler(); + @Test public void testJavadoc() { prepareZip(); assertJavadoc("test.Clazz|", "test.Clazz\n" + @@ -65,6 +65,7 @@ public void testJavadoc() { assertJavadoc("clz.undef|"); } + @Test public void testVariableInRepl() { assertEval("Object o;"); assertSignature("o|", "o:java.lang.Object"); @@ -107,6 +108,7 @@ private void prepareZip() { addToClasspath(compiler.getClassDir()); } + @Test public void testCollectionsMin() { prepareJavaUtilZip(); assertJavadoc("java.util.Collections.min(|", diff --git a/test/langtools/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java b/test/langtools/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java index 199964abb0bf..c45370c1a549 100644 --- a/test/langtools/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiBadOptionLaunchExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,22 +26,22 @@ * @bug 8169519 8166581 * @summary Tests for JDI connector failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution - * @run testng JdiBadOptionLaunchExecutionControlTest + * @run junit JdiBadOptionLaunchExecutionControlTest */ import java.util.logging.Level; import java.util.logging.Logger; -import org.testng.annotations.Test; import jdk.jshell.JShell; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiBadOptionLaunchExecutionControlTest { private static final String EXPECTED_ERROR = "Launching JShell execution engine threw: Failed remote launch: java.util.concurrent.ExecutionException: com.sun.jdi.connect.VMStartException: VM initialization failed"; + @Test public void badOptionLaunchTest() { try { // turn on logging of launch failures diff --git a/test/langtools/jdk/jshell/JdiBadOptionListenExecutionControlTest.java b/test/langtools/jdk/jshell/JdiBadOptionListenExecutionControlTest.java index bdf05c7bd7fb..422c6c18b756 100644 --- a/test/langtools/jdk/jshell/JdiBadOptionListenExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiBadOptionListenExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,22 +26,22 @@ * @bug 8169519 8166581 * @summary Tests for JDI connector failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution - * @run testng JdiBadOptionListenExecutionControlTest + * @run junit JdiBadOptionListenExecutionControlTest */ import java.util.logging.Level; import java.util.logging.Logger; -import org.testng.annotations.Test; import jdk.jshell.JShell; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiBadOptionListenExecutionControlTest { private static final String EXPECTED_ERROR = "Unrecognized option: -BadBadOption"; + @Test public void badOptionListenTest() { try { // turn on logging of launch failures diff --git a/test/langtools/jdk/jshell/JdiBogusHostListenExecutionControlTest.java b/test/langtools/jdk/jshell/JdiBogusHostListenExecutionControlTest.java index 03659952279e..7f0924229b73 100644 --- a/test/langtools/jdk/jshell/JdiBogusHostListenExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiBogusHostListenExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,17 +26,16 @@ * @bug 8169519 8168615 8176474 * @summary Tests for JDI connector failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution - * @run testng JdiBogusHostListenExecutionControlTest + * @run junit JdiBogusHostListenExecutionControlTest */ import java.util.logging.Level; import java.util.logging.Logger; -import org.testng.annotations.Test; import jdk.jshell.JShell; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiBogusHostListenExecutionControlTest { private static final String EXPECTED_ERROR = @@ -44,6 +43,7 @@ public class JdiBogusHostListenExecutionControlTest { private static final String EXPECTED_LOCATION = "@ com.sun.jdi.SocketListen"; + @Test public void badOptionListenTest() { try { // turn on logging of launch failures diff --git a/test/langtools/jdk/jshell/JdiFailingLaunchExecutionControlTest.java b/test/langtools/jdk/jshell/JdiFailingLaunchExecutionControlTest.java index 288983a05e52..6ce9df1ccf44 100644 --- a/test/langtools/jdk/jshell/JdiFailingLaunchExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiFailingLaunchExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,19 +27,19 @@ * @summary Tests for JDI connector failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution * @build DyingRemoteAgent - * @run testng JdiFailingLaunchExecutionControlTest + * @run junit JdiFailingLaunchExecutionControlTest */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiFailingLaunchExecutionControlTest { private static final String EXPECTED_ERROR = "Launching JShell execution engine threw: Accept timed out"; + @Test public void failLaunchTest() { try { System.err.printf("Unexpected return value: %s\n", DyingRemoteAgent.state(true, null).eval("33;")); diff --git a/test/langtools/jdk/jshell/JdiFailingListenExecutionControlTest.java b/test/langtools/jdk/jshell/JdiFailingListenExecutionControlTest.java index aaa3357a754f..d8b524585519 100644 --- a/test/langtools/jdk/jshell/JdiFailingListenExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiFailingListenExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,19 +27,19 @@ * @summary Tests for JDI connector failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution * @build DyingRemoteAgent - * @run testng JdiFailingListenExecutionControlTest + * @run junit JdiFailingListenExecutionControlTest */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiFailingListenExecutionControlTest { private static final String EXPECTED_ERROR = "Launching JShell execution engine threw: Accept timed out"; + @Test public void failListenTest() { try { System.err.printf("Unexpected return value: %s\n", DyingRemoteAgent.state(true, null).eval("33;")); diff --git a/test/langtools/jdk/jshell/JdiHangingLaunchExecutionControlTest.java b/test/langtools/jdk/jshell/JdiHangingLaunchExecutionControlTest.java index 577228d48209..a0c0751395d2 100644 --- a/test/langtools/jdk/jshell/JdiHangingLaunchExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiHangingLaunchExecutionControlTest.java @@ -27,19 +27,19 @@ * @summary Tests for JDI connector timeout failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution * @build HangingRemoteAgent - * @run testng JdiHangingLaunchExecutionControlTest + * @run junit JdiHangingLaunchExecutionControlTest */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiHangingLaunchExecutionControlTest { private static final String EXPECTED_ERROR = "Launching JShell execution engine threw: Accept timed out"; + @Test public void hangLaunchTimeoutTest() { try { System.err.printf("Unexpected return value: %s\n", diff --git a/test/langtools/jdk/jshell/JdiHangingListenExecutionControlTest.java b/test/langtools/jdk/jshell/JdiHangingListenExecutionControlTest.java index 2e9b04a634b2..2013b0809a25 100644 --- a/test/langtools/jdk/jshell/JdiHangingListenExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiHangingListenExecutionControlTest.java @@ -27,20 +27,20 @@ * @summary Tests for JDI connector timeout failure * @modules jdk.jshell/jdk.jshell jdk.jshell/jdk.jshell.spi jdk.jshell/jdk.jshell.execution * @build HangingRemoteAgent - * @run testng JdiHangingListenExecutionControlTest + * @run junit JdiHangingListenExecutionControlTest * @key intermittent */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Test; -@Test public class JdiHangingListenExecutionControlTest { private static final String EXPECTED_ERROR = "Launching JShell execution engine threw: Accept timed out"; + @Test public void hangListenTimeoutTest() { try { System.err.printf("Unexpected return value: %s\n", diff --git a/test/langtools/jdk/jshell/JdiLaunchingExecutionControlTest.java b/test/langtools/jdk/jshell/JdiLaunchingExecutionControlTest.java index af9dce89bcf4..35261ff6fa1a 100644 --- a/test/langtools/jdk/jshell/JdiLaunchingExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiLaunchingExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,18 +27,16 @@ * @summary Tests for standard JDI connector (without failover) -- launching * @modules jdk.jshell/jdk.jshell.execution * @build KullaTesting ExecutionControlTestBase - * @run testng JdiLaunchingExecutionControlTest + * @run junit JdiLaunchingExecutionControlTest * @key intermittent */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class JdiLaunchingExecutionControlTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("jdi:launch(true)")); diff --git a/test/langtools/jdk/jshell/JdiListeningExecutionControlTest.java b/test/langtools/jdk/jshell/JdiListeningExecutionControlTest.java index 700ec077e34f..3cc2a9785a3c 100644 --- a/test/langtools/jdk/jshell/JdiListeningExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiListeningExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,18 +27,16 @@ * @summary Tests for alternate JDI connector -- listening * @modules jdk.jshell/jdk.jshell.execution * @build KullaTesting ExecutionControlTestBase - * @run testng JdiListeningExecutionControlTest + * @run junit JdiListeningExecutionControlTest * @key intermittent */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class JdiListeningExecutionControlTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("jdi")); diff --git a/test/langtools/jdk/jshell/JdiListeningLocalhostExecutionControlTest.java b/test/langtools/jdk/jshell/JdiListeningLocalhostExecutionControlTest.java index 241774d639e0..2e38e9f9aaef 100644 --- a/test/langtools/jdk/jshell/JdiListeningLocalhostExecutionControlTest.java +++ b/test/langtools/jdk/jshell/JdiListeningLocalhostExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,18 +27,16 @@ * @summary Tests for alternate JDI connector -- listening to "localhost" * @modules jdk.jshell/jdk.jshell.execution * @build KullaTesting ExecutionControlTestBase - * @run testng JdiListeningLocalhostExecutionControlTest + * @run junit JdiListeningLocalhostExecutionControlTest * @key intermittent */ -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; -@Test public class JdiListeningLocalhostExecutionControlTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("jdi:hostname(localhost)")); diff --git a/test/langtools/jdk/jshell/KullaCompletenessStressTest.java b/test/langtools/jdk/jshell/KullaCompletenessStressTest.java index e79e043dd10c..16274fa924e0 100644 --- a/test/langtools/jdk/jshell/KullaCompletenessStressTest.java +++ b/test/langtools/jdk/jshell/KullaCompletenessStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved. * 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,15 @@ * @summary Test SourceCodeAnalysis * @modules jdk.compiler/com.sun.tools.javac.api * @build KullaTesting TestingInputStream KullaCompletenessStressTest CompletenessStressTest - * @run testng KullaCompletenessStressTest + * @run junit KullaCompletenessStressTest */ import java.io.File; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.TestInstance; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class KullaCompletenessStressTest extends CompletenessStressTest { @Override public File[] getDirectoriesToTest() { @@ -44,11 +45,10 @@ public File[] getDirectoriesToTest() { } else { file = new File(src, "../../../src/jdk.jshell/share/classes"); } - if (!file.exists()) { - System.out.println("jdk.jshell sources are not exist. Test has been skipped. Path: " + file.toString()); - return new File[]{}; - }else { - return new File[]{file}; - } + + Assumptions.assumeTrue(file.exists(), + "jdk.jshell sources are not exist. Test has been skipped. Path: " + file.toString()); + + return new File[]{file}; } } diff --git a/test/langtools/jdk/jshell/KullaTesting.java b/test/langtools/jdk/jshell/KullaTesting.java index d74f3484f4bd..9689b812e0ae 100644 --- a/test/langtools/jdk/jshell/KullaTesting.java +++ b/test/langtools/jdk/jshell/KullaTesting.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -71,8 +71,6 @@ import jdk.jshell.SourceCodeAnalysis.QualifiedNames; import jdk.jshell.SourceCodeAnalysis.Suggestion; import jdk.jshell.UnresolvedReferenceException; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; import jdk.jshell.Diag; @@ -80,9 +78,11 @@ import static java.util.stream.Collectors.toSet; import static jdk.jshell.Snippet.Status.*; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import static jdk.jshell.Snippet.SubKind.METHOD_SUBKIND; import jdk.jshell.SourceCodeAnalysis.Documentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; public class KullaTesting { @@ -166,7 +166,7 @@ public void addToClasspath(Path path) { addToClasspath(path.toString()); } - @BeforeMethod + @BeforeEach public void setUp() { setUp(b -> {}); } @@ -202,7 +202,7 @@ public int read(byte[] b, int off, int len) throws IOException { idToSnippet = new LinkedHashMap<>(); } - @AfterMethod + @AfterEach public void tearDown() { if (state != null) state.close(); state = null; @@ -226,16 +226,16 @@ public ClassLoader createAndRunFromModule(String moduleName, Path modPath) { public List assertUnresolvedDependencies(DeclarationSnippet key, int unresolvedSize) { List unresolved = getState().unresolvedDependencies(key).collect(toList()); - assertEquals(unresolved.size(), unresolvedSize, "Input: " + key.source() + ", checking unresolved: "); + assertEquals(unresolvedSize, unresolved.size(), "Input: " + key.source() + ", checking unresolved: "); return unresolved; } public DeclarationSnippet assertUnresolvedDependencies1(DeclarationSnippet key, Status status, String name) { List unresolved = assertUnresolvedDependencies(key, 1); String input = key.source(); - assertEquals(unresolved.size(), 1, "Given input: " + input + ", checking unresolved"); - assertEquals(unresolved.get(0), name, "Given input: " + input + ", checking unresolved: "); - assertEquals(getState().status(key), status, "Given input: " + input + ", checking status: "); + assertEquals(1, unresolved.size(), "Given input: " + input + ", checking unresolved"); + assertEquals(name, unresolved.get(0), "Given input: " + input + ", checking unresolved: "); + assertEquals(status, getState().status(key), "Given input: " + input + ", checking status: "); return key; } @@ -243,24 +243,24 @@ public DeclarationSnippet assertEvalUnresolvedException(String input, String nam List events = assertEval(input, null, UnresolvedReferenceException.class, DiagCheck.DIAG_OK, DiagCheck.DIAG_OK, null); SnippetEvent ste = events.get(0); DeclarationSnippet sn = ((UnresolvedReferenceException) ste.exception()).getSnippet(); - assertEquals(sn.name(), name, "Given input: " + input + ", checking name"); - assertEquals(getState().unresolvedDependencies(sn).count(), unresolvedSize, "Given input: " + input + ", checking unresolved"); - assertEquals(getState().diagnostics(sn).count(), (long) diagnosticsSize, "Given input: " + input + ", checking diagnostics"); + assertEquals(name, sn.name(), "Given input: " + input + ", checking name"); + assertEquals(unresolvedSize, getState().unresolvedDependencies(sn).count(), "Given input: " + input + ", checking unresolved"); + assertEquals((long) diagnosticsSize, getState().diagnostics(sn).count(), "Given input: " + input + ", checking diagnostics"); return sn; } public Snippet assertKeyMatch(String input, boolean isExecutable, SubKind expectedSubKind, STEInfo mainInfo, STEInfo... updates) { Snippet key = key(assertEval(input, IGNORE_VALUE, mainInfo, updates)); String source = key.source(); - assertEquals(source, input, "Key \"" + input + "\" source mismatch, got: " + source + ", expected: " + input); + assertEquals(input, source, "Key \"" + input + "\" source mismatch, got: " + source + ", expected: " + input); SubKind subkind = key.subKind(); - assertEquals(subkind, expectedSubKind, "Key \"" + input + "\" subkind mismatch, got: " + assertEquals(expectedSubKind, subkind, "Key \"" + input + "\" subkind mismatch, got: " + subkind + ", expected: " + expectedSubKind); - assertEquals(subkind.isExecutable(), isExecutable, "Key \"" + input + "\", expected isExecutable: " + assertEquals(isExecutable, subkind.isExecutable(), "Key \"" + input + "\", expected isExecutable: " + isExecutable + ", got: " + subkind.isExecutable()); Snippet.Kind expectedKind = getKind(key); - assertEquals(key.kind(), expectedKind, "Checking kind: "); - assertEquals(expectedSubKind.kind(), expectedKind, "Checking kind: "); + assertEquals(expectedKind, key.kind(), "Checking kind: "); + assertEquals(expectedKind, expectedSubKind.kind(), "Checking kind: "); return key; } @@ -309,9 +309,9 @@ public ImportSnippet assertImportKeyMatch(String input, String name, SubKind sub assertTrue(key instanceof ImportSnippet, "Expected an ImportKey, got: " + key.getClass().getName()); ImportSnippet importKey = (ImportSnippet) key; - assertEquals(importKey.name(), name, "Input \"" + input + + assertEquals(name, importKey.name(), "Input \"" + input + "\" name mismatch, got: " + importKey.name() + ", expected: " + name); - assertEquals(importKey.kind(), Kind.IMPORT, "Checking kind: "); + assertEquals(Kind.IMPORT, importKey.kind(), "Checking kind: "); return importKey; } @@ -320,7 +320,7 @@ public DeclarationSnippet assertDeclarationKeyMatch(String input, boolean isExec assertTrue(key instanceof DeclarationSnippet, "Expected a DeclarationKey, got: " + key.getClass().getName()); DeclarationSnippet declKey = (DeclarationSnippet) key; - assertEquals(declKey.name(), name, "Input \"" + input + + assertEquals(name, declKey.name(), "Input \"" + input + "\" name mismatch, got: " + declKey.name() + ", expected: " + name); return declKey; } @@ -330,9 +330,9 @@ public VarSnippet assertVarKeyMatch(String input, boolean isExecutable, String n assertTrue(sn instanceof VarSnippet, "Expected a VarKey, got: " + sn.getClass().getName()); VarSnippet variableKey = (VarSnippet) sn; String signature = variableKey.typeName(); - assertEquals(signature, typeName, "Key \"" + input + + assertEquals(typeName, signature, "Key \"" + input + "\" typeName mismatch, got: " + signature + ", expected: " + typeName); - assertEquals(variableKey.kind(), Kind.VAR, "Checking kind: "); + assertEquals(Kind.VAR, variableKey.kind(), "Checking kind: "); return variableKey; } @@ -340,11 +340,11 @@ public void assertExpressionKeyMatch(String input, String name, SubKind kind, St Snippet key = assertKeyMatch(input, true, kind, added(VALID)); assertTrue(key instanceof ExpressionSnippet, "Expected a ExpressionKey, got: " + key.getClass().getName()); ExpressionSnippet exprKey = (ExpressionSnippet) key; - assertEquals(exprKey.name(), name, "Input \"" + input + + assertEquals(name, exprKey.name(), "Input \"" + input + "\" name mismatch, got: " + exprKey.name() + ", expected: " + name); - assertEquals(exprKey.typeName(), typeName, "Key \"" + input + + assertEquals(typeName, exprKey.typeName(), "Key \"" + input + "\" typeName mismatch, got: " + exprKey.typeName() + ", expected: " + typeName); - assertEquals(exprKey.kind(), Kind.EXPRESSION, "Checking kind: "); + assertEquals(Kind.EXPRESSION, exprKey.kind(), "Checking kind: "); } // For expressions throwing an EvalException @@ -402,7 +402,7 @@ public List assertEval(String input, void assertStreamMatch(Stream result, T... expected) { Set sns = result.collect(toSet()); Set exp = Stream.of(expected).collect(toSet()); - assertEquals(sns, exp); + assertEquals(exp, sns); } private Map closure(List events) { @@ -483,9 +483,9 @@ private List checkEvents(Supplier> toTest, }); List events = toTest.get(); getState().unsubscribe(token); - assertEquals(dispatched.size(), events.size(), "dispatched event size not the same as event size"); + assertEquals(events.size(), dispatched.size(), "dispatched event size not the same as event size"); for (int i = events.size() - 1; i >= 0; --i) { - assertEquals(dispatched.get(i), events.get(i), "Event element " + i + " does not match"); + assertEquals(events.get(i), dispatched.get(i), "Event element " + i + " does not match"); } dispatched.add(null); // mark end of dispatchs @@ -499,11 +499,11 @@ private List checkEvents(Supplier> toTest, if (old != null) { switch (evt.status()) { case DROPPED: - assertEquals(old, evt.snippet(), + assertEquals(evt.snippet(), old, "Drop: Old snippet must be what is dropped -- input: " + descriptor); break; case OVERWRITTEN: - assertEquals(old, evt.snippet(), + assertEquals(evt.snippet(), old, "Overwrite: Old snippet (" + old + ") must be what is overwritten -- input: " + descriptor + " -- " + evt); @@ -511,12 +511,12 @@ private List checkEvents(Supplier> toTest, default: if (evt.causeSnippet() == null) { // New source - assertNotEquals(old, evt.snippet(), + assertNotEquals(evt.snippet(), old, "New source: Old snippet must be different from the replacing -- input: " + descriptor); } else { // An update (key Overwrite??) - assertEquals(old, evt.snippet(), + assertEquals(evt.snippet(), old, "Update: Old snippet must be equal to the replacing -- input: " + descriptor); } @@ -556,7 +556,7 @@ private List checkEvents(Supplier> toTest, int impactId = 0; Map> groupedEvents = groupByCauseSnippet(events); - assertEquals(groupedEvents.size(), eventChains.length, "Number of main events"); + assertEquals(eventChains.length, groupedEvents.size(), "Number of main events"); for (Map.Entry> entry : groupedEvents.entrySet()) { EventChain eventChain = eventChains[impactId++]; SnippetEvent main = entry.getValue().get(0); @@ -579,12 +579,12 @@ private List checkEvents(Supplier> toTest, } } if (((Object) eventChain.value) != IGNORE_VALUE) { - assertEquals(main.value(), eventChain.value, "Expected execution value of: " + eventChain.value + + assertEquals(eventChain.value, main.value(), "Expected execution value of: " + eventChain.value + ", but got: " + main.value()); } if (eventChain.exceptionClass != IGNORE_EXCEPTION) { if (main.exception() == null) { - assertEquals(eventChain.exceptionClass, null, "Expected an exception of class " + assertEquals(null, eventChain.exceptionClass, "Expected an exception of class " + eventChain.exceptionClass + " got no exception"); } else if (eventChain.exceptionClass == null) { fail("Expected no exception but got " + main.exception().toString()); @@ -597,7 +597,7 @@ private List checkEvents(Supplier> toTest, List diagnostics = getState().diagnostics(mainKey).collect(toList()); switch (diagMain) { case DIAG_OK: - assertEquals(diagnostics.size(), 0, "Expected no diagnostics, got: " + diagnosticsToString(diagnostics)); + assertEquals(0, diagnostics.size(), "Expected no diagnostics, got: " + diagnosticsToString(diagnostics)); break; case DIAG_WARNING: assertFalse(hasFatalError(diagnostics), "Expected no errors, got: " + diagnosticsToString(diagnostics)); @@ -611,7 +611,7 @@ private List checkEvents(Supplier> toTest, diagnostics = getState().diagnostics(ste.snippet()).collect(toList()); switch (diagUpdates) { case DIAG_OK: - assertEquals(diagnostics.size(), 0, "Expected no diagnostics, got: " + diagnosticsToString(diagnostics)); + assertEquals(0, diagnostics.size(), "Expected no diagnostics, got: " + diagnosticsToString(diagnostics)); break; case DIAG_WARNING: assertFalse(hasFatalError(diagnostics), "Expected no errors, got: " + diagnosticsToString(diagnostics)); @@ -626,7 +626,7 @@ private List checkEvents(Supplier> toTest, // Use this for all EMPTY calls to eval() public void assertEvalEmpty(String input) { List events = getState().eval(input); - assertEquals(events.size(), 0, "Expected no events, got: " + events.size()); + assertEquals(0, events.size(), "Expected no events, got: " + events.size()); } public VarSnippet varKey(List events) { @@ -660,7 +660,7 @@ public Snippet key(List events) { public void assertVarValue(Snippet key, String expected) { String value = state.varValue((VarSnippet) key); - assertEquals(value, expected, "Expected var value of: " + expected + ", but got: " + value); + assertEquals(expected, value, "Expected var value of: " + expected + ", but got: " + value); } public Snippet assertDeclareFail(String input, String expectedErrorCode) { @@ -684,7 +684,7 @@ public Snippet assertDeclareFail(String input, ExpectedDiagnostic expectedDiagno DiagCheck.DIAG_ERROR, DiagCheck.DIAG_IGNORE, mainInfo, updates); SnippetEvent e = events.get(0); Snippet key = e.snippet(); - assertEquals(getState().status(key), REJECTED); + assertEquals(REJECTED, getState().status(key)); List diagnostics = getState().diagnostics(e.snippet()).collect(toList()); assertTrue(diagnostics.size() > 0, "Expected diagnostics, got none"); assertDiagnostic(input, diagnostics.get(0), expectedDiagnostic); @@ -727,7 +727,7 @@ public void assertMethodDeclSnippet(MethodSnippet method, assertDeclarationSnippet(method, expectedName, expectedStatus, METHOD_SUBKIND, unressz, othersz); String signature = method.signature(); - assertEquals(signature, expectedSignature, + assertEquals(expectedSignature, signature, "Expected " + method.source() + " to have the name: " + expectedSignature + ", got: " + signature); } @@ -739,7 +739,7 @@ public void assertVariableDeclSnippet(VarSnippet var, assertDeclarationSnippet(var, expectedName, expectedStatus, expectedSubKind, unressz, othersz); String signature = var.typeName(); - assertEquals(signature, expectedTypeName, + assertEquals(expectedTypeName, signature, "Expected " + var.source() + " to have the type name: " + expectedTypeName + ", got: " + signature); } @@ -750,27 +750,27 @@ public void assertDeclarationSnippet(DeclarationSnippet declarationKey, int unressz, int othersz) { assertKey(declarationKey, expectedStatus, expectedSubKind); String source = declarationKey.source(); - assertEquals(declarationKey.name(), expectedName, + assertEquals(expectedName, declarationKey.name(), "Expected " + source + " to have the name: " + expectedName + ", got: " + declarationKey.name()); long unresolved = getState().unresolvedDependencies(declarationKey).count(); - assertEquals(unresolved, unressz, "Expected " + source + " to have " + unressz + assertEquals(unressz, unresolved, "Expected " + source + " to have " + unressz + " unresolved symbols, got: " + unresolved); long otherCorralledErrorsCount = getState().diagnostics(declarationKey).count(); - assertEquals(otherCorralledErrorsCount, othersz, "Expected " + source + " to have " + othersz + assertEquals(othersz, otherCorralledErrorsCount, "Expected " + source + " to have " + othersz + " other errors, got: " + otherCorralledErrorsCount); } public void assertKey(Snippet key, Status expectedStatus, SubKind expectedSubKind) { String source = key.source(); SubKind actualSubKind = key.subKind(); - assertEquals(actualSubKind, expectedSubKind, + assertEquals(expectedSubKind, actualSubKind, "Expected " + source + " to have the subkind: " + expectedSubKind + ", got: " + actualSubKind); Status status = getState().status(key); - assertEquals(status, expectedStatus, "Expected " + source + " to be " + assertEquals(expectedStatus, status, "Expected " + source + " to be " + expectedStatus + ", but it is " + status); Snippet.Kind expectedKind = getKind(key); - assertEquals(key.kind(), expectedKind, "Checking kind: "); - assertEquals(expectedSubKind.kind(), expectedKind, "Checking kind: "); + assertEquals(expectedKind, key.kind(), "Checking kind: "); + assertEquals(expectedKind, expectedSubKind.kind(), "Checking kind: "); } public void assertDrop(Snippet key, STEInfo mainInfo, STEInfo... updates) { @@ -795,36 +795,36 @@ public void assertAnalyze(String input, Completeness status, String source) { public void assertAnalyze(String input, Completeness status, String source, String remaining, Boolean isComplete) { CompletionInfo ci = getAnalysis().analyzeCompletion(input); - if (status != null) assertEquals(ci.completeness(), status, "Input : " + input + ", status: "); - assertEquals(ci.source(), source, "Input : " + input + ", source: "); - if (remaining != null) assertEquals(ci.remaining(), remaining, "Input : " + input + ", remaining: "); + if (status != null) assertEquals(status, ci.completeness(), "Input : " + input + ", status: "); + assertEquals(source, ci.source(), "Input : " + input + ", source: "); + if (remaining != null) assertEquals(remaining, ci.remaining(), "Input : " + input + ", remaining: "); if (isComplete != null) { boolean isExpectedComplete = isComplete; - assertEquals(ci.completeness().isComplete(), isExpectedComplete, "Input : " + input + ", isComplete: "); + assertEquals(isExpectedComplete, ci.completeness().isComplete(), "Input : " + input + ", isComplete: "); } } public void assertNumberOfActiveVariables(int cnt) { - assertEquals(getState().variables().count(), cnt, "Variables : " + getState().variables().collect(toList())); + assertEquals(cnt, getState().variables().count(), "Variables : " + getState().variables().collect(toList())); } public void assertNumberOfActiveMethods(int cnt) { - assertEquals(getState().methods().count(), cnt, "Methods : " + getState().methods().collect(toList())); + assertEquals(cnt, getState().methods().count(), "Methods : " + getState().methods().collect(toList())); } public void assertNumberOfActiveClasses(int cnt) { - assertEquals(getState().types().count(), cnt, "Types : " + getState().types().collect(toList())); + assertEquals(cnt, getState().types().count(), "Types : " + getState().types().collect(toList())); } public void assertKeys(MemberInfo... expected) { int index = 0; List snippets = getState().snippets().collect(toList()); - assertEquals(allSnippets.size(), snippets.size()); + assertEquals(snippets.size(), allSnippets.size()); for (Snippet sn : snippets) { if (sn.kind().isPersistent() && getState().status(sn).isActive()) { MemberInfo actual = getMemberInfo(sn); MemberInfo exp = expected[index]; - assertEquals(actual, exp, String.format("Difference in #%d. Expected: %s, actual: %s", + assertEquals(exp, actual, String.format("Difference in #%d. Expected: %s, actual: %s", index, exp, actual)); ++index; } @@ -840,7 +840,7 @@ public void assertActiveKeys(Snippet... expected) { int index = 0; for (Snippet key : getState().snippets().collect(toList())) { if (state.status(key).isActive()) { - assertEquals(expected[index], key, String.format("Difference in #%d. Expected: %s, actual: %s", index, key, expected[index])); + assertEquals(key, expected[index], String.format("Difference in #%d. Expected: %s, actual: %s", index, key, expected[index])); ++index; } } @@ -852,7 +852,7 @@ private void assertActiveSnippets(Stream snippets, Predicate< .collect(Collectors.toSet()); Set got = snippets .collect(Collectors.toSet()); - assertEquals(active, got, label); + assertEquals(got, active, label); } public void assertVariables() { @@ -872,8 +872,8 @@ public void assertMembers(Stream members, MemberInfo...expect Set got = members .map(this::getMemberInfo) .collect(Collectors.toSet()); - assertEquals(got.size(), expected.size(), "Expected : " + expected + ", actual : " + members); - assertEquals(got, expected); + assertEquals(expected.size(), got.size(), "Expected : " + expected + ", actual : " + members); + assertEquals(expected, got); } public void assertVariables(MemberInfo...expected) { @@ -891,7 +891,7 @@ public void assertMethods(MemberInfo...expected) { } assertNotNull(expectedInfo, "Not found method: " + methodKey.name()); int lastIndexOf = expectedInfo.type.lastIndexOf(')'); - assertEquals(methodKey.parameterTypes(), expectedInfo.type.substring(1, lastIndexOf), "Parameter types"); + assertEquals(expectedInfo.type.substring(1, lastIndexOf), methodKey.parameterTypes(), "Parameter types"); }); } @@ -905,7 +905,7 @@ public void assertCompletion(String code, String... expected) { public void assertCompletion(String code, Boolean isSmart, String... expected) { List completions = computeCompletions(code, isSmart); - assertEquals(completions, Arrays.asList(expected), "Input: " + code + ", " + completions.toString()); + assertEquals(Arrays.asList(expected), completions, "Input: " + code + ", " + completions.toString()); } public void assertCompletionIncludesExcludes(String code, Set expected, Set notExpected) { @@ -939,7 +939,7 @@ private List computeCompletions(String code, Boolean isSmart) { public void assertInferredType(String code, String expectedType) { String inferredType = getAnalysis().analyzeType(code, code.length()); - assertEquals(inferredType, expectedType, "Input: " + code + ", " + inferredType); + assertEquals(expectedType, inferredType, "Input: " + code + ", " + inferredType); } public void assertInferredFQNs(String code, String... fqns) { @@ -951,9 +951,9 @@ public void assertInferredFQNs(String code, int simpleNameLen, boolean resolvabl QualifiedNames candidates = getAnalysis().listQualifiedNames(code, code.length()); - assertEquals(candidates.getNames(), Arrays.asList(fqns), "Input: " + code + ", candidates=" + candidates.getNames()); - assertEquals(candidates.getSimpleNameLength(), simpleNameLen, "Input: " + code + ", simpleNameLen=" + candidates.getSimpleNameLength()); - assertEquals(candidates.isResolvable(), resolvable, "Input: " + code + ", resolvable=" + candidates.isResolvable()); + assertEquals(Arrays.asList(fqns), candidates.getNames(), "Input: " + code + ", candidates=" + candidates.getNames()); + assertEquals(simpleNameLen, candidates.getSimpleNameLength(), "Input: " + code + ", simpleNameLen=" + candidates.getSimpleNameLength()); + assertEquals(resolvable, candidates.isResolvable(), "Input: " + code + ", resolvable=" + candidates.isResolvable()); } protected void waitIndexingFinished() { @@ -974,7 +974,7 @@ public void assertSignature(String code, String... expected) { List documentation = getAnalysis().documentation(code, cursor, false); Set docSet = documentation.stream().map(doc -> doc.signature()).collect(Collectors.toSet()); Set expectedSet = Stream.of(expected).collect(Collectors.toSet()); - assertEquals(docSet, expectedSet, "Input: " + code); + assertEquals(expectedSet, docSet, "Input: " + code); } public void assertJavadoc(String code, String... expected) { @@ -986,7 +986,7 @@ public void assertJavadoc(String code, String... expected) { .map(doc -> doc.signature() + "\n" + doc.javadoc()) .collect(Collectors.toSet()); Set expectedSet = Stream.of(expected).collect(Collectors.toSet()); - assertEquals(docSet, expectedSet, "Input: " + code); + assertEquals(expectedSet, docSet, "Input: " + code); } public enum ClassType { @@ -1182,7 +1182,7 @@ public void assertMatch(SnippetEvent ste, Snippet mainSnippet) { assertStatusMatch(ste, ste.previousStatus(), previousStatus()); assertStatusMatch(ste, ste.status(), status()); if (checkIsSignatureChange) { - assertEquals(ste.isSignatureChange(), isSignatureChange(), + assertEquals(isSignatureChange(), ste.isSignatureChange(), "Expected " + (isSignatureChange()? "" : "no ") + "signature-change, got: " + @@ -1205,10 +1205,10 @@ private void assertKeyMatch(SnippetEvent ste, Snippet sn, Snippet expected, Snip assertTrue(sn != testKey, "Main-event: Expected new snippet to be != : " + testKey + "\n got-event: " + toString(ste)); - assertEquals(sn.id(), testKey.id(), "Expected IDs to match: " + testKey + ", got: " + sn + assertEquals(testKey.id(), sn.id(), "Expected IDs to match: " + testKey + ", got: " + sn + "\n expected-event: " + this + "\n got-event: " + toString(ste)); } else { - assertEquals(sn, testKey, "Expected key to be: " + testKey + ", got: " + sn + assertEquals(testKey, sn, "Expected key to be: " + testKey + ", got: " + sn + "\n expected-event: " + this + "\n got-event: " + toString(ste)); } } @@ -1216,7 +1216,7 @@ private void assertKeyMatch(SnippetEvent ste, Snippet sn, Snippet expected, Snip private void assertStatusMatch(SnippetEvent ste, Status status, Status expected) { if (expected != null) { - assertEquals(status, expected, "Expected status to be: " + expected + ", got: " + status + + assertEquals(expected, status, "Expected status to be: " + expected + ", got: " + status + "\n expected-event: " + this + "\n got-event: " + toString(ste)); } } diff --git a/test/langtools/jdk/jshell/MethodsTest.java b/test/langtools/jdk/jshell/MethodsTest.java index 85f63f82f77d..9577f943c519 100644 --- a/test/langtools/jdk/jshell/MethodsTest.java +++ b/test/langtools/jdk/jshell/MethodsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, 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 @@ -26,7 +26,7 @@ * @bug 8080357 8167643 8187359 8199762 8080353 8246353 8247456 8267221 8272135 * @summary Tests for EvaluationState.methods * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng MethodsTest + * @run junit MethodsTest */ import javax.tools.Diagnostic; @@ -34,21 +34,23 @@ import jdk.jshell.Snippet; import jdk.jshell.MethodSnippet; import jdk.jshell.Snippet.Status; -import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static jdk.jshell.Snippet.Status.*; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class MethodsTest extends KullaTesting { + @Test public void noMethods() { assertNumberOfActiveMethods(0); } + @Test public void testSignature1() { MethodSnippet m1 = methodKey(assertEval("void f() { g(); }", added(RECOVERABLE_DEFINED))); assertMethodDeclSnippet(m1, "f", "()void", RECOVERABLE_DEFINED, 1, 0); @@ -58,6 +60,7 @@ public void testSignature1() { assertMethodDeclSnippet(m2, "g", "()void", VALID, 0, 0); } + @Test public void testSignature2() { MethodSnippet m1 = (MethodSnippet) assertDeclareFail("void f() { return g(); }", "compiler.err.prob.found.req"); assertMethodDeclSnippet(m1, "f", "()void", REJECTED, 0, 2); @@ -67,7 +70,8 @@ public void testSignature2() { assertMethodDeclSnippet(m2, "f", "()int", RECOVERABLE_DEFINED, 1, 0); } - @Test(enabled = false) // TODO 8081690 + @Test // TODO 8081690 + @Disabled public void testSignature3() { MethodSnippet m1 = methodKey(assertEval("void f(Bar b) { }", added(RECOVERABLE_NOT_DEFINED))); assertMethodDeclSnippet(m1, "f", "(Bar)void", RECOVERABLE_NOT_DEFINED, 1, 0); @@ -79,6 +83,7 @@ public void testSignature3() { } // 8080357 + @Test public void testNonReplUnresolved() { // internal case assertEval("class CCC {}", added(VALID)); @@ -87,6 +92,7 @@ public void testNonReplUnresolved() { assertDeclareFail("void f2() { System.xxxx(); }", "compiler.err.cant.resolve.location.args"); } + @Test public void methods() { assertEval("int x() { return 10; }"); assertEval("String y() { return null; }"); @@ -95,6 +101,7 @@ public void methods() { assertActiveKeys(); } + @Test public void methodOverload() { assertEval("int m() { return 1; }"); assertEval("int m(int x) { return 2; }"); @@ -139,6 +146,7 @@ public void methodOverloadDependent() { } ***/ + @Test public void methodsRedeclaration1() { Snippet x = methodKey(assertEval("int x() { return 10; }")); Snippet y = methodKey(assertEval("String y() { return \"\"; }")); @@ -158,6 +166,7 @@ public void methodsRedeclaration1() { assertActiveKeys(); } + @Test public void methodsRedeclaration2() { assertEval("int a() { return 1; }"); assertMethods(method("()int", "a")); @@ -179,6 +188,7 @@ public void methodsRedeclaration2() { assertActiveKeys(); } + @Test public void methodsRedeclaration3() { Snippet x = methodKey(assertEval("int x(Object...a) { return 10; }")); assertMethods(method("(Object...)int", "x")); @@ -192,6 +202,7 @@ public void methodsRedeclaration3() { } + @Test public void methodsRedeclaration4() { Snippet a = methodKey(assertEval("int foo(int a) { return a; }")); assertEval("int x = foo(10);"); @@ -204,6 +215,7 @@ public void methodsRedeclaration4() { } // 8199762 + @Test public void methodsRedeclaration5() { Snippet m1 = methodKey(assertEval("int m(Object o) { return 10; }")); assertMethods(method("(Object)int", "m")); @@ -220,22 +232,23 @@ public void methodsRedeclaration5() { assertActiveKeys(); } + @Test public void methodsAbstract() { MethodSnippet m1 = methodKey(assertEval("abstract String f();", ste(MAIN_SNIPPET, NONEXISTENT, RECOVERABLE_DEFINED, true, null))); - assertEquals(getState().unresolvedDependencies(m1).collect(Collectors.toList()), - List.of("method f()")); + assertEquals( List.of("method f()"), getState().unresolvedDependencies(m1).collect(Collectors.toList())); MethodSnippet m2 = methodKey(assertEval("abstract int mm(Blah b);", ste(MAIN_SNIPPET, NONEXISTENT, RECOVERABLE_NOT_DEFINED, false, null))); List unr = getState().unresolvedDependencies(m2).collect(Collectors.toList()); - assertEquals(unr.size(), 2); + assertEquals(2, unr.size()); unr.remove("class Blah"); unr.remove("method mm(Blah)"); - assertEquals(unr.size(), 0, "unexpected entry: " + unr); + assertEquals(0, unr.size(), "unexpected entry: " + unr); assertNumberOfActiveMethods(2); assertActiveKeys(); } + @Test public void methodsErrors() { assertDeclareFail("String f();", new ExpectedDiagnostic("compiler.err.missing.meth.body.or.decl.abstract", 0, 11, 7, -1, -1, Diagnostic.Kind.ERROR)); @@ -267,6 +280,7 @@ public void methodsErrors() { assertActiveKeys(); } + @Test public void objectMethodNamedMethodsErrors() { assertDeclareFail("boolean equals(double d1, double d2) { return d1 == d2; }", new ExpectedDiagnostic("jdk.eval.error.object.method", 8, 14, 8, -1, -1, Diagnostic.Kind.ERROR)); @@ -286,6 +300,7 @@ public void objectMethodNamedMethodsErrors() { } + @Test public void methodsAccessModifierIgnored() { Snippet f = methodKey(assertEval("public String f() {return null;}", added(VALID))); @@ -305,6 +320,7 @@ public void methodsAccessModifierIgnored() { assertActiveKeys(); } + @Test public void methodsIgnoredModifiers() { Snippet f = methodKey(assertEval("static String f() {return null;}")); assertNumberOfActiveMethods(1); @@ -318,6 +334,7 @@ public void methodsIgnoredModifiers() { assertActiveKeys(); } + @Test public void methodSignatureUnresolved() { MethodSnippet key = (MethodSnippet) methodKey(assertEval("und m() { return new und(); }", added(RECOVERABLE_NOT_DEFINED))); assertMethodDeclSnippet(key, "m", "()und", RECOVERABLE_NOT_DEFINED, 1, 0); @@ -330,7 +347,8 @@ public void methodSignatureUnresolved() { assertActiveKeys(); } - @Test(enabled = false) // TODO 8081689 + @Test // TODO 8081689 + @Disabled public void classMethodsAreNotVisible() { assertEval( "class A {" + @@ -351,6 +369,7 @@ public void classMethodsAreNotVisible() { assertActiveKeys(); } + @Test public void lambdas() { assertEval("class Inner1 implements Runnable {" + "public Runnable lambda1 = () -> {};" + @@ -376,15 +395,17 @@ public void lambdas() { } //JDK-8267221: + @Test public void testMethodArrayParameters() { MethodSnippet m1 = methodKey(assertEval("void m1(int... p) { }", added(VALID))); - assertEquals(m1.parameterTypes(), "int..."); + assertEquals("int...", m1.parameterTypes()); MethodSnippet m2 = methodKey(assertEval("void m2(int[]... p) { }", added(VALID))); - assertEquals(m2.parameterTypes(), "int[]..."); + assertEquals("int[]...", m2.parameterTypes()); MethodSnippet m3 = methodKey(assertEval("void m3(int[][] p) { }", added(VALID))); - assertEquals(m3.parameterTypes(), "int[][]"); + assertEquals("int[][]", m3.parameterTypes()); } + @Test public void testOverloadCalls() { MethodSnippet orig = methodKey(assertEval("int m(String s) { return 0; }")); MethodSnippet overload = methodKey(assertEval("int m(int i) { return 1; }")); diff --git a/test/langtools/jdk/jshell/ModifiersTest.java b/test/langtools/jdk/jshell/ModifiersTest.java index 2cbebc8b5b87..2cdb5ce28b6f 100644 --- a/test/langtools/jdk/jshell/ModifiersTest.java +++ b/test/langtools/jdk/jshell/ModifiersTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, 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 @@ -25,7 +25,7 @@ * @test 8167643 8129559 8247456 * @summary Tests for modifiers * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng ModifiersTest + * @run junit ModifiersTest */ import java.util.ArrayList; @@ -34,13 +34,14 @@ import java.util.function.Consumer; import javax.tools.Diagnostic; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@Test +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class ModifiersTest extends KullaTesting { - @DataProvider(name = "ignoredModifiers") public Object[][] getTestCases() { List testCases = new ArrayList<>(); String[] ignoredModifiers = new String[] { @@ -77,7 +78,8 @@ public Object[][] getTestCases() { return testCases.toArray(new Object[testCases.size()][]); } - @Test(dataProvider = "ignoredModifiers") + @ParameterizedTest + @MethodSource("getTestCases") public void ignoredModifiers(String modifier, ClassType classType, Consumer eval, String preface, String context) { if (context != null) { @@ -95,6 +97,7 @@ public void ignoredModifiers(String modifier, ClassType classType, assertActiveKeys(); } + @Test public void accessToStaticFieldsOfClass() { assertEval("class A {" + "int x = 14;" + @@ -108,6 +111,7 @@ public void accessToStaticFieldsOfClass() { assertActiveKeys(); } + @Test public void accessToStaticMethodsOfClass() { assertEval("class A {" + "void x() {}" + @@ -119,6 +123,7 @@ public void accessToStaticMethodsOfClass() { assertActiveKeys(); } + @Test public void accessToStaticFieldsOfInterface() { assertEval("interface A {" + "int x = 14;" + @@ -134,12 +139,14 @@ public void accessToStaticFieldsOfInterface() { assertActiveKeys(); } + @Test public void accessToStaticMethodsOfInterface() { assertEval("interface A { static void x() {} }"); assertEval("A.x();"); assertActiveKeys(); } + @Test public void finalMethod() { assertEval("class A { final void f() {} }"); assertDeclareFail("class B extends A { void f() {} }", @@ -148,6 +155,7 @@ public void finalMethod() { } //TODO: is this the right semantics? + @Test public void finalConstructor() { assertDeclareFail("class A { final A() {} }", new ExpectedDiagnostic("compiler.err.mod.not.allowed.here", 10, 22, 16, -1, -1, Diagnostic.Kind.ERROR)); @@ -155,6 +163,7 @@ public void finalConstructor() { } //TODO: is this the right semantics? + @Test public void finalDefaultMethod() { assertDeclareFail("interface A { final default void a() {} }", new ExpectedDiagnostic("compiler.err.mod.not.allowed.here", 14, 39, 33, -1, -1, Diagnostic.Kind.ERROR)); diff --git a/test/langtools/jdk/jshell/MultipleDocumentationTest.java b/test/langtools/jdk/jshell/MultipleDocumentationTest.java index 8037381ccc8d..d7894212016d 100644 --- a/test/langtools/jdk/jshell/MultipleDocumentationTest.java +++ b/test/langtools/jdk/jshell/MultipleDocumentationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -26,8 +26,8 @@ import java.util.List; import java.util.stream.Collectors; import jdk.jshell.JShell; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; /* * @test @@ -39,11 +39,11 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build Compiler toolbox.ToolBox - * @run testng MultipleDocumentationTest + * @run junit MultipleDocumentationTest */ -@Test public class MultipleDocumentationTest { + @Test public void testMultipleDocumentation() { String input = "java.lang.String"; @@ -68,7 +68,7 @@ public void testMultipleDocumentation() { .map(d -> d.javadoc()) .collect(Collectors.toList()); - assertEquals(javadocs2, javadocs1); + assertEquals(javadocs1, javadocs2); } } } diff --git a/test/langtools/jdk/jshell/MyExecutionControl.java b/test/langtools/jdk/jshell/MyExecutionControl.java index 8493638db576..12a0ac6986d0 100644 --- a/test/langtools/jdk/jshell/MyExecutionControl.java +++ b/test/langtools/jdk/jshell/MyExecutionControl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -42,7 +42,7 @@ import jdk.jshell.spi.ExecutionControl; import jdk.jshell.spi.ExecutionControl.EngineTerminationException; import jdk.jshell.spi.ExecutionEnv; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; import static jdk.jshell.execution.Util.remoteInputOutput; class MyExecutionControl extends JdiExecutionControl { diff --git a/test/langtools/jdk/jshell/NullTest.java b/test/langtools/jdk/jshell/NullTest.java index b365b5155f8c..c4759aca87fb 100644 --- a/test/langtools/jdk/jshell/NullTest.java +++ b/test/langtools/jdk/jshell/NullTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -25,14 +25,14 @@ * @test * @summary null test * @build KullaTesting TestingInputStream - * @run testng NullTest + * @run junit NullTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class NullTest extends KullaTesting { + @Test public void testNull() { assertEval("null;", "null"); assertEval("(Object)null;", "null"); diff --git a/test/langtools/jdk/jshell/PasteAndMeasurementsUITest.java b/test/langtools/jdk/jshell/PasteAndMeasurementsUITest.java index 409965e2e682..350a6659c525 100644 --- a/test/langtools/jdk/jshell/PasteAndMeasurementsUITest.java +++ b/test/langtools/jdk/jshell/PasteAndMeasurementsUITest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8182297 8242919 8267459 * @summary Verify that pasting multi-line snippets works properly. @@ -38,7 +38,7 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @build PasteAndMeasurementsUITest - * @run testng/othervm PasteAndMeasurementsUITest + * @run junit/othervm PasteAndMeasurementsUITest */ import java.io.Console; @@ -46,15 +46,15 @@ import java.lang.reflect.Field; import jdk.internal.org.jline.reader.impl.LineReaderImpl; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class PasteAndMeasurementsUITest extends UITesting { public PasteAndMeasurementsUITest() { super(true); } + @Test public void testPrevNextSnippet() throws Exception { Field cons = System.class.getDeclaredField("cons"); cons.setAccessible(true); @@ -77,6 +77,7 @@ public void testPrevNextSnippet() throws Exception { } private static final String LOC = "\033[12;1R"; + @Test public void testBracketedPaste() throws Exception { Field cons = System.class.getDeclaredField("cons"); cons.setAccessible(true); @@ -91,6 +92,7 @@ public void testBracketedPaste() throws Exception { }); } + @Test public void testBracketedPasteNonAscii() throws Exception { Field cons = System.class.getDeclaredField("cons"); cons.setAccessible(true); diff --git a/test/langtools/jdk/jshell/PipeInputStreamTest.java b/test/langtools/jdk/jshell/PipeInputStreamTest.java index 867a1f254a49..0062c6006e11 100644 --- a/test/langtools/jdk/jshell/PipeInputStreamTest.java +++ b/test/langtools/jdk/jshell/PipeInputStreamTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,7 +26,7 @@ * @summary Verify PipeInputStream works. * @modules jdk.compiler/com.sun.tools.javac.util * jdk.jshell/jdk.jshell.execution.impl:open - * @run testng PipeInputStreamTest + * @run junit PipeInputStreamTest */ import java.io.InputStream; @@ -34,28 +34,28 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; -import org.testng.annotations.Test; import com.sun.tools.javac.util.Pair; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; -@Test public class PipeInputStreamTest { + @Test public void testReadArrayNotBlocking() throws Exception { Pair streams = createPipeStream(); InputStream in = streams.fst; OutputStream out = streams.snd; out.write('a'); byte[] data = new byte[12]; - assertEquals(in.read(data), 1); - assertEquals(data[0], 'a'); + assertEquals(1, in.read(data)); + assertEquals('a', data[0]); out.write('a'); out.write('b'); out.write('c'); - assertEquals(in.read(data), 3); - assertEquals(data[0], 'a'); - assertEquals(data[1], 'b'); - assertEquals(data[2], 'c'); + assertEquals(3, in.read(data)); + assertEquals('a', data[0]); + assertEquals('b', data[1]); + assertEquals('c', data[2]); } private Pair createPipeStream() throws Exception { diff --git a/test/langtools/jdk/jshell/RecordsTest.java b/test/langtools/jdk/jshell/RecordsTest.java index 69aaae8e46f8..fdf75aed3ab9 100644 --- a/test/langtools/jdk/jshell/RecordsTest.java +++ b/test/langtools/jdk/jshell/RecordsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 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 @@ -27,27 +27,27 @@ * @summary Tests for evalution of records * @modules jdk.jshell * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng RecordsTest + * @run junit RecordsTest */ -import org.testng.annotations.Test; import javax.lang.model.SourceVersion; import jdk.jshell.Snippet.Status; import jdk.jshell.UnresolvedReferenceException; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.BeforeMethod; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -@Test public class RecordsTest extends KullaTesting { + @Test public void testRecordClass() { assertEval("record R(String s, int i) { }"); - assertEquals(varKey(assertEval("R r = new R(\"r\", 42);")).name(), "r"); + assertEquals("r", varKey(assertEval("R r = new R(\"r\", 42);")).name()); assertEval("r.s()", "\"r\""); assertEval("r.i()", "42"); } + @Test public void testRecordCorralling() { //simple record with a mistake that can be fixed by corralling: assertEval("record R1(int i) { int g() { return j; } }", ste(MAIN_SNIPPET, Status.NONEXISTENT, Status.RECOVERABLE_DEFINED, true, null)); @@ -66,13 +66,15 @@ public void testRecordCorralling() { assertEval("R5 r5 = new R5(1);", null, UnresolvedReferenceException.class, DiagCheck.DIAG_OK, DiagCheck.DIAG_OK, added(Status.VALID)); } + @Test public void testRecordField() { - assertEquals(varKey(assertEval("String record = \"\";")).name(), "record"); + assertEquals("record", varKey(assertEval("String record = \"\";")).name()); assertEval("record.length()", "0"); } + @Test public void testRecordMethod() { - assertEquals(methodKey(assertEval("String record(String record) { return record + record; }")).name(), "record"); + assertEquals("record", methodKey(assertEval("String record(String record) { return record + record; }")).name()); assertEval("record(\"r\")", "\"rr\""); assertEval("record(\"r\").length()", "2"); } diff --git a/test/langtools/jdk/jshell/RejectedFailedTest.java b/test/langtools/jdk/jshell/RejectedFailedTest.java index 5411d5d8aee1..5e97a03d3994 100644 --- a/test/langtools/jdk/jshell/RejectedFailedTest.java +++ b/test/langtools/jdk/jshell/RejectedFailedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,13 +25,12 @@ * @test 8080352 * @summary Tests for hard errors, like syntax errors * @build KullaTesting - * @run testng RejectedFailedTest + * @run junit RejectedFailedTest */ import java.util.List; import jdk.jshell.Snippet.SubKind; -import org.testng.annotations.Test; import jdk.jshell.Diag; import jdk.jshell.Snippet; @@ -40,31 +39,31 @@ import jdk.jshell.SnippetEvent; import static java.util.stream.Collectors.toList; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class RejectedFailedTest extends KullaTesting { private String bad(String input, Kind kind, String prevId) { List events = assertEvalFail(input); - assertEquals(events.size(), 1, "Expected one event, got: " + events.size()); + assertEquals(1, events.size(), "Expected one event, got: " + events.size()); SnippetEvent e = events.get(0); List diagnostics = getState().diagnostics(e.snippet()).collect(toList()); assertTrue(diagnostics.size() > 0, "Expected diagnostics, got none"); - assertEquals(e.exception(), null, "Expected exception to be null."); - assertEquals(e.value(), null, "Expected value to be null."); + assertEquals(null, e.exception(), "Expected exception to be null."); + assertEquals(null, e.value(), "Expected value to be null."); Snippet key = e.snippet(); assertTrue(key != null, "key must be non-null, but was null."); - assertEquals(key.kind(), kind, "Expected kind: " + kind + ", got: " + key.kind()); + assertEquals(kind, key.kind(), "Expected kind: " + kind + ", got: " + key.kind()); SubKind expectedSubKind = kind == Kind.ERRONEOUS ? SubKind.UNKNOWN_SUBKIND : SubKind.METHOD_SUBKIND; - assertEquals(key.subKind(), expectedSubKind, "SubKind: "); + assertEquals(expectedSubKind, key.subKind(), "SubKind: "); assertTrue(key.id().compareTo(prevId) > 0, "Current id: " + key.id() + ", previous: " + prevId); - assertEquals(getState().diagnostics(key).collect(toList()), diagnostics, "Expected retrieved diagnostics to match, but didn't."); - assertEquals(key.source(), input, "Expected retrieved source: " + + assertEquals(diagnostics, getState().diagnostics(key).collect(toList()), "Expected retrieved diagnostics to match, but didn't."); + assertEquals(input, key.source(), "Expected retrieved source: " + key.source() + " to match input: " + input); - assertEquals(getState().status(key), Status.REJECTED, "Expected status of REJECTED, got: " + getState().status(key)); + assertEquals(Status.REJECTED, getState().status(key), "Expected status of REJECTED, got: " + getState().status(key)); return key.id(); } @@ -75,6 +74,7 @@ private void checkByKind(String[] inputs, Kind kind) { } } + @Test public void testErroneous() { String[] inputsErroneous = { "%&^%&", @@ -86,6 +86,7 @@ public void testErroneous() { checkByKind(inputsErroneous, Kind.ERRONEOUS); } + @Test public void testBadMethod() { String[] inputsMethod = { "transient int m() { return x; }", diff --git a/test/langtools/jdk/jshell/ReplToolTesting.java b/test/langtools/jdk/jshell/ReplToolTesting.java index 52eb2d5798c6..f6c15ca2d792 100644 --- a/test/langtools/jdk/jshell/ReplToolTesting.java +++ b/test/langtools/jdk/jshell/ReplToolTesting.java @@ -45,14 +45,14 @@ import java.util.stream.Stream; -import org.testng.annotations.BeforeMethod; import jdk.jshell.tool.JavaShellToolBuilder; import static java.util.stream.Collectors.toList; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; public class ReplToolTesting { @@ -142,7 +142,7 @@ public Consumer assertList() { .filter(l -> !l.isEmpty()) .collect(Collectors.toList()); int previousId = Integer.MIN_VALUE; - assertEquals(lines.size(), keys.size(), "Number of keys"); + assertEquals(keys.size(), lines.size(), "Number of keys"); for (int i = 0; i < lines.size(); ++i) { String line = lines.get(i); Matcher matcher = idPattern.matcher(line); @@ -165,7 +165,7 @@ private Consumer assertMembers(String message, Map !l.isEmpty()) .filter(l -> !l.startsWith("| ")) // error/unresolved info .collect(Collectors.toList()); - assertEquals(lines.size(), set.size(), message + " : expected: " + set.keySet() + "\ngot:\n" + lines); + assertEquals(set.size(), lines.size(), message + " : expected: " + set.keySet() + "\ngot:\n" + lines); for (String line : lines) { Matcher matcher = extractPattern.matcher(line); assertTrue(matcher.find(), line); @@ -275,7 +275,7 @@ private void initSnippets() { } } - @BeforeMethod + @BeforeEach public void setUp() { prefsMap = new HashMap<>(); prefsMap.put("INDENT", "0"); @@ -335,8 +335,7 @@ private void testRawCheck(Locale locale, String expectedErrorOutput) { String ueos = getUserErrorOutput(); assertTrue((cos.isEmpty() || cos.startsWith("| Goodbye") || !locale.equals(Locale.ROOT)), "Expected a goodbye, but got: " + cos); - assertEquals(ceos, - expectedErrorOutput, + assertEquals( expectedErrorOutput, ceos, "Expected \"" + expectedErrorOutput + "\" command error output, got: \"" + ceos + "\""); assertTrue(uos.isEmpty(), "Expected empty user output, got: " + uos); @@ -560,7 +559,7 @@ public Consumer assertStartsWith(String prefix) { public void assertOutput(String got, String expected, String display) { if (expected != null) { - assertEquals(got, expected, display + ".\n"); + assertEquals(expected, got, display + ".\n"); } } diff --git a/test/langtools/jdk/jshell/ReplaceTest.java b/test/langtools/jdk/jshell/ReplaceTest.java index e4c2c8575c0c..02ebb27fcb9b 100644 --- a/test/langtools/jdk/jshell/ReplaceTest.java +++ b/test/langtools/jdk/jshell/ReplaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -25,7 +25,7 @@ * @test 8080069 8152925 * @summary Test of Snippet redefinition and replacement. * @build KullaTesting TestingInputStream - * @run testng ReplaceTest + * @run junit ReplaceTest */ import java.util.Iterator; @@ -34,16 +34,16 @@ import jdk.jshell.MethodSnippet; import jdk.jshell.TypeDeclSnippet; import jdk.jshell.VarSnippet; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; import static jdk.jshell.Snippet.Status.*; import static jdk.jshell.Snippet.SubKind.*; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class ReplaceTest extends KullaTesting { + @Test public void testRedefine() { Snippet vx = varKey(assertEval("int x;")); Snippet mu = methodKey(assertEval("int mu() { return x * 4; }")); @@ -69,6 +69,7 @@ public void testRedefine() { assertActiveKeys(); } + @Test public void testReplaceClassToVar() { Snippet oldA = classKey(assertEval("class A { public String toString() { return \"old\"; } }")); Snippet v = varKey(assertEval("A a = new A();", "old")); @@ -92,6 +93,7 @@ private void identityMatch(Stream got, T expected) { assertFalse(it.hasNext(), "expected exactly one"); } + @Test public void testReplaceVarToMethod() { Snippet x = varKey(assertEval("int x;")); MethodSnippet musn = methodKey(assertEval("double mu() { return x * 4; }")); @@ -106,6 +108,7 @@ public void testReplaceVarToMethod() { assertActiveKeys(); } + @Test public void testReplaceMethodToMethod() { Snippet a = methodKey(assertEval("double a() { return 2; }")); Snippet b = methodKey(assertEval("double b() { return a() * 10; }")); @@ -119,6 +122,7 @@ public void testReplaceMethodToMethod() { assertActiveKeys(); } + @Test public void testReplaceClassToMethod() { Snippet c = classKey(assertEval("class C { int f() { return 7; } }")); Snippet m = methodKey(assertEval("int m() { return new C().f(); }")); @@ -130,6 +134,7 @@ public void testReplaceClassToMethod() { assertActiveKeys(); } + @Test public void testReplaceVarToClass() { Snippet x = varKey(assertEval("int x;")); TypeDeclSnippet c = classKey(assertEval("class A { double a = 4 * x; }")); @@ -144,6 +149,7 @@ public void testReplaceVarToClass() { assertActiveKeys(); } + @Test public void testReplaceMethodToClass() { Snippet x = methodKey(assertEval("int x() { return 0; }")); TypeDeclSnippet c = classKey(assertEval("class A { double a = 4 * x(); }")); @@ -159,6 +165,7 @@ public void testReplaceMethodToClass() { assertActiveKeys(); } + @Test public void testReplaceClassToClass() { TypeDeclSnippet a = classKey(assertEval("class A {}")); assertTypeDeclSnippet(a, "A", VALID, CLASS_SUBKIND, 0, 0); @@ -178,6 +185,7 @@ public void testReplaceClassToClass() { assertActiveKeys(); } + @Test public void testOverwriteReplaceMethod() { MethodSnippet k1 = methodKey(assertEval("String m(Integer i) { return i.toString(); }")); MethodSnippet k2 = methodKey(assertEval("String m(java.lang.Integer i) { return \"java.lang.\" + i.toString(); }", @@ -193,6 +201,7 @@ public void testOverwriteReplaceMethod() { assertActiveKeys(); } + @Test public void testImportDeclare() { Snippet singleImport = importKey(assertEval("import java.util.List;", added(VALID))); Snippet importOnDemand = importKey(assertEval("import java.util.*;", added(VALID))); @@ -213,7 +222,8 @@ public void testImportDeclare() { assertActiveKeys(); } - @Test(enabled = false) // TODO 8129420 + @Test // TODO 8129420 + @Disabled public void testLocalClassEvolve() { Snippet j = methodKey(assertEval("Object j() { return null; }", added(VALID))); assertEval("Object j() { class B {}; return null; }", @@ -227,6 +237,7 @@ public void testLocalClassEvolve() { assertEval("j();", "Yep"); } + @Test public void testReplaceCausesMethodReferenceError() { Snippet l = classKey(assertEval("interface Logger { public void log(String message); }", added(VALID))); Snippet v = varKey(assertEval("Logger l = System.out::println;", added(VALID))); @@ -238,6 +249,7 @@ public void testReplaceCausesMethodReferenceError() { ste(v, VALID, RECOVERABLE_NOT_DEFINED, true, MAIN_SNIPPET)); } + @Test public void testReplaceCausesClassCompilationError() { Snippet l = classKey(assertEval("interface L { }", added(VALID))); Snippet c = classKey(assertEval("class C implements L { }", added(VALID))); @@ -249,6 +261,7 @@ public void testReplaceCausesClassCompilationError() { ste(c, VALID, RECOVERABLE_NOT_DEFINED, true, MAIN_SNIPPET)); } + @Test public void testOverwriteNoUpdate() { String xsi = "int x = 5;"; String xsd = "double x = 3.14159;"; diff --git a/test/langtools/jdk/jshell/SealedClassesTest.java b/test/langtools/jdk/jshell/SealedClassesTest.java index ba4f8c8f008c..c45bc7677692 100644 --- a/test/langtools/jdk/jshell/SealedClassesTest.java +++ b/test/langtools/jdk/jshell/SealedClassesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -27,7 +27,7 @@ * @summary Test sealed class in jshell * @modules jdk.jshell * @build KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng SealedClassesTest + * @run junit SealedClassesTest */ import javax.lang.model.SourceVersion; @@ -35,14 +35,13 @@ import jdk.jshell.TypeDeclSnippet; import jdk.jshell.Snippet.Status; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.VALID; +import org.junit.jupiter.api.Test; -@Test public class SealedClassesTest extends KullaTesting { + @Test public void testSealed() { TypeDeclSnippet base = classKey( assertEval("sealed class B permits I {}", @@ -53,6 +52,7 @@ public void testSealed() { assertEval("new I()"); } + @Test public void testInterface() { TypeDeclSnippet base = classKey( assertEval("sealed interface I permits C {}", @@ -63,6 +63,7 @@ public void testInterface() { assertEval("new C()"); } + @Test public void testNonSealed() { TypeDeclSnippet base = classKey( assertEval("sealed class B permits I {}", @@ -74,6 +75,7 @@ public void testNonSealed() { assertEval("new I2()"); } + @Test public void testNonSealedInterface() { TypeDeclSnippet base = classKey( assertEval("sealed interface B permits C {}", diff --git a/test/langtools/jdk/jshell/ShutdownTest.java b/test/langtools/jdk/jshell/ShutdownTest.java index 45431f661620..9c3b084f6a3d 100644 --- a/test/langtools/jdk/jshell/ShutdownTest.java +++ b/test/langtools/jdk/jshell/ShutdownTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,18 +25,21 @@ * @test * @summary Shutdown tests * @build KullaTesting TestingInputStream - * @run testng ShutdownTest + * @run junit ShutdownTest */ import java.util.function.Consumer; import jdk.jshell.JShell; import jdk.jshell.JShell.Subscription; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; -import static org.testng.Assert.assertEquals; - -@Test public class ShutdownTest extends KullaTesting { int shutdownCount; @@ -45,29 +48,33 @@ void shutdownCounter(JShell state) { ++shutdownCount; } - @Test(enabled = false) //TODO 8139873 + @Test //TODO 8139873 + @Disabled public void testExit() { shutdownCount = 0; getState().onShutdown(this::shutdownCounter); assertEval("System.exit(1);"); - assertEquals(shutdownCount, 1); + assertEquals(1, shutdownCount); } + @Test public void testCloseCallback() { shutdownCount = 0; getState().onShutdown(this::shutdownCounter); getState().close(); - assertEquals(shutdownCount, 1); + assertEquals(1, shutdownCount); } + @Test public void testCloseUnsubscribe() { shutdownCount = 0; Subscription token = getState().onShutdown(this::shutdownCounter); getState().unsubscribe(token); getState().close(); - assertEquals(shutdownCount, 0); + assertEquals(0, shutdownCount); } + @Test public void testTwoShutdownListeners() { ShutdownListener listener1 = new ShutdownListener(); ShutdownListener listener2 = new ShutdownListener(); @@ -76,46 +83,56 @@ public void testTwoShutdownListeners() { getState().unsubscribe(subscription1); getState().close(); - assertEquals(listener1.getEvents(), 0, "Checking got events"); - assertEquals(listener2.getEvents(), 1, "Checking got events"); + assertEquals(0, listener1.getEvents(), "Checking got events"); + assertEquals(1, listener2.getEvents(), "Checking got events"); getState().close(); - assertEquals(listener1.getEvents(), 0, "Checking got events"); - assertEquals(listener2.getEvents(), 1, "Checking got events"); + assertEquals(0, listener1.getEvents(), "Checking got events"); + assertEquals(1, listener2.getEvents(), "Checking got events"); getState().unsubscribe(subscription2); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void testCloseException() { - getState().close(); - getState().eval("45"); + Assertions.assertThrows(IllegalStateException.class, () -> { + getState().close(); + getState().eval("45"); + }); } - @Test(expectedExceptions = IllegalStateException.class, - enabled = false) //TODO 8139873 + @Test //TODO 8139873 + @Disabled public void testShutdownException() { - assertEval("System.exit(0);"); - getState().eval("45"); + Assertions.assertThrows(IllegalStateException.class, () -> { + assertEval("System.exit(0);"); + getState().eval("45"); + }); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void testNullCallback() { - getState().onShutdown(null); + Assertions.assertThrows(NullPointerException.class, () -> { + getState().onShutdown(null); + }); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void testSubscriptionAfterClose() { - getState().close(); - getState().onShutdown(e -> {}); + Assertions.assertThrows(IllegalStateException.class, () -> { + getState().close(); + getState().onShutdown(e -> {}); + }); } - @Test(expectedExceptions = IllegalStateException.class, - enabled = false) //TODO 8139873 + @Test //TODO 8139873 + @Disabled public void testSubscriptionAfterShutdown() { - assertEval("System.exit(0);"); - getState().onShutdown(e -> {}); + Assertions.assertThrows(IllegalStateException.class, () -> { + assertEval("System.exit(0);"); + getState().onShutdown(e -> {}); + }); } private static class ShutdownListener implements Consumer { diff --git a/test/langtools/jdk/jshell/SimpleRegressionTest.java b/test/langtools/jdk/jshell/SimpleRegressionTest.java index 1e347cfd207e..4cd7c8b71eb1 100644 --- a/test/langtools/jdk/jshell/SimpleRegressionTest.java +++ b/test/langtools/jdk/jshell/SimpleRegressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -25,7 +25,7 @@ * @test 8130450 8158906 8154374 8166400 8171892 8173807 8173848 8282434 * @summary simple regression test * @build KullaTesting TestingInputStream - * @run testng SimpleRegressionTest + * @run junit SimpleRegressionTest */ @@ -36,53 +36,56 @@ import jdk.jshell.Snippet; import jdk.jshell.VarSnippet; import jdk.jshell.SnippetEvent; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.SubKind.TEMP_VAR_EXPRESSION_SUBKIND; import static jdk.jshell.Snippet.Status.VALID; -import org.testng.annotations.BeforeMethod; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class SimpleRegressionTest extends KullaTesting { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("local")); } + @Test public void testSnippetMemberAssignment() { assertEval("class C { int y; }"); assertEval("C c = new C();"); assertVarKeyMatch("c.y = 4;", true, "$1", TEMP_VAR_EXPRESSION_SUBKIND, "int", added(VALID)); } + @Test public void testUserTakesTempVarName() { assertEval("int $2 = 4;"); assertEval("String $1;"); assertVarKeyMatch("1234;", true, "$3", TEMP_VAR_EXPRESSION_SUBKIND, "int", added(VALID)); } + @Test public void testCompileThrow() { assertEvalException("throw new Exception();"); } + @Test public void testMultiSnippetDependencies() { List events = assertEval("int a = 3, b = a+a, c = b *100;", DiagCheck.DIAG_OK, DiagCheck.DIAG_OK, chain(added(VALID)), chain(added(VALID)), chain(added(VALID))); - assertEquals(events.get(0).value(), "3"); - assertEquals(events.get(1).value(), "6"); - assertEquals(events.get(2).value(), "600"); + assertEquals("3", events.get(0).value()); + assertEquals("6", events.get(1).value()); + assertEquals("600", events.get(2).value()); assertEval("c;", "600"); } + @Test public void testLessThanParsing() { assertEval("int x = 3;", "3"); assertEval("int y = 4;", "4"); @@ -92,18 +95,22 @@ public void testLessThanParsing() { assertEval("x < y && y < z", "true"); } + @Test public void testNotStmtCannotResolve() { assertDeclareFail("dfasder;", new ExpectedDiagnostic("compiler.err.cant.resolve.location", 0, 7, 0, -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void testNotStmtIncomparable() { assertDeclareFail("true == 5.0;", new ExpectedDiagnostic("compiler.err.incomparable.types", 0, 11, 5, -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void testStringAdd() { assertEval("String s = \"a\" + \"b\";", "\"ab\""); } + @Test public void testExprSanity() { assertEval("int x = 3;", "3"); assertEval("int y = 4;", "4"); @@ -111,13 +118,15 @@ public void testExprSanity() { assertActiveKeys(); } + @Test public void testGenericMethodCrash() { assertDeclareWarn1(" void f(T...a) {}", (ExpectedDiagnostic) null); Snippet sn = methodKey(assertEval(" R n(R x) { return x; }", added(VALID))); VarSnippet sne = varKey(assertEval("n(5)", added(VALID))); - assertEquals(sne.typeName(), "Integer"); + assertEquals("Integer", sne.typeName()); } + @Test public void testLongRemoteStrings() { //8158906 assertEval("String m(int x) { byte[] b = new byte[x]; for (int i = 0; i < x; ++i) b[i] = (byte) 'a'; return new String(b); }"); boolean[] shut = new boolean[1]; @@ -127,12 +136,13 @@ public void testLongRemoteStrings() { //8158906 for (String len : new String[]{"12345", "64000", "65535", "65536", "120000"}) { List el = assertEval("m(" + len + ");"); assertFalse(shut[0], "JShell died with long string"); - assertEquals(el.size(), 1, "Excepted one event"); + assertEquals(1, el.size(), "Excepted one event"); assertTrue(el.get(0).value().length() > 10000, "Expected truncated but long String, got: " + el.get(0).value().length()); } } + @Test public void testLongRemoteJapaneseStrings() { //8158906 assertEval("import java.util.stream.*;"); assertEval("String m(int x) { return Stream.generate(() -> \"\u3042\").limit(x).collect(Collectors.joining()); }"); @@ -143,13 +153,14 @@ public void testLongRemoteJapaneseStrings() { //8158906 for (String len : new String[]{"12345", "21843", "21844", "21845", "21846", "64000", "65535", "65536", "120000"}) { List el = assertEval("m(" + len + ");"); assertFalse(shut[0], "JShell died with long string"); - assertEquals(el.size(), 1, "Excepted one event"); + assertEquals(1, el.size(), "Excepted one event"); assertTrue(el.get(0).value().length() > 10000, "Expected truncated but long String, got: " + el.get(0).value().length()); } } // 8130450 + @Test public void testDuplicate() { Snippet snm = methodKey(assertEval("void mm() {}", added(VALID))); assertEval("void mm() {}", @@ -161,11 +172,13 @@ public void testDuplicate() { ste(snv, VALID, OVERWRITTEN, false, MAIN_SNIPPET)); } + @Test public void testContextClassLoader() { assertEval("class C {}"); assertEval("C.class.getClassLoader() == Thread.currentThread().getContextClassLoader()", "true"); } + @Test public void testArrayRepresentation() { assertEval("new int[4]", "int[4] { 0, 0, 0, 0 }"); assertEval("new int[0]", "int[0] { }"); @@ -183,6 +196,7 @@ public void testArrayRepresentation() { "Object[3] { \"howdy\", int[3] { 33, 44, 55 }, String[2] { \"up\", \"down\" } }"); } + @Test public void testMultiDimArrayRepresentation() { assertEval("new int[3][1]", "int[3][] { int[1] { 0 }, int[1] { 0 }, int[1] { 0 } }"); @@ -199,6 +213,7 @@ public void testMultiDimArrayRepresentation() { "boolean[2][][] { boolean[1][] { boolean[3] { false, false, false } }, boolean[1][] { boolean[3] { false, false, false } } }"); } + @Test public void testStringRepresentation() { assertEval("\"A!\\rB!\"", "\"A!\\rB!\""); @@ -220,6 +235,7 @@ public void testStringRepresentation() { "\"a\u032Ea\""); } + @Test public void testCharRepresentation() { for (String s : new String[]{"'A'", "'Z'", "'0'", "'9'", "'a'", "'z'", "'*'", "'%'", diff --git a/test/langtools/jdk/jshell/SnippetEventToStringTest.java b/test/langtools/jdk/jshell/SnippetEventToStringTest.java new file mode 100644 index 000000000000..7dacafe93d22 --- /dev/null +++ b/test/langtools/jdk/jshell/SnippetEventToStringTest.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +/* + * @test + * @bug 8350808 + * @summary Check for proper formatting of SnippetEvent.toString() + * @run junit SnippetEventToStringTest + */ + +import java.util.Map; +import java.util.List; + +import jdk.jshell.JShell; +import jdk.jshell.SnippetEvent; +import jdk.jshell.execution.LocalExecutionControlProvider; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class SnippetEventToStringTest { + + public String[][] sourceLevels() { + return new String[][] { + { "*", ",causeSnippet=null" }, + { "123", ",value=123" }, + { "throw new Exception(\"foo\");", ",exception=jdk.jshell.EvalException: foo" } + }; + } + + @ParameterizedTest + @MethodSource("sourceLevels") + void verifySnippetEvent(String source, String match) { + try (JShell jsh = JShell.builder().executionEngine(new LocalExecutionControlProvider(), Map.of()).build()) { + List result = jsh.eval(source); + assertEquals(1, result.size()); + String string = result.get(0).toString(); + if (!string.contains(match)) + throw new AssertionError(String.format("\"%s\" not found in \"%s\"", match, string)); + } + } +} diff --git a/test/langtools/jdk/jshell/SnippetHighlightTest.java b/test/langtools/jdk/jshell/SnippetHighlightTest.java index 9c59a3d80163..fb954706aa8e 100644 --- a/test/langtools/jdk/jshell/SnippetHighlightTest.java +++ b/test/langtools/jdk/jshell/SnippetHighlightTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -32,22 +32,22 @@ * jdk.jshell/jdk.jshell:open * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng SnippetHighlightTest + * @run junit SnippetHighlightTest */ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.testng.annotations.Test; import jdk.jshell.SourceCodeAnalysis.Highlight; -import static org.testng.Assert.*; +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.Test; -@Test public class SnippetHighlightTest extends KullaTesting { + @Test public void testMemberExpr() { assertEval("@Deprecated class TestClass { }"); assertEval("class TestConstructor { @Deprecated TestConstructor() {} }"); @@ -99,6 +99,7 @@ public void testMemberExpr() { "Highlight[start=5, end=11, attributes=[DECLARATION]]"); } + @Test public void testClassErrorRecovery() { //JDK-8301580 assertHighlights(""" class C { @@ -116,7 +117,7 @@ class C { private void assertHighlights(String code, String... expected) { List completions = computeHighlights(code); - assertEquals(completions, Arrays.asList(expected), "Input: " + code + ", " + completions.toString()); + assertEquals(Arrays.asList(expected), completions, "Input: " + code + ", " + completions.toString()); } private List computeHighlights(String code) { diff --git a/test/langtools/jdk/jshell/SnippetStatusListenerTest.java b/test/langtools/jdk/jshell/SnippetStatusListenerTest.java index 14ea0b956a70..205749af277e 100644 --- a/test/langtools/jdk/jshell/SnippetStatusListenerTest.java +++ b/test/langtools/jdk/jshell/SnippetStatusListenerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -25,7 +25,7 @@ * @test * @summary Subscribe tests * @build KullaTesting TestingInputStream - * @run testng SnippetStatusListenerTest + * @run junit SnippetStatusListenerTest */ import java.util.ArrayList; @@ -37,14 +37,16 @@ import jdk.jshell.JShell.Subscription; import jdk.jshell.SnippetEvent; import jdk.jshell.TypeDeclSnippet; -import org.testng.annotations.Test; import static jdk.jshell.Snippet.Status.*; -import static org.testng.Assert.assertEquals; +import org.junit.jupiter.api.Assertions; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class SnippetStatusListenerTest extends KullaTesting { + @Test public void testTwoSnippetEventListeners() { SnippetListener listener1 = new SnippetListener(); SnippetListener listener2 = new SnippetListener(); @@ -61,45 +63,52 @@ public void testTwoSnippetEventListeners() { assertEval("int a = 0;"); List events1 = Collections.unmodifiableList(listener1.getEvents()); - assertEquals(events1, listener2.getEvents(), "Checking got events"); + assertEquals(listener2.getEvents(), events1, "Checking got events"); getState().unsubscribe(subscription1); assertDrop(f, DiagCheck.DIAG_IGNORE, DiagCheck.DIAG_IGNORE, ste(f, REJECTED, DROPPED, false, null)); assertEval("void f() { }", added(VALID)); assertEvalException("throw new RuntimeException();"); - assertEquals(listener1.getEvents(), events1, "Checking that unsubscribed listener does not get events"); + assertEquals(events1, listener1.getEvents(), "Checking that unsubscribed listener does not get events"); List events2 = new ArrayList<>(listener2.getEvents()); events2.removeAll(events1); - assertEquals(events2.size(), 3, "The second listener got events"); + assertEquals(3, events2.size(), "The second listener got events"); } - @Test(expectedExceptions = NullPointerException.class) + @Test public void testNullCallback() { - getState().onSnippetEvent(null); + Assertions.assertThrows(NullPointerException.class, () -> { + getState().onSnippetEvent(null); + }); } - @Test(expectedExceptions = IllegalStateException.class) + @Test public void testSubscriptionAfterClose() { - getState().close(); - getState().onSnippetEvent(e -> {}); + Assertions.assertThrows(IllegalStateException.class, () -> { + getState().close(); + getState().onSnippetEvent(e -> {}); + }); } - @Test(expectedExceptions = IllegalStateException.class, - enabled = false) //TODO 8139873 + @Test //TODO 8139873 + @Disabled public void testSubscriptionAfterShutdown() { - assertEval("System.exit(0);"); - getState().onSnippetEvent(e -> {}); + Assertions.assertThrows(IllegalStateException.class, () -> { + assertEval("System.exit(0);"); + getState().onSnippetEvent(e -> {}); + }); } + @Test public void testSubscriptionToAnotherState() { SnippetListener listener = new SnippetListener(); Subscription subscription = getState().onSnippetEvent(listener); tearDown(); setUp(); assertEval("int x;"); - assertEquals(Collections.emptyList(), listener.getEvents(), "No events"); + assertEquals(listener.getEvents(), Collections.emptyList(), "No events"); getState().unsubscribe(subscription); } diff --git a/test/langtools/jdk/jshell/SnippetTest.java b/test/langtools/jdk/jshell/SnippetTest.java index 3ccd0e42f4b8..3e5bdbbf3242 100644 --- a/test/langtools/jdk/jshell/SnippetTest.java +++ b/test/langtools/jdk/jshell/SnippetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -26,74 +26,86 @@ * @bug 8139829 * @summary test accessors of Snippet * @build KullaTesting TestingInputStream - * @run testng SnippetTest + * @run junit SnippetTest */ import jdk.jshell.Snippet; import jdk.jshell.DeclarationSnippet; -import org.testng.annotations.Test; import jdk.jshell.MethodSnippet; import jdk.jshell.Snippet.Status; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.Status.RECOVERABLE_DEFINED; import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.Status.RECOVERABLE_NOT_DEFINED; import static jdk.jshell.Snippet.SubKind.*; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class SnippetTest extends KullaTesting { + @Test public void testImportKey() { assertImportKeyMatch("import java.util.List;", "List", SINGLE_TYPE_IMPORT_SUBKIND, added(VALID)); assertImportKeyMatch("import java.util.*;", "java.util.*", TYPE_IMPORT_ON_DEMAND_SUBKIND, added(VALID)); assertImportKeyMatch("import static java.lang.String.*;", "java.lang.String.*", STATIC_IMPORT_ON_DEMAND_SUBKIND, added(VALID)); } + @Test public void testClassKey() { assertDeclarationKeyMatch("class X {}", false, "X", CLASS_SUBKIND, added(VALID)); } + @Test public void testInterfaceKey() { assertDeclarationKeyMatch("interface I {}", false, "I", INTERFACE_SUBKIND, added(VALID)); } + @Test public void testEnumKey() { assertDeclarationKeyMatch("enum E {}", false, "E", ENUM_SUBKIND, added(VALID)); } + @Test public void testAnnotationKey() { assertDeclarationKeyMatch("@interface A {}", false, "A", ANNOTATION_TYPE_SUBKIND, added(VALID)); } + @Test public void testMethodKey() { assertDeclarationKeyMatch("void m() {}", false, "m", METHOD_SUBKIND, added(VALID)); } + @Test public void testVarDeclarationKey() { assertVarKeyMatch("int a;", true, "a", VAR_DECLARATION_SUBKIND, "int", added(VALID)); } + @Test public void testVarDeclarationWithInitializerKey() { assertVarKeyMatch("double b = 9.0;", true, "b", VAR_DECLARATION_WITH_INITIALIZER_SUBKIND, "double", added(VALID)); } + @Test public void testTempVarExpressionKey() { assertVarKeyMatch("47;", true, "$1", TEMP_VAR_EXPRESSION_SUBKIND, "int", added(VALID)); } + @Test public void testVarValueKey() { assertEval("double x = 4;", "4.0"); assertExpressionKeyMatch("x;", "x", VAR_VALUE_SUBKIND, "double"); } + @Test public void testAssignmentKey() { assertEval("int y;"); assertExpressionKeyMatch("y = 4;", "y", ASSIGNMENT_SUBKIND, "int"); } + @Test public void testStatementKey() { assertKeyMatch("if (true) {}", true, STATEMENT_SUBKIND, added(VALID)); assertKeyMatch("while (true) { break; }", true, STATEMENT_SUBKIND, added(VALID)); @@ -101,10 +113,12 @@ public void testStatementKey() { assertKeyMatch("for (;;) { break; }", true, STATEMENT_SUBKIND, added(VALID)); } + @Test public void noKeys() { assertActiveKeys(new DeclarationSnippet[0]); } + @Test public void testKeyId1() { Snippet a = classKey(assertEval("class A { }")); assertEval("void f() { }"); @@ -116,7 +130,8 @@ public void testKeyId1() { assertActiveKeys(); } - @Test(enabled = false) // TODO 8081689 + @Test // TODO 8081689 + @Disabled public void testKeyId2() { Snippet g = methodKey(assertEval("void g() { f(); }", added(RECOVERABLE_DEFINED))); Snippet f = methodKey(assertEval("void f() { }", @@ -136,6 +151,7 @@ public void testKeyId2() { assertActiveKeys(); } + @Test public void testKeyId3() { Snippet g = methodKey(assertEval("void g() { f(); }", added(RECOVERABLE_DEFINED))); Snippet f = methodKey(assertEval("void f() { }", @@ -154,6 +170,7 @@ public void testKeyId3() { assertActiveKeys(); } + @Test public void testBooleanSnippetQueries() { Snippet nd = varKey(assertEval("blort x;", added(RECOVERABLE_NOT_DEFINED))); assertTrue(nd.kind().isPersistent(), "nd.isPersistent"); diff --git a/test/langtools/jdk/jshell/SourceLevelTest.java b/test/langtools/jdk/jshell/SourceLevelTest.java index ce5572e6f712..f1092a5d2e89 100644 --- a/test/langtools/jdk/jshell/SourceLevelTest.java +++ b/test/langtools/jdk/jshell/SourceLevelTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -26,15 +26,16 @@ * @bug 8259820 * @summary Check JShell can handle -source 8 * @modules jdk.jshell - * @run testng SourceLevelTest + * @run junit SourceLevelTest */ -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SourceLevelTest extends ReplToolTesting { - @DataProvider(name="sourceLevels") public Object[][] sourceLevels() { return new Object[][] { new Object[] {"8"}, @@ -42,7 +43,8 @@ public Object[][] sourceLevels() { }; } - @Test(dataProvider="sourceLevels") + @ParameterizedTest + @MethodSource("sourceLevels") public void testSourceLevel(String sourceLevel) { test(new String[] {"-C", "-source", "-C", sourceLevel}, (a) -> assertCommand(a, "1 + 1", "$1 ==> 2"), diff --git a/test/langtools/jdk/jshell/StartOptionTest.java b/test/langtools/jdk/jshell/StartOptionTest.java index aa8d9be03a9e..16d362dda2c1 100644 --- a/test/langtools/jdk/jshell/StartOptionTest.java +++ b/test/langtools/jdk/jshell/StartOptionTest.java @@ -22,15 +22,16 @@ */ /* - * @test 8151754 8080883 8160089 8170162 8166581 8172102 8171343 8178023 8186708 8179856 8185840 8190383 + * @test 8151754 8080883 8160089 8170162 8166581 8172102 8171343 8178023 8186708 8179856 8185840 8190383 8341833 * @summary Testing startExCe-up options. * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool + * jdk.jshell/jdk.internal.jshell.tool.resources:+open * @library /tools/lib * @build Compiler toolbox.ToolBox - * @run testng StartOptionTest + * @run junit StartOptionTest */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -38,24 +39,26 @@ import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.text.MessageFormat; import java.util.HashMap; import java.util.Locale; +import java.util.ResourceBundle; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; +import jdk.jshell.JShell; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import jdk.jshell.tool.JavaShellToolBuilder; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import org.junit.jupiter.api.AfterEach; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class StartOptionTest { protected ByteArrayOutputStream cmdout; @@ -97,7 +100,7 @@ protected void check(ByteArrayOutputStream str, Consumer checkOut, Strin if (checkOut != null) { checkOut.accept(out); } else { - assertEquals(out, "", label + ": Expected empty -- "); + assertEquals("", out, label + ": Expected empty -- "); } } @@ -105,7 +108,7 @@ protected void checkExit(int ec, Consumer checkCode) { if (checkCode != null) { checkCode.accept(ec); } else { - assertEquals(ec, 0, "Expected standard exit code (0), but found: " + ec); + assertEquals(0, ec, "Expected standard exit code (0), but found: " + ec); } } @@ -126,10 +129,17 @@ protected void startExCoUoCeCn(Consumer checkExitCode, check(usererr, null, "usererr"); } + protected void startCheckError(Consumer checkError, + String... args) { + runShell(args); + check(cmderr, checkError, "userout"); + check(userout, null, "userout"); + check(usererr, null, "usererr"); + } + // Start with an exit code and command error check protected void startExCe(int eec, Consumer checkError, String... args) { - StartOptionTest.this.startExCoUoCeCn( - (Integer ec) -> assertEquals((int) ec, eec, + StartOptionTest.this.startExCoUoCeCn((Integer ec) -> assertEquals(eec, (int) ec, "Expected error exit code (" + eec + "), but found: " + ec), null, null, checkError, null, args); } @@ -142,7 +152,7 @@ protected void startCo(Consumer checkCmdOutput, String... args) { private Consumer assertOrNull(String expected, String label) { return expected == null ? null - : s -> assertEquals(s.replaceAll("\\r\\n?", "\n").trim(), expected.trim(), label); + : s -> assertEquals(expected.trim(), s.replaceAll("\\r\\n?", "\n").trim(), label); } // Start and check the resultant: exit code (Ex), command output (Co), @@ -153,10 +163,9 @@ protected void startExCoUoCeCn(int expectedExitCode, String expectedError, String expectedConsole, String... args) { - startExCoUoCeCn( - expectedExitCode == 0 + startExCoUoCeCn(expectedExitCode == 0 ? null - : (Integer i) -> assertEquals((int) i, expectedExitCode, + : (Integer i) -> assertEquals(expectedExitCode, (int) i, "Expected exit code (" + expectedExitCode + "), but found: " + i), assertOrNull(expectedCmdOutput, "cmdout: "), assertOrNull(expectedUserOutput, "userout: "), @@ -180,7 +189,7 @@ protected void startUo(String expectedUserOutput, String... args) { startExCoUoCeCn(0, null, expectedUserOutput, null, null, args); } - @BeforeMethod + @BeforeEach public void setUp() { cmdout = new ByteArrayOutputStream(); cmderr = new ByteArrayOutputStream(); @@ -203,6 +212,7 @@ protected void setIn(String s) { } // Test load files + @Test public void testCommandFile() { String fn = writeToFile("String str = \"Hello \"\n" + "/list\n" + @@ -217,6 +227,7 @@ public void testCommandFile() { } // Test that the usage message is printed + @Test public void testUsage() { for (String opt : new String[]{"-?", "-h", "--help"}) { startCo(s -> { @@ -229,6 +240,7 @@ public void testUsage() { } // Test the --help-extra message + @Test public void testHelpExtra() { for (String opt : new String[]{"-X", "--help-extra"}) { startCo(s -> { @@ -241,12 +253,14 @@ public void testHelpExtra() { } // Test handling of bogus options + @Test public void testUnknown() { startExCe(1, "Unknown option: u", "-unknown"); startExCe(1, "Unknown option: unknown", "--unknown"); } // Test that input is read with "-" and there is no extra output. + @Test public void testHypenFile() { setIn("System.out.print(\"Hello\");\n"); startUo("Hello", "-"); @@ -263,6 +277,7 @@ public void testHypenFile() { } // Test that user specified exit codes are propagated + @Test public void testExitCode() { setIn("/exit 57\n"); startExCoUoCeCn(57, null, null, null, "-> /exit 57", "-s"); @@ -277,11 +292,13 @@ public void testExitCode() { } // Test that non-existent load file sends output to stderr and does not startExCe (no welcome). + @Test public void testUnknownLoadFile() { startExCe(1, "File 'UNKNOWN' for 'jshell' is not found.", "UNKNOWN"); } // Test bad usage of the --startup option + @Test public void testStartup() { String fn = writeToFile(""); startExCe(1, "Argument to startup missing.", "--startup"); @@ -291,18 +308,21 @@ public void testStartup() { } // Test an option that causes the back-end to fail is propagated + @Test public void testStartupFailedOption() { startExCe(1, s -> assertTrue(s.contains("Unrecognized option: -hoge-foo-bar"), "cmderr: " + s), "-R-hoge-foo-bar"); } // Test the use of non-existant files with the --startup option + @Test public void testStartupUnknown() { startExCe(1, "File 'UNKNOWN' for '--startup' is not found.", "--startup", "UNKNOWN"); startExCe(1, "File 'UNKNOWN' for '--startup' is not found.", "--startup", "DEFAULT", "--startup", "UNKNOWN"); } // Test bad usage of --class-path option + @Test public void testClasspath() { for (String cp : new String[]{"--class-path"}) { startExCe(1, "Only one --class-path option may be used.", cp, ".", "--class-path", "."); @@ -311,12 +331,14 @@ public void testClasspath() { } // Test bogus module on --add-modules option + @Test public void testUnknownModule() { startExCe(1, s -> assertTrue(s.contains("rror") && s.contains("unKnown"), "cmderr: " + s), "--add-modules", "unKnown"); } // Test that muliple feedback options fail + @Test public void testFeedbackOptionConflict() { startExCe(1, "Only one feedback option (--feedback, -q, -s, or -v) may be used.", "--feedback", "concise", "--feedback", "verbose"); @@ -331,12 +353,14 @@ public void testFeedbackOptionConflict() { } // Test bogus arguments to the --feedback option + @Test public void testNegFeedbackOption() { startExCe(1, "Argument to feedback missing.", "--feedback"); startExCe(1, "Does not match any current feedback mode: blorp -- --feedback blorp", "--feedback", "blorp"); } // Test --version + @Test public void testVersion() { startCo(s -> { assertTrue(s.startsWith("jshell"), "unexpected version: " + s); @@ -346,6 +370,7 @@ public void testVersion() { } // Test --show-version + @Test public void testShowVersion() { startExCoUoCeCn(null, s -> { @@ -358,7 +383,26 @@ public void testShowVersion() { "--show-version"); } - @AfterMethod + public void testErroneousFile() { + String code = """ + var v = ( + System.console().readLine("prompt: "); + /exit + """; + String readLinePrompt = writeToFile(code); + String expectedErrorFormat = + ResourceBundle.getBundle("jdk.internal.jshell.tool.resources.l10n", + Locale.getDefault(), + JShell.class.getModule()) + .getString("jshell.err.incomplete.input"); + String expectedError = + new MessageFormat(expectedErrorFormat).format(new Object[] {code}); + startCheckError(s -> assertEquals(expectedError, s), + readLinePrompt); + } + + + @AfterEach public void tearDown() { cmdout = null; cmderr = null; diff --git a/test/langtools/jdk/jshell/StopExecutionTest.java b/test/langtools/jdk/jshell/StopExecutionTest.java index 389794d35d24..12f95ea99c0d 100644 --- a/test/langtools/jdk/jshell/StopExecutionTest.java +++ b/test/langtools/jdk/jshell/StopExecutionTest.java @@ -27,7 +27,7 @@ * @summary Test JShell#stop * @modules jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream - * @run testng StopExecutionTest + * @run junit StopExecutionTest */ import java.io.IOException; @@ -42,28 +42,30 @@ import jdk.internal.jshell.tool.StopDetectingInputStream; import jdk.internal.jshell.tool.StopDetectingInputStream.State; import jdk.jshell.JShell; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - -@Test public class StopExecutionTest extends KullaTesting { private final Object lock = new Object(); private boolean isStopped; - @Test(enabled = false) // TODO 8129546 + @Test // TODO 8129546 + @Disabled public void testStopLoop() throws InterruptedException { scheduleStop("while (true) ;"); } - @Test(enabled = false) // TODO 8129546 + @Test // TODO 8129546 + @Disabled public void testStopASleep() throws InterruptedException { scheduleStop("while (true) { try { Thread.sleep(100); } catch (InterruptedException ex) { } }"); } - @Test(enabled = false) // TODO 8129546 + @Test // TODO 8129546 + @Disabled public void testScriptCatchesStop() throws Exception { scheduleStop("for (int i = 0; i < 30; i++) { try { Thread.sleep(100); } catch (Throwable ex) { } }"); } @@ -104,6 +106,7 @@ private void scheduleStop(String src) throws InterruptedException { t.join(); } + @Test public void testStopDetectingInputRandom() throws IOException { long seed = System.nanoTime(); Random r = new Random(seed); @@ -129,10 +132,11 @@ private void doChunk(StopDetectingInputStream buffer, int chunkSize) throws IOEx for (int c = 0; c < chunkSize; c++) { int read = buffer.read(); - assertEquals(read, c); + assertEquals(c, read); } } + @Test public void testStopDetectingInputBufferWaitStop() throws Exception { Runnable shouldNotHappenRun = () -> { throw new AssertionError("Should not happen."); }; diff --git a/test/langtools/jdk/jshell/T8146368/JShellTest8146368.java b/test/langtools/jdk/jshell/T8146368/JShellTest8146368.java index 8cf92545bb5c..21cb37e65b3a 100644 --- a/test/langtools/jdk/jshell/T8146368/JShellTest8146368.java +++ b/test/langtools/jdk/jshell/T8146368/JShellTest8146368.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 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 @@ -27,14 +27,14 @@ * @summary Test Smashing Error when user language is Japanese * @library /tools/lib /jdk/jshell * @build KullaTesting - * @run testng/othervm -Duser.language=ja JShellTest8146368 + * @run junit/othervm -Duser.language=ja JShellTest8146368 */ import static jdk.jshell.Snippet.Status.RECOVERABLE_NOT_DEFINED; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class JShellTest8146368 extends KullaTesting { + @Test public void test() { assertEval("class A extends B {}", added(RECOVERABLE_NOT_DEFINED)); assertEval("und m() { return new und(); }", added(RECOVERABLE_NOT_DEFINED)); diff --git a/test/langtools/jdk/jshell/T8146368/JShellToolTest8146368.java b/test/langtools/jdk/jshell/T8146368/JShellToolTest8146368.java index 101083c0e271..3a7db71be713 100644 --- a/test/langtools/jdk/jshell/T8146368/JShellToolTest8146368.java +++ b/test/langtools/jdk/jshell/T8146368/JShellToolTest8146368.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2016, 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 @@ -28,13 +28,13 @@ * @modules jdk.jshell/jdk.internal.jshell.tool * @library /tools/lib /jdk/jshell * @build ReplToolTesting - * @run testng/othervm -Duser.language=ja JShellToolTest8146368 + * @run junit/othervm -Duser.language=ja JShellToolTest8146368 */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class JShellToolTest8146368 extends ReplToolTesting { + @Test public void test() { test( a -> assertCommand(a, "class A extends B {}", "| created class A, however, it cannot be referenced until class B is declared\n"), diff --git a/test/langtools/jdk/jshell/Test8294583.java b/test/langtools/jdk/jshell/Test8294583.java index 3d2ce2e36381..281911b71133 100644 --- a/test/langtools/jdk/jshell/Test8294583.java +++ b/test/langtools/jdk/jshell/Test8294583.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -26,22 +26,23 @@ * @bug 8294583 * @summary JShell: NPE in switch with non existing record pattern * @build KullaTesting TestingInputStream - * @run testng Test8294583 + * @run junit Test8294583 */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class Test8294583 extends KullaTesting { + @Test public void test() { assertEvalFail("switch (new Object()) {\n" + " case Foo() -> {}\n" + "};"); } - @org.testng.annotations.BeforeMethod + @BeforeEach public void setUp() { super.setUp(bc -> bc.compilerOptions("--source", System.getProperty("java.specification.version"), "--enable-preview").remoteVMOptions("--enable-preview")); } diff --git a/test/langtools/jdk/jshell/Test8296012.java b/test/langtools/jdk/jshell/Test8296012.java index 73e5cc06ae0a..4f08861b952d 100644 --- a/test/langtools/jdk/jshell/Test8296012.java +++ b/test/langtools/jdk/jshell/Test8296012.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 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 @@ -26,21 +26,22 @@ * @bug 8296012 * @summary jshell crashes on mismatched record pattern * @build KullaTesting TestingInputStream - * @run testng Test8296012 + * @run junit Test8296012 */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class Test8296012 extends KullaTesting { + @Test public void test() { assertEval("record Foo(int x, int y) {}"); assertEvalFail("switch (new Foo(1, 2)) { case Foo(int z) -> z; }"); } - @org.testng.annotations.BeforeMethod + @BeforeEach public void setUp() { super.setUp(bc -> bc.compilerOptions("--source", System.getProperty("java.specification.version"), "--enable-preview").remoteVMOptions("--enable-preview")); } diff --git a/test/langtools/jdk/jshell/ToolBasicTest.java b/test/langtools/jdk/jshell/ToolBasicTest.java index b5128de738a9..5015d1f64b12 100644 --- a/test/langtools/jdk/jshell/ToolBasicTest.java +++ b/test/langtools/jdk/jshell/ToolBasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, 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 @@ -32,7 +32,7 @@ * @library /tools/lib * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build KullaTesting TestingInputStream Compiler - * @run testng/timeout=600 ToolBasicTest + * @run junit/timeout=600 ToolBasicTest * @key intermittent */ @@ -57,19 +57,18 @@ import java.util.stream.Stream; import com.sun.net.httpserver.HttpServer; -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.fail; - -@Test public class ToolBasicTest extends ReplToolTesting { + @Test public void elideStartUpFromList() { - test( - (a) -> assertCommandOutputContains(a, "123", "==> 123"), + test((a) -> assertCommandOutputContains(a, "123", "==> 123"), (a) -> assertCommandCheckOutput(a, "/list", (s) -> { int cnt; try (Scanner scanner = new Scanner(s)) { @@ -81,11 +80,12 @@ public void elideStartUpFromList() { } } } - assertEquals(cnt, 1, "Expected only one listed line"); + assertEquals(1, cnt, "Expected only one listed line"); }) ); } + @Test public void elideStartUpFromSave() throws IOException { Compiler compiler = new Compiler(); Path path = compiler.getPath("myfile"); @@ -94,10 +94,11 @@ public void elideStartUpFromSave() throws IOException { (a) -> assertCommand(a, "/save " + path.toString(), "") ); try (Stream lines = Files.lines(path)) { - assertEquals(lines.count(), 1, "Expected only one saved line"); + assertEquals(1, lines.count(), "Expected only one saved line"); } } + @Test public void testInterrupt() { ReplTest interrupt = (a) -> assertCommand(a, "\u0003", ""); for (String s : new String[] { "", "\u0003" }) { @@ -132,6 +133,7 @@ public void testInterrupt() { } } + @Test public void testCtrlD() { test(false, new String[]{"--no-startup"}, a -> { @@ -193,6 +195,7 @@ private void assertStop(boolean after, String cmd, String output) { } } + @Test public void testStop() { test( (a) -> assertStop(a, "while (true) {}", ""), @@ -200,6 +203,7 @@ public void testStop() { ); } + @Test public void testRerun() { test(false, new String[] {"--no-startup"}, (a) -> assertCommand(a, "/0", "| No snippet with ID: 0"), @@ -221,7 +225,7 @@ public void testRerun() { final int finalI = i; Consumer check = (s) -> { String[] ss = s.split("\n"); - assertEquals(ss[0], codes[finalI]); + assertEquals(codes[finalI], ss[0]); assertTrue(ss.length > 1, s); }; tests.add((a) -> assertCommandCheckOutput(a, "/" + (finalI + 1), check)); @@ -231,7 +235,7 @@ public void testRerun() { final int finalI = i; Consumer check = (s) -> { String[] ss = s.split("\n"); - assertEquals(ss[0], codes[codes.length - finalI - 1]); + assertEquals(codes[codes.length - finalI - 1], ss[0]); assertTrue(ss.length > 1, s); }; tests.add((a) -> assertCommandCheckOutput(a, "/-" + (2 * finalI + 1), check)); @@ -241,11 +245,12 @@ public void testRerun() { tests.toArray(new ReplTest[tests.size()])); } + @Test public void test8142447() { Function> assertRerun = cmd -> (code, assertionCount) -> (a) -> assertCommandCheckOutput(a, cmd, s -> { String[] ss = s.split("\n"); - assertEquals(ss[0], code); + assertEquals(code, ss[0]); loadVariable(a, "int", "assertionCount", Integer.toString(assertionCount), Integer.toString(assertionCount)); }); ReplTest assertVariables = (a) -> assertCommandCheckOutput(a, "/v", assertVariables()); @@ -256,7 +261,7 @@ public void test8142447() { "void add(int n) { assertionCount += n; }"); test(new String[]{"--startup", startup.toString()}, (a) -> assertCommand(a, "add(1)", ""), // id: 1 - (a) -> assertCommandCheckOutput(a, "add(ONE)", s -> assertEquals(s.split("\n")[0], "| Error:")), // id: e1 + (a) -> assertCommandCheckOutput(a, "add(ONE)", s -> assertEquals("| Error:", s.split("\n")[0])), // id: e1 (a) -> assertVariable(a, "int", "ONE", "1", "1"), assertRerun.apply("/1").apply("add(1)", 2), assertVariables, assertRerun.apply("/e1").apply("add(ONE)", 3), assertVariables, @@ -270,6 +275,7 @@ public void test8142447() { ); } + @Test public void testClasspathDirectory() { Compiler compiler = new Compiler(); Path outDir = Paths.get("testClasspathDirectory"); @@ -285,6 +291,7 @@ public void testClasspathDirectory() { ); } + @Test public void testEnvInStartUp() { Compiler compiler = new Compiler(); Path outDir = Paths.get("testClasspathDirectory"); @@ -320,6 +327,7 @@ private String makeSimpleJar() { return compiler.getPath(outDir).resolve(jarName).toString(); } + @Test public void testClasspathJar() { String jarPath = makeSimpleJar(); test( @@ -332,6 +340,7 @@ public void testClasspathJar() { ); } + @Test public void testClasspathUserHomeExpansion() { String jarPath = makeSimpleJar(); String tilde = "~" + File.separator; @@ -346,6 +355,7 @@ public void testClasspathUserHomeExpansion() { ); } + @Test public void testBadClasspath() { String jarPath = makeSimpleJar(); Compiler compiler = new Compiler(); @@ -373,6 +383,7 @@ private String makeBadSourceJar() { return compiler.getPath(outDir).resolve(jarName).toString(); } + @Test public void testBadSourceJarClasspath() { String jarPath = makeBadSourceJar(); test( @@ -391,6 +402,7 @@ public void testBadSourceJarClasspath() { ); } + @Test public void testModulePath() { Compiler compiler = new Compiler(); Path modsDir = Paths.get("mods"); @@ -406,6 +418,7 @@ public void testModulePath() { ); } + @Test public void testModulePathUserHomeExpansion() { String tilde = "~" + File.separatorChar; test( @@ -415,6 +428,7 @@ public void testModulePathUserHomeExpansion() { ); } + @Test public void testBadModulePath() { Compiler compiler = new Compiler(); Path t1 = compiler.getPath("whatever/thing.zip"); @@ -425,6 +439,7 @@ public void testBadModulePath() { ); } + @Test public void testStartupFileOption() { Compiler compiler = new Compiler(); Path startup = compiler.getPath("StartupFileOption/startup.txt"); @@ -440,6 +455,7 @@ public void testStartupFileOption() { ); } + @Test public void testLoadingFromArgs() { Compiler compiler = new Compiler(); Path path = compiler.getPath("loading.repl"); @@ -450,6 +466,7 @@ public void testLoadingFromArgs() { ); } + @Test public void testReset() { test( (a) -> assertReset(a, "/res"), @@ -470,6 +487,7 @@ public void testReset() { ); } + @Test public void testOpen() { Compiler compiler = new Compiler(); Path path = compiler.getPath("testOpen.repl"); @@ -504,6 +522,7 @@ public void testOpen() { } } + @Test public void testOpenLocalFileUrl() { Compiler compiler = new Compiler(); Path path = compiler.getPath("testOpen.repl"); @@ -518,6 +537,7 @@ public void testOpenLocalFileUrl() { } } + @Test public void testOpenFileOverHttp() throws IOException { var script = "int a = 10;int b = 20;int c = a + b;"; @@ -549,6 +569,7 @@ public void testOpenFileOverHttp() throws IOException { } } + @Test public void testOpenResource() { test(new String[]{"-R", "-Duser.language=en", "-R", "-Duser.country=US"}, (a) -> assertCommand(a, "/open PRINTING", ""), @@ -559,6 +580,7 @@ public void testOpenResource() { ); } + @Test public void testSave() throws IOException { Compiler compiler = new Compiler(); Path path = compiler.getPath("testSave.repl"); @@ -573,7 +595,7 @@ public void testSave() throws IOException { (a) -> assertClass(a, "class A { public String toString() { return \"A\"; } }", "class", "A"), (a) -> assertCommand(a, "/save " + path.toString(), "") ); - assertEquals(Files.readAllLines(path), list); + assertEquals(list, Files.readAllLines(path)); } { List output = new ArrayList<>(); @@ -589,7 +611,7 @@ public void testSave() throws IOException { .collect(Collectors.toList()))), (a) -> assertCommand(a, "/save -all " + path.toString(), "") ); - assertEquals(Files.readAllLines(path), output); + assertEquals(output, Files.readAllLines(path)); } { List output = new ArrayList<>(); @@ -606,7 +628,7 @@ public void testSave() throws IOException { .collect(Collectors.toList()))), (a) -> assertCommand(a, "/save 2-3 1 4 " + path.toString(), "") ); - assertEquals(Files.readAllLines(path), output); + assertEquals(output, Files.readAllLines(path)); } { List output = new ArrayList<>(); @@ -621,10 +643,11 @@ public void testSave() throws IOException { (a) -> assertCommand(a, "/save -history " + path.toString(), "") ); output.add("/save -history " + path.toString()); - assertEquals(Files.readAllLines(path), output); + assertEquals(output, Files.readAllLines(path)); } } + @Test public void testStartRetain() { Compiler compiler = new Compiler(); Path startUpFile = compiler.getPath("startUp.txt"); @@ -655,6 +678,7 @@ public void testStartRetain() { ); } + @Test public void testStartSave() throws IOException { Compiler compiler = new Compiler(); Path startSave = compiler.getPath("startSave.txt"); @@ -662,9 +686,10 @@ public void testStartSave() throws IOException { List lines = Files.lines(startSave) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); - assertEquals(lines, START_UP); + assertEquals(START_UP, lines); } + @Test public void testConstrainedUpdates() { test( a -> assertClass(a, "class XYZZY { }", "class", "XYZZY"), @@ -674,6 +699,7 @@ public void testConstrainedUpdates() { ); } + @Test public void testRemoteExit() { test( a -> assertVariable(a, "int", "x"), @@ -686,11 +712,13 @@ public void testRemoteExit() { ); } + @Test public void testFeedbackNegative() { test(a -> assertCommandCheckOutput(a, "/set feedback aaaa", assertStartsWith("| Does not match any current feedback mode"))); } + @Test public void testFeedbackSilent() { for (String off : new String[]{"s", "silent"}) { test( @@ -702,6 +730,7 @@ public void testFeedbackSilent() { } } + @Test public void testFeedbackNormal() { Compiler compiler = new Compiler(); Path testNormalFile = compiler.getPath("testConciseNormal"); @@ -728,6 +757,7 @@ public void testFeedbackNormal() { } } + @Test public void testVarsWithNotActive() { test( a -> assertVariable(a, "Blath", "x"), @@ -735,6 +765,7 @@ public void testVarsWithNotActive() { ); } + @Test public void testHistoryReference() { test(false, new String[]{"--no-startup"}, a -> assertCommand(a, "System.err.println(99)", "", "", null, "", "99\n"), @@ -767,6 +798,7 @@ public void testHistoryReference() { ); } + @Test public void testRerunIdRange() { Compiler compiler = new Compiler(); Path startup = compiler.getPath("rangeStartup"); @@ -825,7 +857,8 @@ public void testRerunIdRange() { ); } - @Test(enabled = false) // TODO 8158197 + @Test // TODO 8158197 + @Disabled public void testHeadlessEditPad() { String prevHeadless = System.getProperty("java.awt.headless"); try { @@ -838,6 +871,7 @@ public void testHeadlessEditPad() { } } + @Test public void testAddExports() { test(false, new String[]{"--no-startup"}, a -> assertCommandOutputStartsWith(a, "import jdk.internal.misc.VM;", "| Error:") @@ -854,6 +888,7 @@ public void testAddExports() { ); } + @Test public void testRedeclareVariableNoInit() { test( a -> assertCommand(a, "Integer a;", "a ==> null"), @@ -865,6 +900,7 @@ public void testRedeclareVariableNoInit() { ); } + @Test public void testWarningUnchecked() { //8223688 test(false, new String[]{"--no-startup"}, a -> assertCommand(a, "abstract class A { A(T t){} }", "| created class A"), @@ -876,6 +912,7 @@ public void testWarningUnchecked() { //8223688 ); } + @Test public void testIndent() { //8223688 prefsMap.remove("INDENT"); test(false, new String[]{"--no-startup"}, @@ -887,6 +924,7 @@ public void testIndent() { //8223688 ); } + @Test public void testSystemExitStartUp() { Compiler compiler = new Compiler(); Path startup = compiler.getPath("SystemExitStartUp/startup.txt"); diff --git a/test/langtools/jdk/jshell/ToolCommandOptionTest.java b/test/langtools/jdk/jshell/ToolCommandOptionTest.java index ec137a3ec608..d647c28c20cf 100644 --- a/test/langtools/jdk/jshell/ToolCommandOptionTest.java +++ b/test/langtools/jdk/jshell/ToolCommandOptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -30,16 +30,16 @@ * jdk.compiler/com.sun.tools.javac.main * @library /tools/lib * @build ToolCommandOptionTest ReplToolTesting - * @run testng ToolCommandOptionTest + * @run junit ToolCommandOptionTest */ import java.nio.file.Path; -import org.testng.annotations.Test; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class ToolCommandOptionTest extends ReplToolTesting { + @Test public void listTest() { test( (a) -> assertCommand(a, "int x;", @@ -67,6 +67,7 @@ public void listTest() { ); } + @Test public void typesTest() { test( (a) -> assertCommand(a, "int x", @@ -92,6 +93,7 @@ public void typesTest() { ); } + @Test public void dropTest() { test(false, new String[]{"--no-startup"}, (a) -> assertCommand(a, "int x = 5;", @@ -120,6 +122,7 @@ public void dropTest() { ); } + @Test public void setEditorTest() { test( (a) -> assertCommand(a, "/set editor -furball", @@ -157,6 +160,7 @@ public void setEditorTest() { ); } + @Test public void retainEditorTest() { test( (a) -> assertCommand(a, "/set editor -retain -furball", @@ -211,6 +215,7 @@ public void retainEditorTest() { ); } + @Test public void setEditorEnvTest() { setEnvVar("EDITOR", "best one"); setEditorEnvSubtest(); @@ -244,6 +249,7 @@ private void setEditorEnvSubtest() { ); } + @Test public void setStartTest() { Compiler compiler = new Compiler(); Path startup = compiler.getPath("StartTest/startup.txt"); @@ -288,6 +294,7 @@ public void setStartTest() { ); } + @Test public void retainStartTest() { Compiler compiler = new Compiler(); Path startup = compiler.getPath("StartTest/startup.txt"); @@ -337,6 +344,7 @@ public void retainStartTest() { ); } + @Test public void setModeTest() { test( (a) -> assertCommandOutputContains(a, "/set mode", @@ -399,6 +407,7 @@ public void setModeTest() { ); } + @Test public void setModeSmashTest() { test( (a) -> assertCommand(a, "/set mode mymode -command", @@ -428,6 +437,7 @@ public void setModeSmashTest() { ); } + @Test public void retainModeTest() { test( (a) -> assertCommandOutputStartsWith(a, "/set mode -retain", @@ -531,6 +541,7 @@ public void retainModeTest() { ); } + @Test public void retainModeDeleteLocalTest() { test( (a) -> assertCommand(a, "/set mode rmdlt normal -command", diff --git a/test/langtools/jdk/jshell/ToolEnableNativeAccessTest.java b/test/langtools/jdk/jshell/ToolEnableNativeAccessTest.java index 212301c0fd83..54cae875d893 100644 --- a/test/langtools/jdk/jshell/ToolEnableNativeAccessTest.java +++ b/test/langtools/jdk/jshell/ToolEnableNativeAccessTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 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 @@ -26,12 +26,11 @@ * @bug 8268725 * @summary Tests for the --enable-native-access option * @modules jdk.jshell - * @run testng ToolEnableNativeAccessTest + * @run junit ToolEnableNativeAccessTest */ -import org.testng.annotations.Test; - -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class ToolEnableNativeAccessTest extends ReplToolTesting { diff --git a/test/langtools/jdk/jshell/ToolEnablePreviewTest.java b/test/langtools/jdk/jshell/ToolEnablePreviewTest.java index 61a54254455e..6e5d63eade9f 100644 --- a/test/langtools/jdk/jshell/ToolEnablePreviewTest.java +++ b/test/langtools/jdk/jshell/ToolEnablePreviewTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, 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 @@ -25,12 +25,11 @@ * @test * @bug 8199193 * @summary Tests for the --enable-preview option - * @run testng ToolEnablePreviewTest + * @run junit ToolEnablePreviewTest */ -import org.testng.annotations.Test; - -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class ToolEnablePreviewTest extends ReplToolTesting { diff --git a/test/langtools/jdk/jshell/ToolFormatTest.java b/test/langtools/jdk/jshell/ToolFormatTest.java index 3aaf5e79ea5f..5d25fb99928b 100644 --- a/test/langtools/jdk/jshell/ToolFormatTest.java +++ b/test/langtools/jdk/jshell/ToolFormatTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -31,21 +31,22 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream toolbox.ToolBox Compiler - * @run testng ToolFormatTest + * @run junit ToolFormatTest */ import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class ToolFormatTest extends ReplToolTesting { + @Test public void testSetFormat() { try { test( @@ -86,6 +87,7 @@ public void testSetFormat() { } } + @Test public void testSetFormatOverride() { test( (a) -> assertCommand(a, "/set mode tm -c", "| Created new feedback mode: tm"), @@ -138,6 +140,7 @@ public void testSetFormatOverride() { ); } + @Test public void testSetFormatSelectorSample() { test( (a) -> assertCommandOutputStartsWith(a, "/set mode ate -quiet", @@ -197,7 +200,8 @@ public void testSetFormatSelectorSample() { // A sampling of these has been added (above: testSetFormatSelectorSample). // See 8173007 // Save for possible future deep testing or debugging - @Test(enabled = false) + @Test + @Disabled public void testSetFormatSelector() { List tests = new ArrayList<>(); tests.add((a) -> assertCommandOutputStartsWith(a, "/set mode ate -quiet", @@ -278,6 +282,7 @@ boolean append(boolean ahead) { } } + @Test public void testSetTruncation() { try { test( @@ -309,6 +314,7 @@ public void testSetTruncation() { } } + @Test public void testDefaultTruncation() { test( (a) -> assertCommand(a, "char[] cs = new char[2000];", null), @@ -331,9 +337,9 @@ public void testDefaultTruncation() { ); } + @Test public void testPrompt() { - test( - (a) -> assertCommand(a, "/set mode tp -quiet", "| Created new feedback mode: tp"), + test((a) -> assertCommand(a, "/set mode tp -quiet", "| Created new feedback mode: tp"), (a) -> assertCommand(a, "/set prompt tp 'aaa' 'bbb'", ""), (a) -> assertCommand(a, "/set prompt tp", "| /set prompt tp \"aaa\" \"bbb\""), @@ -347,21 +353,21 @@ public void testPrompt() { (s) -> { try { BufferedReader rdr = new BufferedReader(new StringReader(s)); - assertEquals(rdr.readLine(), "| /set mode tp -quiet", + assertEquals("| /set mode tp -quiet", rdr.readLine(), "| /set mode tp -quiet"); - assertEquals(rdr.readLine(), "| /set prompt tp \"aaa\" \"bbb\"", + assertEquals("| /set prompt tp \"aaa\" \"bbb\"", rdr.readLine(), "| /set prompt tp \"aaa\" \"bbb\""); String l = rdr.readLine(); while (l.startsWith("| /set format tp ")) { l = rdr.readLine(); } - assertEquals(l, "| /set mode -retain tp", + assertEquals("| /set mode -retain tp", l, "| /set mode -retain tp"); - assertEquals(rdr.readLine(), "| ", + assertEquals("| ", rdr.readLine(), "| "); - assertEquals(rdr.readLine(), "| /set mode tp -quiet", + assertEquals("| /set mode tp -quiet", rdr.readLine(), "| /set mode tp -quiet"); - assertEquals(rdr.readLine(), "| /set prompt tp \"ccc\" \"ddd\"", + assertEquals("| /set prompt tp \"ccc\" \"ddd\"", rdr.readLine(), "| /set prompt tp \"ccc\" \"ddd\""); } catch (IOException ex) { fail("threw " + ex); @@ -370,12 +376,14 @@ public void testPrompt() { ); } + @Test public void testShowFeedbackModes() { test( (a) -> assertCommandOutputContains(a, "/set feedback", "normal") ); } + @Test public void testSetNewModeQuiet() { try { test( @@ -396,6 +404,7 @@ public void testSetNewModeQuiet() { } } + @Test public void testSetError() { try { test( @@ -473,6 +482,7 @@ public void testSetError() { } } + @Test public void testSetHelp() { try { test( diff --git a/test/langtools/jdk/jshell/ToolLocalSimpleTest.java b/test/langtools/jdk/jshell/ToolLocalSimpleTest.java index 6221f2951036..bb0273a2123d 100644 --- a/test/langtools/jdk/jshell/ToolLocalSimpleTest.java +++ b/test/langtools/jdk/jshell/ToolLocalSimpleTest.java @@ -30,12 +30,12 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream ToolSimpleTest - * @run testng/othervm ToolLocalSimpleTest + * @run junit/othervm ToolLocalSimpleTest */ import java.util.Locale; -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; public class ToolLocalSimpleTest extends ToolSimpleTest { @@ -51,12 +51,12 @@ public void test(Locale locale, boolean isDefaultStartUp, String[] args, String @Test public void verifyLocal() { System.setProperty("LOCAL_CHECK", "Here"); - assertEquals(System.getProperty("LOCAL_CHECK"), "Here"); + assertEquals("Here", System.getProperty("LOCAL_CHECK")); test(new String[]{"--no-startup"}, a -> assertCommand(a, "System.getProperty(\"LOCAL_CHECK\")", "$1 ==> \"Here\""), a -> assertCommand(a, "System.setProperty(\"LOCAL_CHECK\", \"After\")", "$2 ==> \"Here\"") ); - assertEquals(System.getProperty("LOCAL_CHECK"), "After"); + assertEquals("After", System.getProperty("LOCAL_CHECK")); } @Override diff --git a/test/langtools/jdk/jshell/ToolLocaleMessageTest.java b/test/langtools/jdk/jshell/ToolLocaleMessageTest.java index 6111320f1af4..c3e4a4211437 100644 --- a/test/langtools/jdk/jshell/ToolLocaleMessageTest.java +++ b/test/langtools/jdk/jshell/ToolLocaleMessageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -31,16 +31,15 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream toolbox.ToolBox Compiler - * @run testng ToolLocaleMessageTest + * @run junit ToolLocaleMessageTest * @key intermittent */ import java.util.Locale; -import org.testng.annotations.Test; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class ToolLocaleMessageTest extends ReplToolTesting { void testLocale(ReplTest... tests) { @@ -67,12 +66,14 @@ void assertCommandFail(boolean after, String cmd, String... contains) { }); } + @Test public void testTerminate() { testLocale( (a) -> assertCommandOK(a, "System.exit(1)", "/reload") ); } + @Test public void testSample() { try { testLocale( @@ -98,6 +99,7 @@ public void testSample() { } } + @Test public void testCommand() { try { testLocale( @@ -132,6 +134,7 @@ public void testCommand() { } } + @Test public void testHelp() { testLocale( (a) -> assertCommandOK(a, "/help", "/list", "/save", "/set", "[-restore]"), @@ -153,6 +156,7 @@ public void testHelp() { ); } + @Test public void testFeedbackError() { try { testLocale( diff --git a/test/langtools/jdk/jshell/ToolMultilineSnippetHistoryTest.java b/test/langtools/jdk/jshell/ToolMultilineSnippetHistoryTest.java index 8a7b46fc1c77..e3cbba3f20d4 100644 --- a/test/langtools/jdk/jshell/ToolMultilineSnippetHistoryTest.java +++ b/test/langtools/jdk/jshell/ToolMultilineSnippetHistoryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8182489 * @summary test history with multiline snippets @@ -31,18 +31,18 @@ * jdk.jshell/jdk.jshell:open * @build UITesting * @build ToolMultilineSnippetHistoryTest - * @run testng ToolMultilineSnippetHistoryTest + * @run junit ToolMultilineSnippetHistoryTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ToolMultilineSnippetHistoryTest extends UITesting { public ToolMultilineSnippetHistoryTest() { super(true); } + @Test public void testUpArrow() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("int x=\n44\n"); diff --git a/test/langtools/jdk/jshell/ToolProviderTest.java b/test/langtools/jdk/jshell/ToolProviderTest.java index be8ba23f7c48..b8e9f8e0f4e0 100644 --- a/test/langtools/jdk/jshell/ToolProviderTest.java +++ b/test/langtools/jdk/jshell/ToolProviderTest.java @@ -23,8 +23,8 @@ import java.util.ServiceLoader; import javax.tools.Tool; -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; /* * @test @@ -34,11 +34,11 @@ * jdk.compiler/com.sun.tools.javac.main * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool + * jdk.jshell/jdk.internal.jshell.tool.resources:+open * @library /tools/lib * @build Compiler toolbox.ToolBox - * @run testng ToolProviderTest + * @run junit ToolProviderTest */ -@Test public class ToolProviderTest extends StartOptionTest { // Through the provider, the console and console go to command out (we assume, @@ -71,6 +71,7 @@ protected int runShell(String... args) { // Test --show-version @Override + @Test public void testShowVersion() { startCo(s -> { assertTrue(s.startsWith("jshell "), "unexpected version: " + s); diff --git a/test/langtools/jdk/jshell/ToolReloadTest.java b/test/langtools/jdk/jshell/ToolReloadTest.java index 4709584cd126..c4193f602bef 100644 --- a/test/langtools/jdk/jshell/ToolReloadTest.java +++ b/test/langtools/jdk/jshell/ToolReloadTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2017, 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 @@ -32,20 +32,20 @@ * jdk.jshell/jdk.internal.jshell.tool * @library /tools/lib * @build KullaTesting TestingInputStream toolbox.ToolBox Compiler - * @run testng ToolReloadTest + * @run junit ToolReloadTest */ import java.nio.file.Path; import java.nio.file.Paths; import java.util.function.Function; -import org.testng.annotations.Test; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; -@Test public class ToolReloadTest extends ReplToolTesting { + @Test public void testReloadSnippets() { test( (a) -> assertVariable(a, "int", "x", "5", "5"), @@ -63,6 +63,7 @@ public void testReloadSnippets() { ); } + @Test public void testReloadClasspath() { Function prog = (s) -> String.format( "package pkg; public class A { public String toString() { return \"%s\"; } }\n", s); @@ -89,6 +90,7 @@ public void testReloadClasspath() { ); } + @Test public void testReloadDrop() { test(false, new String[]{"--no-startup"}, a -> assertVariable(a, "int", "a"), @@ -112,6 +114,7 @@ public void testReloadDrop() { ); } + @Test public void testReloadQuiet() { test(false, new String[]{"--no-startup"}, a -> assertVariable(a, "int", "a"), @@ -129,6 +132,7 @@ public void testReloadQuiet() { ); } + @Test public void testReloadRepeat() { test(false, new String[]{"--no-startup"}, (a) -> assertVariable(a, "int", "c", "7", "7"), @@ -149,6 +153,7 @@ public void testReloadRepeat() { ); } + @Test public void testReloadIgnore() { test(false, new String[]{"--no-startup"}, (a) -> assertCommand(a, "(-)", null), @@ -162,6 +167,7 @@ public void testReloadIgnore() { ); } + @Test public void testReloadResetRestore() { test( (a) -> assertVariable(a, "int", "x", "5", "5"), @@ -180,6 +186,7 @@ public void testReloadResetRestore() { ); } + @Test public void testReloadCrashRestore() { test( (a) -> assertVariable(a, "int", "x", "5", "5"), @@ -200,6 +207,7 @@ public void testReloadCrashRestore() { ); } + @Test public void testEnvBadModule() { test(new String[] {"--execution", Presets.TEST_STANDARD_EXECUTION}, (a) -> assertVariable(a, "int", "x", "5", "5"), @@ -221,6 +229,7 @@ public void testEnvBadModule() { ); } + @Test public void testReloadExitRestore() { test(false, new String[]{"--no-startup"}, (a) -> assertVariable(a, "int", "x", "5", "5"), diff --git a/test/langtools/jdk/jshell/ToolRetainTest.java b/test/langtools/jdk/jshell/ToolRetainTest.java index 452a3d8dac2c..adf3dd0343e2 100644 --- a/test/langtools/jdk/jshell/ToolRetainTest.java +++ b/test/langtools/jdk/jshell/ToolRetainTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,15 +27,15 @@ * @summary Tests of what information is retained across jshell tool runs * @modules jdk.jshell/jdk.internal.jshell.tool * @build ToolRetainTest ReplToolTesting - * @run testng ToolRetainTest + * @run junit ToolRetainTest */ import java.util.Locale; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ToolRetainTest extends ReplToolTesting { + @Test public void testRetainMode() { test( (a) -> assertCommand(a, "/set mode trm -quiet", "| Created new feedback mode: trm"), @@ -53,6 +53,7 @@ public void testRetainMode() { ); } + @Test public void testRetain2Mode() { test( (a) -> assertCommand(a, "/set mode trm1 -quiet", "| Created new feedback mode: trm1"), @@ -81,6 +82,7 @@ public void testRetain2Mode() { ); } + @Test public void testRetainFeedback() { test( (a) -> assertCommand(a, "/set feedback -retain verbose", "| Feedback mode: verbose"), @@ -95,6 +97,7 @@ public void testRetainFeedback() { ); } + @Test public void testRetainFeedbackBlank() { String feedbackOut = "| /set feedback -retain verbose\n" + @@ -116,6 +119,7 @@ public void testRetainFeedbackBlank() { ); } + @Test public void testRetainEditor() { test( (a) -> assertCommand(a, "/set editor -retain nonexistent", @@ -130,6 +134,7 @@ public void testRetainEditor() { ); } + @Test public void testRetainEditorBlank() { test( (a) -> assertCommand(a, "/set editor nonexistent", "| Editor set to: nonexistent"), @@ -142,6 +147,7 @@ public void testRetainEditorBlank() { ); } + @Test public void testRetainModeNeg() { test( (a) -> assertCommandOutputStartsWith(a, "/set mode -retain verbose", @@ -151,6 +157,7 @@ public void testRetainModeNeg() { ); } + @Test public void testRetainFeedbackNeg() { test( (a) -> assertCommandOutputStartsWith(a, "/set feedback -retain babble1", @@ -167,6 +174,7 @@ public void testRetainFeedbackNeg() { ); } + @Test public void testNoRetainMode() { test( (a) -> assertCommand(a, "/set mode trm -quiet", "| Created new feedback mode: trm"), @@ -182,6 +190,7 @@ public void testNoRetainMode() { ); } + @Test public void testNoRetainFeedback() { test( (a) -> assertCommand(a, "/set feedback verbose", "| Feedback mode: verbose"), diff --git a/test/langtools/jdk/jshell/ToolShiftTabTest.java b/test/langtools/jdk/jshell/ToolShiftTabTest.java index 4c36d79c16a4..84f1a65c67be 100644 --- a/test/langtools/jdk/jshell/ToolShiftTabTest.java +++ b/test/langtools/jdk/jshell/ToolShiftTabTest.java @@ -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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8166334 8188894 * @summary test shift-tab shortcuts "fixes" @@ -31,18 +31,18 @@ * jdk.jshell/jdk.jshell:open * @build UITesting * @build ToolShiftTabTest - * @run testng/timeout=300 ToolShiftTabTest + * @run junit/timeout=300 ToolShiftTabTest */ import java.util.regex.Pattern; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ToolShiftTabTest extends UITesting { // Shift-tab as escape sequence private String FIX = "\033\133\132"; + @Test public void testFixVariable() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("3+4"); @@ -54,6 +54,7 @@ public void testFixVariable() throws Exception { }); } + @Test public void testFixMethod() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("5.5 >= 3.1415926535"); @@ -68,6 +69,7 @@ public void testFixMethod() throws Exception { }); } + @Test public void testFixMethodVoid() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("System.out.println(\"Testing\")"); @@ -81,6 +83,7 @@ public void testFixMethodVoid() throws Exception { }); } + @Test public void testFixMethodNoLeaks() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("4"); @@ -106,6 +109,7 @@ public void testFixMethodNoLeaks() throws Exception { }); } + @Test public void testFixImport() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("Frame"); @@ -126,6 +130,7 @@ public void testFixImport() throws Exception { }); } + @Test public void testFixBad() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("123"); diff --git a/test/langtools/jdk/jshell/ToolSimpleTest.java b/test/langtools/jdk/jshell/ToolSimpleTest.java index 222acb5291c7..668da9605788 100644 --- a/test/langtools/jdk/jshell/ToolSimpleTest.java +++ b/test/langtools/jdk/jshell/ToolSimpleTest.java @@ -34,7 +34,7 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream - * @run testng ToolSimpleTest + * @run junit ToolSimpleTest */ import java.util.ArrayList; @@ -46,10 +46,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; public class ToolSimpleTest extends ReplToolTesting { @@ -542,7 +541,7 @@ private void checkLineToList(String in, List match) { String[] res = trimmed.isEmpty() ? new String[0] : trimmed.split("\n"); - assertEquals(res.length, match.size(), "Got: " + Arrays.asList(res)); + assertEquals(match.size(), res.length, "Got: " + Arrays.asList(res)); for (int i = 0; i < match.size(); ++i) { assertTrue(res[i].contains(match.get(i))); } @@ -618,7 +617,7 @@ public void testMethodsArgs() { a -> assertCommandCheckOutput(a, "/methods print println printf", s -> checkLineToList(s, printingMethodList)), a -> assertCommandCheckOutput(a, "/methods println", - s -> assertEquals(s.trim().split("\n").length, 10)), + s -> assertEquals(10, s.trim().split("\n").length)), a -> assertCommandCheckOutput(a, "/methods", s -> checkLineToList(s, printingMethodList)), a -> assertCommandOutputStartsWith(a, "/methods " + arg, diff --git a/test/langtools/jdk/jshell/ToolTabCommandTest.java b/test/langtools/jdk/jshell/ToolTabCommandTest.java index 9a429bb72530..3dcc81e77bea 100644 --- a/test/langtools/jdk/jshell/ToolTabCommandTest.java +++ b/test/langtools/jdk/jshell/ToolTabCommandTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8177076 8185840 8178109 8192863 * @modules @@ -34,18 +34,18 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @build ToolTabCommandTest - * @run testng ToolTabCommandTest + * @run junit ToolTabCommandTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ToolTabCommandTest extends UITesting { public ToolTabCommandTest() { super(true); } + @Test public void testCommand() throws Exception { // set terminal height so that help output won't hit page breaks System.setProperty("test.terminal.height", "1000000"); @@ -133,6 +133,7 @@ public void testCommand() throws Exception { }); } + @Test public void testRerunCommands() throws Exception { // set terminal height so that help output won't hit page breaks System.setProperty("test.terminal.height", "1000000"); @@ -170,6 +171,7 @@ public void testRerunCommands() throws Exception { }); } + @Test public void testHelp() throws Exception { // set terminal height so that help output won't hit page breaks System.setProperty("test.terminal.height", "1000000"); diff --git a/test/langtools/jdk/jshell/ToolTabSnippetTest.java b/test/langtools/jdk/jshell/ToolTabSnippetTest.java index 86338938c2cd..39189da86865 100644 --- a/test/langtools/jdk/jshell/ToolTabSnippetTest.java +++ b/test/langtools/jdk/jshell/ToolTabSnippetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8177076 8185426 8189595 8188072 8221759 8255273 * @modules @@ -34,7 +34,7 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @build ToolTabSnippetTest - * @run testng/timeout=300 ToolTabSnippetTest + * @run junit/timeout=300 ToolTabSnippetTest */ import java.io.IOException; @@ -48,15 +48,15 @@ import java.util.jar.JarOutputStream; import jdk.internal.jshell.tool.ConsoleIOContextTestSupport; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class ToolTabSnippetTest extends UITesting { public ToolTabSnippetTest() { super(true); } + @Test public void testExpression() throws Exception { Path classes = prepareZip(); doRunTest((inputSink, out) -> { @@ -208,6 +208,7 @@ public void testExpression() throws Exception { }); } + @Test public void testCleaningCompletionTODO() throws Exception { doRunTest((inputSink, out) -> { CountDownLatch testCompleteComputationStarted = new CountDownLatch(1); @@ -241,6 +242,7 @@ protected void willComputeCompletionCallback() { }); } + @Test public void testNoRepeat() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("String xyzAA;\n"); @@ -266,6 +268,7 @@ public void testNoRepeat() throws Exception { }); } + @Test public void testCrash8221759() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("java.io.File.path" + TAB); @@ -331,6 +334,7 @@ private Path prepareZip() { //where: private final Compiler compiler = new Compiler(); + @Test public void testDocumentationAfterInsert() throws Exception { doRunTest((inputSink, out) -> { inputSink.write("import java.time.*\n"); diff --git a/test/langtools/jdk/jshell/ToolingTest.java b/test/langtools/jdk/jshell/ToolingTest.java index b36fdc03c190..1f514caf2e39 100644 --- a/test/langtools/jdk/jshell/ToolingTest.java +++ b/test/langtools/jdk/jshell/ToolingTest.java @@ -30,11 +30,10 @@ * jdk.jdeps/com.sun.tools.javap * jdk.jshell/jdk.internal.jshell.tool * @build KullaTesting TestingInputStream - * @run testng ToolingTest + * @run junit ToolingTest */ -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; public class ToolingTest extends ReplToolTesting { @Test diff --git a/test/langtools/jdk/jshell/TypeNameTest.java b/test/langtools/jdk/jshell/TypeNameTest.java index dc2b2152ca81..cbcde20a5413 100644 --- a/test/langtools/jdk/jshell/TypeNameTest.java +++ b/test/langtools/jdk/jshell/TypeNameTest.java @@ -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 @@ -26,14 +26,12 @@ * @bug 8144903 8171981 8191802 8191842 * @summary Tests for determining the type from the expression * @build KullaTesting TestingInputStream - * @run testng TypeNameTest + * @run junit TypeNameTest */ -import org.testng.annotations.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; -import static org.testng.Assert.assertEquals; - -@Test public class TypeNameTest extends KullaTesting { @@ -42,10 +40,11 @@ private void assertType(String expr, String type) { } private void assertType(String expr, String type, String inferType) { - assertEquals(varKey(assertEval(expr)).typeName(), type); + assertEquals(type, varKey(assertEval(expr)).typeName()); assertInferredType(expr, inferType); } + @Test public void testTypeInference() { assertEval("import java.util.List;"); assertEval("import java.util.ArrayList;"); @@ -75,6 +74,7 @@ public void testTypeInference() { assertType("(P) null", "P"); } + @Test public void testConditionals() { assertEval("import java.util.List;"); assertEval("import java.util.ArrayList;"); @@ -95,6 +95,7 @@ public void testConditionals() { assertType("b? new B() : new C()", "X"); } + @Test public void testJEP286NonDenotable() { assertEval("import java.util.List;"); assertEval("import java.util.Arrays;"); @@ -144,6 +145,7 @@ public void testJEP286NonDenotable() { assertType("unbStringIter().iterator().next().get(0)", "Object"); } + @Test public void testJEP286NonDenotable2() { assertEval("import java.util.List;"); assertEval("import java.util.Arrays;"); @@ -197,6 +199,7 @@ public void testJEP286NonDenotable2() { "Number"); } + @Test public void testVariableTypeName() { assertType("\"x\"", "String"); @@ -213,30 +216,36 @@ public void testVariableTypeName() { assertType("java.util.Locale.Category.FORMAT", "Category"); } + @Test public void testReplNestedClassName() { assertEval("class D { static class E {} }"); assertType("new D.E();", "D.E"); } + @Test public void testAnonymousClassName() { assertEval("class C {}"); assertType("new C();", "C"); assertType("new C() { int x; };", "", "C"); } + @Test public void testCapturedTypeName() { assertType("\"\".getClass();", "Class"); assertType("\"\".getClass().getEnumConstants();", "String[]"); } + @Test public void testJavaLang() { assertType("\"\";", "String"); } + @Test public void testNotOverEagerPackageEating() { assertType("\"\".getClass().getDeclaredMethod(\"hashCode\");", "java.lang.reflect.Method"); } + @Test public void testBounds() { assertEval("java.util.List list1 = java.util.Arrays.asList(\"\");"); assertType("list1.iterator().next()", "String"); diff --git a/test/langtools/jdk/jshell/UITesting.java b/test/langtools/jdk/jshell/UITesting.java index 473ba36c5aed..b9bfd994fc85 100644 --- a/test/langtools/jdk/jshell/UITesting.java +++ b/test/langtools/jdk/jshell/UITesting.java @@ -61,7 +61,7 @@ public UITesting(boolean laxLineEndings) { this.laxLineEndings = laxLineEndings; } - protected void doRunTest(Test test) throws Exception { + protected void doRunTest(UITest test) throws Exception { // turn on logging of launch failures Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL); @@ -127,7 +127,7 @@ public void write(String str) throws IOException { } } - protected interface Test { + protected interface UITest { public void test(Writer inputSink, StringBuilder out) throws Exception; } diff --git a/test/langtools/jdk/jshell/UndefinedClassTest.java b/test/langtools/jdk/jshell/UndefinedClassTest.java index 5c509252bd6f..3891aa7b4cd3 100644 --- a/test/langtools/jdk/jshell/UndefinedClassTest.java +++ b/test/langtools/jdk/jshell/UndefinedClassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -21,7 +21,7 @@ * questions. */ -/** +/* * @test * @bug 8292755 * @summary InternalError seen while throwing undefined exception @@ -35,18 +35,18 @@ * @build toolbox.ToolBox toolbox.JarTask toolbox.JavacTask * @build Compiler UITesting * @build UndefinedClassTest - * @run testng UndefinedClassTest + * @run junit UndefinedClassTest */ -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class UndefinedClassTest extends UITesting { public UndefinedClassTest() { super(true); } + @Test public void testUndefinedClassWithStaticAccess() throws Exception{ String code = "@FunctionalInterface\n" + "interface RunnableWithThrowable {\n" + @@ -62,6 +62,7 @@ public void testUndefinedClassWithStaticAccess() throws Exception{ }); } + @Test public void testUndefinedClassWithDefaultAccess() throws Exception{ String code = "@FunctionalInterface\n" + "interface RunnableWithThrowable {\n" + diff --git a/test/langtools/jdk/jshell/UnicodeTest.java b/test/langtools/jdk/jshell/UnicodeTest.java index 6812dcf1a50e..13dd30f0975d 100644 --- a/test/langtools/jdk/jshell/UnicodeTest.java +++ b/test/langtools/jdk/jshell/UnicodeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 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 @@ -26,27 +26,28 @@ * @bug 8248157 * @summary test Unicode characters in Snippets * @build KullaTesting TestingInputStream - * @run testng UnicodeTest + * @run junit UnicodeTest */ import jdk.jshell.Snippet; import jdk.jshell.DeclarationSnippet; -import org.testng.annotations.Test; import jdk.jshell.Snippet.Status; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static jdk.jshell.Snippet.Status.VALID; import static jdk.jshell.Snippet.SubKind.*; +import org.junit.jupiter.api.Test; -@Test public class UnicodeTest extends KullaTesting { + @Test public void testVarDeclarationKey() { assertVarKeyMatch("int \\u00aa;", true, "\u00aa", VAR_DECLARATION_SUBKIND, "int", added(VALID)); assertEval("\\u00aa", "0"); } + @Test public void testVarDeclarationWithInitializerKey() { assertVarKeyMatch("double \\u00ba\\u0044\\u0577 = 9.4;", true, "\u00ba\u0044\u0577", VAR_DECLARATION_WITH_INITIALIZER_SUBKIND, "double", added(VALID)); diff --git a/test/langtools/jdk/jshell/UnnamedTest.java b/test/langtools/jdk/jshell/UnnamedTest.java index 87ce6f68cadd..65d2b83c8562 100644 --- a/test/langtools/jdk/jshell/UnnamedTest.java +++ b/test/langtools/jdk/jshell/UnnamedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -23,31 +23,109 @@ /* * @test - * @bug 9999999 + * @bug 8315851 8315588 * @summary Tests for unnamed variables * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jshell * @build Compiler KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng UnnamedTest + * @run junit UnnamedTest */ import java.util.function.Consumer; + +import jdk.jshell.SourceCodeAnalysis; import jdk.jshell.VarSnippet; -import org.testng.Assert; -import org.testng.annotations.Test; import jdk.jshell.JShell; +import static jdk.jshell.SourceCodeAnalysis.Completeness.COMPLETE; +import static jdk.jshell.SourceCodeAnalysis.Completeness.DEFINITELY_INCOMPLETE; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class UnnamedTest extends KullaTesting { @Test public void unnamed() { VarSnippet sn1 = varKey(assertEval("int _ = 0;")); VarSnippet sn2 = varKey(assertEval("String _ = \"x\";")); - Assert.assertEquals(getState().varValue(sn1), "0"); - Assert.assertEquals(getState().varValue(sn2), "\"x\""); + Assertions.assertEquals("0", getState().varValue(sn1)); + Assertions.assertEquals("\"x\"", getState().varValue(sn2)); + } + + static final String[] definitely_incomplete = new String[]{ + "int _ = ", + "int m(String v, int r) {\n" + + " try {\n" + + " return Integer.parseInt(v, r);\n" + + " } catch (NumberFormatException _) {", + "try (final Lock _ = ", + "try (Lock _ = null) {\n" + + " try (Lock _ = null) {", + "for (var _ : strs", + "TwoParams p1 = (_, _) ->", + "for (int _ = 0, _ = 1, x = 1;", + "if (r instanceof R(_" + }; + + static final String[] complete = new String[]{ + "int _ = 42;", + "int m(String v, int r) {\n" + + " try {\n" + + " return Integer.parseInt(v, r);\n" + + " } catch (NumberFormatException _) { } }", + "try (final Lock _ = TEST) {}", + "try (Lock _ = null) {\n" + + " try (Lock _ = null) { } }", + "for (var _ : strs) { }", + "TwoParams p1 = (_, _) -> {};", + "for (int _ = 0, _ = 1, x = 1; x <= 1 ; x++) {}", + "if (r instanceof R(_)) { }" + }; + + private void assertStatus(String input, SourceCodeAnalysis.Completeness status, String source) { + String augSrc; + switch (status) { + case COMPLETE_WITH_SEMI: + augSrc = source + ";"; + break; + + case DEFINITELY_INCOMPLETE: + augSrc = null; + break; + + case CONSIDERED_INCOMPLETE: + augSrc = source + ";"; + break; + + case EMPTY: + case COMPLETE: + case UNKNOWN: + augSrc = source; + break; + + default: + throw new AssertionError(); + } + assertAnalyze(input, status, augSrc); + } + + private void assertStatus(String[] ins, SourceCodeAnalysis.Completeness status) { + for (String input : ins) { + assertStatus(input, status, input); + } + } + + @Test + public void test_definitely_incomplete() { + assertStatus(definitely_incomplete, DEFINITELY_INCOMPLETE); + } + + @Test + public void test_definitely_complete() { + assertStatus(complete, COMPLETE); } @Override diff --git a/test/langtools/jdk/jshell/UserExecutionControlTest.java b/test/langtools/jdk/jshell/UserExecutionControlTest.java index 90c99db4a8fb..41719f9ff2ab 100644 --- a/test/langtools/jdk/jshell/UserExecutionControlTest.java +++ b/test/langtools/jdk/jshell/UserExecutionControlTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,29 +26,29 @@ * @bug 8156101 8159935 8159122 8168615 * @summary Tests for ExecutionControl SPI * @build KullaTesting ExecutionControlTestBase - * @run testng UserExecutionControlTest + * @run junit UserExecutionControlTest */ -import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import org.testng.annotations.BeforeMethod; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class UserExecutionControlTest extends ExecutionControlTestBase { - @BeforeMethod + @BeforeEach @Override public void setUp() { setUp(builder -> builder.executionEngine("local")); } + @Test public void verifyLocal() throws ClassNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { System.setProperty("LOCAL_CHECK", "TBD"); - assertEquals(System.getProperty("LOCAL_CHECK"), "TBD"); + assertEquals("TBD", System.getProperty("LOCAL_CHECK")); assertEval("System.getProperty(\"LOCAL_CHECK\")", "\"TBD\""); assertEval("System.setProperty(\"LOCAL_CHECK\", \"local\")"); - assertEquals(System.getProperty("LOCAL_CHECK"), "local"); + assertEquals("local", System.getProperty("LOCAL_CHECK")); } } diff --git a/test/langtools/jdk/jshell/UserInputTest.java b/test/langtools/jdk/jshell/UserInputTest.java index 392278abef19..c0246acdf63e 100644 --- a/test/langtools/jdk/jshell/UserInputTest.java +++ b/test/langtools/jdk/jshell/UserInputTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,18 +26,18 @@ * @bug 8131023 8167461 * @summary Verify that the user's code can read System.in * @build KullaTesting TestingInputStream - * @run testng UserInputTest + * @run junit UserInputTest * @key intermittent */ import java.io.IOException; import java.io.InputStream; -import org.testng.annotations.Test; +import org.junit.jupiter.api.Test; -@Test public class UserInputTest extends KullaTesting { + @Test public void testReadInput() { setInput("AB\n"); assertEval("System.in.read()", "65"); @@ -45,6 +45,7 @@ public void testReadInput() { assertEval("System.in.read()", "67"); } + @Test public void testScanner() { assertEval("import java.util.Scanner;"); assertEval("Scanner s = new Scanner(System.in);"); @@ -52,6 +53,7 @@ public void testScanner() { assertEval("s.nextInt();", "12"); } + @Test public void testClose() { setInput(new InputStream() { private final byte[] data = new byte[] {0, 1, 2}; @@ -73,6 +75,7 @@ public void testClose() { assertEval("System.in.read();", "-1"); } + @Test public void testException() { setInput(new InputStream() { private final int[] data = new int[] {0, 1, -2, 2}; @@ -99,6 +102,7 @@ public void testException() { assertEval("System.in.read();", "-1"); } + @Test public void testNoConsole() { assertEval("System.console()", "null"); } diff --git a/test/langtools/jdk/jshell/UserJdiUserRemoteTest.java b/test/langtools/jdk/jshell/UserJdiUserRemoteTest.java index 02c725cffa41..094c705bce64 100644 --- a/test/langtools/jdk/jshell/UserJdiUserRemoteTest.java +++ b/test/langtools/jdk/jshell/UserJdiUserRemoteTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -26,46 +26,48 @@ * @bug 8160128 8159935 8168615 * @summary Tests for Aux channel, custom remote agents, custom JDI implementations. * @build KullaTesting ExecutionControlTestBase MyExecutionControl MyRemoteExecutionControl MyExecutionControlProvider - * @run testng UserJdiUserRemoteTest + * @run junit UserJdiUserRemoteTest * @key intermittent */ import java.io.ByteArrayOutputStream; -import org.testng.annotations.Test; -import org.testng.annotations.BeforeMethod; import jdk.jshell.Snippet; import static jdk.jshell.Snippet.Status.OVERWRITTEN; import static jdk.jshell.Snippet.Status.VALID; import jdk.jshell.VarSnippet; import jdk.jshell.spi.ExecutionControl; import jdk.jshell.spi.ExecutionControl.ExecutionControlException; -import static org.testng.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -@Test public class UserJdiUserRemoteTest extends ExecutionControlTestBase { ExecutionControl currentEC; ByteArrayOutputStream auxStream; - @BeforeMethod + @BeforeEach @Override public void setUp() { auxStream = new ByteArrayOutputStream(); setUp(builder -> builder.executionEngine(new MyExecutionControlProvider(this), null)); } + @Test public void testVarValue() { VarSnippet dv = varKey(assertEval("double aDouble = 1.5;")); String vd = getState().varValue(dv); - assertEquals(vd, "1.5"); - assertEquals(auxStream.toString(), "aDouble"); + assertEquals("1.5", vd); + assertEquals("aDouble", auxStream.toString()); } + @Test public void testExtension() throws ExecutionControlException { assertEval("42;"); Object res = currentEC.extensionCommand("FROG", "test"); - assertEquals(res, "ribbit"); + assertEquals("ribbit", res); } + @Test public void testRedefine() { Snippet vx = varKey(assertEval("int x;")); Snippet mu = methodKey(assertEval("int mu() { return x * 4; }")); diff --git a/test/langtools/jdk/jshell/VariablesTest.java b/test/langtools/jdk/jshell/VariablesTest.java index 51ccbd17d604..46ddc699d13e 100644 --- a/test/langtools/jdk/jshell/VariablesTest.java +++ b/test/langtools/jdk/jshell/VariablesTest.java @@ -23,14 +23,14 @@ /* * @test - * @bug 8144903 8177466 8191842 8211694 8213725 8239536 8257236 8252409 8294431 + * @bug 8144903 8177466 8191842 8211694 8213725 8239536 8257236 8252409 8294431 8322532 * @summary Tests for EvaluationState.variables * @library /tools/lib * @modules jdk.compiler/com.sun.tools.javac.api * jdk.compiler/com.sun.tools.javac.main * jdk.jshell * @build Compiler KullaTesting TestingInputStream ExpectedDiagnostic - * @run testng VariablesTest + * @run junit VariablesTest */ import java.nio.file.Path; @@ -44,18 +44,19 @@ import jdk.jshell.VarSnippet; import jdk.jshell.Snippet.SubKind; import jdk.jshell.SnippetEvent; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; import static java.util.stream.Collectors.toList; import static jdk.jshell.Snippet.Status.*; import static jdk.jshell.Snippet.SubKind.VAR_DECLARATION_SUBKIND; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; -@Test public class VariablesTest extends KullaTesting { + @Test public void noVariables() { assertNumberOfActiveVariables(0); } @@ -69,6 +70,7 @@ private void badVarValue(VarSnippet key) { } } + @Test public void testVarValue1() { VarSnippet v1 = varKey(assertEval("und1 a;", added(RECOVERABLE_NOT_DEFINED))); badVarValue(v1); @@ -89,6 +91,7 @@ public void testVarValue1() { badVarValue(v2); } + @Test public void testVarValue2() { VarSnippet v1 = (VarSnippet) assertDeclareFail("int a = 0.0;", "compiler.err.prob.found.req"); badVarValue(v1); @@ -97,6 +100,7 @@ public void testVarValue2() { badVarValue(v2); } + @Test public void testSignature1() { VarSnippet v1 = varKey(assertEval("und1 a;", added(RECOVERABLE_NOT_DEFINED))); assertVariableDeclSnippet(v1, "a", "und1", RECOVERABLE_NOT_DEFINED, VAR_DECLARATION_SUBKIND, 1, 0); @@ -116,6 +120,7 @@ public void testSignature1() { assertVariableDeclSnippet(v2, "a", "und2", RECOVERABLE_NOT_DEFINED, VAR_DECLARATION_SUBKIND, 1, 0); } + @Test public void testSignature2() { VarSnippet v1 = (VarSnippet) assertDeclareFail("int a = 0.0;", "compiler.err.prob.found.req"); assertVariableDeclSnippet(v1, "a", "int", REJECTED, SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND, 0, 1); @@ -126,6 +131,7 @@ public void testSignature2() { assertVariableDeclSnippet(v2, "a", "int", DROPPED, SubKind.VAR_DECLARATION_WITH_INITIALIZER_SUBKIND, 0, 0); } + @Test public void variables() { VarSnippet snx = varKey(assertEval("int x = 10;")); VarSnippet sny = varKey(assertEval("String y = \"hi\";")); @@ -137,22 +143,25 @@ public void variables() { assertActiveKeys(); } + @Test public void variablesArray() { VarSnippet sn = varKey(assertEval("int[] a = new int[12];")); - assertEquals(sn.typeName(), "int[]"); + assertEquals("int[]", sn.typeName()); assertEval("int len = a.length;", "12"); assertVariables(variable("int[]", "a"), variable("int", "len")); assertActiveKeys(); } + @Test public void variablesArrayOld() { VarSnippet sn = varKey(assertEval("int a[] = new int[12];")); - assertEquals(sn.typeName(), "int[]"); + assertEquals("int[]", sn.typeName()); assertEval("int len = a.length;", "12"); assertVariables(variable("int[]", "a"), variable("int", "len")); assertActiveKeys(); } + @Test public void variablesRedefinition() { Snippet x = varKey(assertEval("int x = 10;")); Snippet y = varKey(assertEval("String y = \"\";", added(VALID))); @@ -170,6 +179,7 @@ public void variablesRedefinition() { assertActiveKeys(); } + @Test public void variablesTemporary() { assertEval("int $1 = 10;", added(VALID)); assertEval("2 * $1;", added(VALID)); @@ -180,6 +190,7 @@ public void variablesTemporary() { assertActiveKeys(); } + @Test public void variablesTemporaryNull() { assertEval("null;", added(VALID)); assertVariables(variable("Object", "$1")); @@ -194,6 +205,7 @@ public void variablesTemporaryNull() { assertActiveKeys(); } + @Test public void variablesTemporaryArrayOfCapturedType() { assertEval("class Test { T[][] get() { return null; } }", added(VALID)); assertEval("Test test() { return new Test<>(); }", added(VALID)); @@ -204,6 +216,7 @@ public void variablesTemporaryArrayOfCapturedType() { assertActiveKeys(); } + @Test public void variablesClassReplace() { assertEval("import java.util.*;", added(VALID)); Snippet var = varKey(assertEval("List list = new ArrayList<>();", "[]", @@ -223,12 +236,14 @@ public void variablesClassReplace() { assertActiveKeys(); } + @Test public void variablesErrors() { assertDeclareFail("String;", new ExpectedDiagnostic("compiler.err.cant.resolve.location", 0, 6, 0, -1, -1, Diagnostic.Kind.ERROR)); assertNumberOfActiveVariables(0); assertActiveKeys(); } + @Test public void variablesUnresolvedActiveFailed() { VarSnippet key = varKey(assertEval("und x;", added(RECOVERABLE_NOT_DEFINED))); assertVariableDeclSnippet(key, "x", "und", RECOVERABLE_NOT_DEFINED, VAR_DECLARATION_SUBKIND, 1, 0); @@ -237,12 +252,14 @@ public void variablesUnresolvedActiveFailed() { assertActiveKeys(); } + @Test public void variablesUnresolvedError() { assertDeclareFail("und y = null;", new ExpectedDiagnostic("compiler.err.cant.resolve.location", 0, 3, 0, -1, -1, Diagnostic.Kind.ERROR)); assertNumberOfActiveVariables(0); assertActiveKeys(); } + @Test public void variablesMultiByteCharacterType() { assertEval("class \u3042 {}"); assertEval("\u3042 \u3042 = null;", added(VALID)); @@ -261,7 +278,8 @@ public void variablesMultiByteCharacterType() { assertActiveKeys(); } - @Test(enabled = false) // TODO 8081689 + @Test // TODO 8081689 + @Disabled public void methodVariablesAreNotVisible() { Snippet foo = varKey(assertEval("int foo() {" + "int x = 10;" + @@ -283,7 +301,8 @@ public void methodVariablesAreNotVisible() { assertActiveKeys(); } - @Test(enabled = false) // TODO 8081689 + @Test // TODO 8081689 + @Disabled public void classFieldsAreNotVisible() { Snippet key = classKey(assertEval("class clazz {" + "int x = 10;" + @@ -303,6 +322,7 @@ public void classFieldsAreNotVisible() { assertActiveKeys(); } + @Test public void multiVariables() { List abc = assertEval("int a, b, c = 10;", DiagCheck.DIAG_OK, DiagCheck.DIAG_OK, @@ -324,12 +344,14 @@ public void multiVariables() { assertActiveKeys(); } + @Test public void syntheticVariables() { assertEval("assert false;"); assertNumberOfActiveVariables(0); assertActiveKeys(); } + @Test public void undefinedReplaceVariable() { Snippet key = varKey(assertEval("int d = 234;", "234")); assertVariables(variable("int", "d")); @@ -339,13 +361,14 @@ public void undefinedReplaceVariable() { ste(key, VALID, OVERWRITTEN, false, MAIN_SNIPPET))); //assertEquals(getState().source(snippet), src); //assertEquals(snippet, undefKey); - assertEquals(getState().status(undefKey), RECOVERABLE_NOT_DEFINED); + assertEquals(RECOVERABLE_NOT_DEFINED, getState().status(undefKey)); List unr = getState().unresolvedDependencies((VarSnippet) undefKey).collect(toList()); - assertEquals(unr.size(), 1); - assertEquals(unr.get(0), "class undefined"); + assertEquals(1, unr.size()); + assertEquals("class undefined", unr.get(0)); assertVariables(variable("undefined", "d")); } + @Test public void lvti() { assertEval("var d = 234;", "234"); assertEval("class Test { T[][] get() { return null; } }", added(VALID)); @@ -410,12 +433,14 @@ public void lvti() { assertEval("var r16d = r16d();"); } + @Test public void test8191842() { assertEval("import java.util.stream.*;"); assertEval("var list = Stream.of(1, 2, 3).map(j -> new Object() { int i = j; }).collect(Collectors.toList());"); assertEval("list.stream().map(a -> String.valueOf(a.i)).collect(Collectors.joining(\", \"));", "\"1, 2, 3\""); } + @Test public void lvtiRecompileDependentsWithIntersectionTypes() { assertEval(" Z get1() { return null; }", added(VALID)); assertEval("var i1 = get1();", added(VALID)); @@ -428,27 +453,32 @@ public void lvtiRecompileDependentsWithIntersectionTypes() { assertEval("void t2() { i2.run(); i2.count(); }", added(VALID)); } + @Test public void arrayInit() { assertEval("int[] d = {1, 2, 3};"); } + @Test public void testAnonymousVar() { assertEval("new Object() { public String get() { return \"a\"; } }"); assertEval("$1.get()", "\"a\""); } + @Test public void testIntersectionVar() { assertEval(" Z get() { return null; }", added(VALID)); assertEval("get();", added(VALID)); assertEval("void t1() { $1.run(); $1.length(); }", added(VALID)); } + @Test public void multipleCaptures() { assertEval("class D { D(int foo, String bar) { this.foo = foo; this.bar = bar; } int foo; String bar; } "); assertEval("var d = new D(34, \"hi\") { String z = foo + bar; };"); assertEval("d.z", "\"34hi\""); } + @Test public void multipleAnonymous() { VarSnippet v1 = varKey(assertEval("new Object() { public int i = 42; public int i1 = i; public int m1() { return i1; } };")); VarSnippet v2 = varKey(assertEval("new Object() { public int i = 42; public int i2 = i; public int m2() { return i2; } };")); @@ -466,6 +496,7 @@ public void multipleAnonymous() { -1, -1, Diagnostic.Kind.ERROR)); } + @Test public void displayName() { assertVarDisplayName("var v1 = 234;", "int"); assertVarDisplayName("var v2 = new int[] {234};", "int[]"); @@ -478,6 +509,7 @@ public void displayName() { assertVarDisplayName("var v6 = new Runnable() { public void run() { } };", ""); } + @Test public void varType() { assertEval("import java.util.*;"); var firstVar = varKey(assertEval("var v1 = List.of(1);", added(VALID))); @@ -487,6 +519,7 @@ public void varType() { assertEval("v2", "[1]"); } + @Test public void varDeclNoInit() { assertVarDeclNoInit("byte", "b", "0"); assertVarDeclNoInit("short", "h", "0"); @@ -500,6 +533,7 @@ public void varDeclNoInit() { assertVarDeclNoInit("String", "s", "null"); } + @Test public void varDeclRedefNoInit() { assertVarDeclRedefNoInit("byte", "b", "1", "0"); assertVarDeclRedefNoInit("short", "h", "2", "0"); @@ -513,6 +547,7 @@ public void varDeclRedefNoInit() { assertVarDeclRedefNoInit("String", "s", "\"hi\"", "null"); } + @Test public void badPkgVarDecl() { Compiler compiler = new Compiler(); Path nopkgdirpath = Paths.get("cp", "xyz"); @@ -545,16 +580,16 @@ private VarSnippet assertVarDeclNoInit(String typeName, String name, String dval private VarSnippet assertVarDeclNoInit(String typeName, String name, String dvalue, STEInfo mainInfo, STEInfo... updates) { VarSnippet vs = varKey(assertEval(typeName + " " + name + ";", dvalue, mainInfo, updates)); - assertEquals(vs.typeName(), typeName); + assertEquals(typeName, vs.typeName()); assertEval(name, dvalue, added(VALID)); return vs; } private void assertVarDisplayName(String var, String typeName) { - assertEquals(varKey(assertEval(var)).typeName(), typeName); + assertEquals(typeName, varKey(assertEval(var)).typeName()); } - @BeforeMethod + @BeforeEach @Override public void setUp() { Path path = Paths.get("cp"); @@ -611,14 +646,23 @@ public void setUp() { .compilerOptions("--class-path", tpath)); } + @Test public void varIntersection() { assertEval("interface Marker {}"); assertEval("var v = (Marker & Runnable) () -> {};", added(VALID)); assertEval("v.run()"); } + @Test public void varAnonymousClassAndStaticField() { //JDK-8294431 assertEval("var obj = new Object() { public static final String msg = \"hello\"; };"); } + @Test + public void underscoreAsLambdaParameter() { //JDK-8322532 + assertAnalyze("Func f = _ -> 0; int i;", + "Func f = _ -> 0;", + " int i;", true); + } + } diff --git a/test/langtools/jdk/jshell/WrapperTest.java b/test/langtools/jdk/jshell/WrapperTest.java index 8986c99b4b3d..9903f04676fa 100644 --- a/test/langtools/jdk/jshell/WrapperTest.java +++ b/test/langtools/jdk/jshell/WrapperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 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 @@ -27,28 +27,28 @@ * @summary test wrappers and dependencies * @modules jdk.jshell/jdk.jshell * @build KullaTesting - * @run testng WrapperTest + * @run junit WrapperTest */ import java.util.Collection; import java.util.List; -import org.testng.annotations.Test; import jdk.jshell.ErroneousSnippet; import jdk.jshell.Snippet; import jdk.jshell.Snippet.Kind; import jdk.jshell.SourceCodeAnalysis.SnippetWrapper; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static jdk.jshell.Snippet.Status.RECOVERABLE_DEFINED; import static jdk.jshell.Snippet.Status.VALID; +import org.junit.jupiter.api.Test; -@Test public class WrapperTest extends KullaTesting { + @Test public void testMethod() { String src = "void glib() { System.out.println(\"hello\"); }"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.METHOD, "void", "glib", "println"); assertPosition(swl.get(0), src, 0, 4); assertPosition(swl.get(0), src, 5, 4); @@ -63,6 +63,7 @@ public void testMethod() { } // test 8159740 + @Test public void testMethodCorralled() { String src = "void glib() { f(); }"; // _123456789_123456789 @@ -75,6 +76,7 @@ public void testMethodCorralled() { } // test 8159740 + @Test public void testClassCorralled0() { String src = "class AAA { float mmm(double d1234) { return (float) (f0 * d1234); } }"; // _123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789 @@ -91,6 +93,7 @@ public void testClassCorralled0() { } // test 8159740 + @Test public void testClassCorralled() { String src = "class AAA { int xxx = x0 + 4; float mmm(float ffff) { return f0 * ffff; } }"; // _123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789 @@ -109,6 +112,7 @@ public void testClassCorralled() { } // test 8159740 + @Test public void testClassWithConstructorCorralled() { String src = "public class AAA { AAA(String b) {} int xxx = x0 + 4; float mmm(float ffff) { return f0 * ffff; } }"; // _123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789 @@ -130,6 +134,7 @@ public void testClassWithConstructorCorralled() { } // test 8159740 + @Test public void testInterfaceCorralled() { String src = "interface AAA { default float mmm(double d1234) { return (float) (f0 * d1234); } }"; // _123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789 @@ -147,6 +152,7 @@ public void testInterfaceCorralled() { } // test 8159740 + @Test public void testEnumCorralled() { String src = "public enum Planet {\n" + @@ -182,25 +188,27 @@ public void testEnumCorralled() { "radius", "surfaceGravity", "surfaceWeight"); } + @Test public void testMethodBad() { String src = "void flob() { ?????; }"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.METHOD, "void", "flob", "?????"); assertPosition(swl.get(0), src, 9, 2); Snippet f = key(assertEvalFail(src)); - assertEquals(f.kind(), Kind.ERRONEOUS); - assertEquals(((ErroneousSnippet)f).probableKind(), Kind.METHOD); + assertEquals(Kind.ERRONEOUS, f.kind()); + assertEquals(Kind.METHOD, ((ErroneousSnippet)f).probableKind()); SnippetWrapper sw = getState().sourceCodeAnalysis().wrapper(f); assertWrapperHas(sw, src, Kind.METHOD, "void", "flob", "?????"); assertPosition(swl.get(0), src, 14, 5); } + @Test public void testVar() { String src = "int gx = 1234;"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.VAR, "int", "gx", "1234"); assertPosition(swl.get(0), src, 4, 2); @@ -210,25 +218,27 @@ public void testVar() { assertPosition(swg, src, 0, 3); } + @Test public void testVarBad() { String src = "double dd = ?????;"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.VAR, "double", "dd", "?????"); assertPosition(swl.get(0), src, 9, 2); Snippet f = key(assertEvalFail(src)); - assertEquals(f.kind(), Kind.ERRONEOUS); - assertEquals(((ErroneousSnippet)f).probableKind(), Kind.VAR); + assertEquals(Kind.ERRONEOUS, f.kind()); + assertEquals(Kind.VAR, ((ErroneousSnippet)f).probableKind()); SnippetWrapper sw = getState().sourceCodeAnalysis().wrapper(f); assertWrapperHas(sw, src, Kind.VAR, "double", "dd", "?????"); assertPosition(swl.get(0), src, 12, 5); } + @Test public void testImport() { String src = "import java.lang.*;"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.IMPORT, "import", "java.lang"); assertPosition(swl.get(0), src, 7, 4); @@ -238,61 +248,65 @@ public void testImport() { assertPosition(swg, src, 0, 6); } + @Test public void testImportBad() { String src = "import java.?????;"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.IMPORT, "import", "?????"); assertPosition(swl.get(0), src, 7, 4); Snippet f = key(assertEvalFail(src)); - assertEquals(f.kind(), Kind.ERRONEOUS); - assertEquals(((ErroneousSnippet)f).probableKind(), Kind.IMPORT); + assertEquals(Kind.ERRONEOUS, f.kind()); + assertEquals(Kind.IMPORT, ((ErroneousSnippet)f).probableKind()); SnippetWrapper sw = getState().sourceCodeAnalysis().wrapper(f); assertWrapperHas(sw, src, Kind.IMPORT, "import", "?????"); assertPosition(swl.get(0), src, 0, 6); } + @Test public void testErroneous() { String src = "@@@@@@@@@@"; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 1, "unexpected list length"); + assertEquals(1, swl.size(), "unexpected list length"); assertWrapperHas(swl.get(0), src, Kind.ERRONEOUS, "@@@@@@@@@@"); assertPosition(swl.get(0), src, 0, 10); Snippet f = key(assertEvalFail(src)); - assertEquals(f.kind(), Kind.ERRONEOUS); - assertEquals(((ErroneousSnippet)f).probableKind(), Kind.ERRONEOUS); + assertEquals(Kind.ERRONEOUS, f.kind()); + assertEquals(Kind.ERRONEOUS, ((ErroneousSnippet)f).probableKind()); SnippetWrapper sw = getState().sourceCodeAnalysis().wrapper(f); assertWrapperHas(sw, src, Kind.ERRONEOUS, "@@@@@@@@@@"); assertPosition(swl.get(0), src, 0, 10); } + @Test public void testEmpty() { String src = ""; List swl = getState().sourceCodeAnalysis().wrappers(src); - assertEquals(swl.size(), 0, "expected empty list"); + assertEquals(0, swl.size(), "expected empty list"); } + @Test public void testDependencies() { Snippet a = key(assertEval("int aaa = 6;", added(VALID))); Snippet b = key(assertEval("class B { B(int x) { aaa = x; } }", added(VALID))); Snippet c = key(assertEval("B ccc() { return new B(aaa); }", added(VALID))); Collection dep; dep = getState().sourceCodeAnalysis().dependents(c); - assertEquals(dep.size(), 0); + assertEquals(0, dep.size()); dep = getState().sourceCodeAnalysis().dependents(b); - assertEquals(dep.size(), 1); + assertEquals(1, dep.size()); assertTrue(dep.contains(c)); dep = getState().sourceCodeAnalysis().dependents(a); - assertEquals(dep.size(), 2); + assertEquals(2, dep.size()); assertTrue(dep.contains(c)); assertTrue(dep.contains(b)); } private void assertWrapperHas(SnippetWrapper sw, String source, Kind kind, String... has) { - assertEquals(sw.source(), source); - assertEquals(sw.kind(), kind); + assertEquals(source, sw.source()); + assertEquals(kind, sw.kind()); String s = sw.wrapped(); if (kind == Kind.IMPORT) { assertHas(s, "import"); @@ -322,8 +336,8 @@ private void assertPosition(SnippetWrapper sw, String source, int start, int len //System.err.printf("# wrapped @ wrappedPos: %s\n", wrappedPart); //System.err.printf("# source @ start: %s\n", sourcePart); - assertEquals(wrappedPart, sourcePart, + assertEquals(sourcePart, wrappedPart, "position " + wpg + " in " + sw.wrapped()); - assertEquals(sw.wrappedToSourcePosition(wpg), start); + assertEquals(start, sw.wrappedToSourcePosition(wpg)); } } diff --git a/test/langtools/tools/javac/7129225/NegTest.out b/test/langtools/tools/javac/7129225/NegTest.out index d6fbd22adc39..53ceaa4cb9a1 100644 --- a/test/langtools/tools/javac/7129225/NegTest.out +++ b/test/langtools/tools/javac/7129225/NegTest.out @@ -1,2 +1,2 @@ -TestImportStar.java:16:1: compiler.err.doesnt.exist: xxx +TestImportStar.java:16:8: compiler.err.doesnt.exist: xxx 1 error diff --git a/test/langtools/tools/javac/7129225/TestImportStar.out b/test/langtools/tools/javac/7129225/TestImportStar.out index 86ff89331387..352c0848392a 100644 --- a/test/langtools/tools/javac/7129225/TestImportStar.out +++ b/test/langtools/tools/javac/7129225/TestImportStar.out @@ -1,4 +1,4 @@ - compiler.note.proc.messager: RUNNING - lastRound = false -TestImportStar.java:16:1: compiler.err.doesnt.exist: xxx +TestImportStar.java:16:8: compiler.err.doesnt.exist: xxx - compiler.note.proc.messager: RUNNING - lastRound = true 1 error diff --git a/test/langtools/tools/javac/HexThree.java b/test/langtools/tools/javac/HexThree.java index a89db6e99f86..81c69a4f5329 100644 --- a/test/langtools/tools/javac/HexThree.java +++ b/test/langtools/tools/javac/HexThree.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -25,7 +25,6 @@ * @test * @bug 4920023 * @summary Test hex floating-point literals - * @author darcy */ public class HexThree { diff --git a/test/langtools/tools/javac/StringsInSwitch/OneCaseSwitches.java b/test/langtools/tools/javac/StringsInSwitch/OneCaseSwitches.java index 160c3a3093d0..58dfc69ee2cf 100644 --- a/test/langtools/tools/javac/StringsInSwitch/OneCaseSwitches.java +++ b/test/langtools/tools/javac/StringsInSwitch/OneCaseSwitches.java @@ -4,7 +4,6 @@ * @summary Positive tests for strings in switch with few alternatives. * @compile OneCaseSwitches.java * @run main OneCaseSwitches - * @author Joseph D. Darcy */ import java.lang.reflect.*; diff --git a/test/langtools/tools/javac/StringsInSwitch/StringSwitches.java b/test/langtools/tools/javac/StringsInSwitch/StringSwitches.java index 2e6737e0c050..cd775a1bcb3b 100644 --- a/test/langtools/tools/javac/StringsInSwitch/StringSwitches.java +++ b/test/langtools/tools/javac/StringsInSwitch/StringSwitches.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -25,7 +25,6 @@ * @test * @bug 6827009 7071246 * @summary Positive tests for strings in switch. - * @author Joseph D. Darcy */ public class StringSwitches { diff --git a/test/langtools/tools/javac/TryWithResources/BadTwr.java b/test/langtools/tools/javac/TryWithResources/BadTwr.java index 6043c527af17..a38300b70369 100644 --- a/test/langtools/tools/javac/TryWithResources/BadTwr.java +++ b/test/langtools/tools/javac/TryWithResources/BadTwr.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 - * @author Joseph D. Darcy * @summary Verify bad TWRs don't compile * @compile/fail/ref=BadTwr.out -XDrawDiagnostics BadTwr.java */ diff --git a/test/langtools/tools/javac/TryWithResources/BadTwr.out b/test/langtools/tools/javac/TryWithResources/BadTwr.out index ed8c2524c1b6..b4e951305a51 100644 --- a/test/langtools/tools/javac/TryWithResources/BadTwr.out +++ b/test/langtools/tools/javac/TryWithResources/BadTwr.out @@ -1,5 +1,5 @@ -BadTwr.java:12:46: compiler.err.already.defined: kindname.variable, r1, kindname.method, meth(java.lang.String...) -BadTwr.java:17:20: compiler.err.already.defined: kindname.variable, args, kindname.method, meth(java.lang.String...) -BadTwr.java:20:13: compiler.err.cant.assign.val.to.var: final, thatsIt -BadTwr.java:25:24: compiler.err.already.defined: kindname.variable, name, kindname.method, meth(java.lang.String...) +BadTwr.java:11:46: compiler.err.already.defined: kindname.variable, r1, kindname.method, meth(java.lang.String...) +BadTwr.java:16:20: compiler.err.already.defined: kindname.variable, args, kindname.method, meth(java.lang.String...) +BadTwr.java:19:13: compiler.err.cant.assign.val.to.var: final, thatsIt +BadTwr.java:24:24: compiler.err.already.defined: kindname.variable, name, kindname.method, meth(java.lang.String...) 4 errors diff --git a/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.java b/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.java index 988249cef200..fc31895315c9 100644 --- a/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.java +++ b/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 - * @author Joseph D. Darcy * @summary Verify bad TWRs don't compile * @compile/fail/ref=BadTwrSyntax.out -XDrawDiagnostics BadTwrSyntax.java */ diff --git a/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.out b/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.out index 0d7263710c58..44b283dc611f 100644 --- a/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.out +++ b/test/langtools/tools/javac/TryWithResources/BadTwrSyntax.out @@ -1,2 +1,2 @@ -BadTwrSyntax.java:13:43: compiler.err.illegal.start.of.expr +BadTwrSyntax.java:12:43: compiler.err.illegal.start.of.expr 1 error diff --git a/test/langtools/tools/javac/TryWithResources/ExplicitFinal.java b/test/langtools/tools/javac/TryWithResources/ExplicitFinal.java index e77de854f472..472b9089c1e6 100644 --- a/test/langtools/tools/javac/TryWithResources/ExplicitFinal.java +++ b/test/langtools/tools/javac/TryWithResources/ExplicitFinal.java @@ -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 @@ -24,7 +24,6 @@ /* * @test * @bug 7013420 - * @author Joseph D. Darcy * @summary Test that resource variables are accepted as explicitly final. */ diff --git a/test/langtools/tools/javac/TryWithResources/PlainTry.java b/test/langtools/tools/javac/TryWithResources/PlainTry.java index edbb233578b2..52c05a1ff7cc 100644 --- a/test/langtools/tools/javac/TryWithResources/PlainTry.java +++ b/test/langtools/tools/javac/TryWithResources/PlainTry.java @@ -1,9 +1,8 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 - * @author Joseph D. Darcy * @summary Test error messages for an unadorned try - * @compile/fail/ref=PlainTry.out -XDrawDiagnostics PlainTry.java + * @compile/fail/ref=PlainTry.out -XDrawDiagnostics PlainTry.java */ public class PlainTry { public static void meth() { diff --git a/test/langtools/tools/javac/TryWithResources/PlainTry.out b/test/langtools/tools/javac/TryWithResources/PlainTry.out index 9357cd8cdd79..0f8f16ae1e87 100644 --- a/test/langtools/tools/javac/TryWithResources/PlainTry.out +++ b/test/langtools/tools/javac/TryWithResources/PlainTry.out @@ -1,2 +1,2 @@ -PlainTry.java:10:9: compiler.err.try.without.catch.finally.or.resource.decls +PlainTry.java:9:9: compiler.err.try.without.catch.finally.or.resource.decls 1 error diff --git a/test/langtools/tools/javac/TryWithResources/TwrFlow.java b/test/langtools/tools/javac/TryWithResources/TwrFlow.java index 8ea54244570f..366648fb42e3 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrFlow.java +++ b/test/langtools/tools/javac/TryWithResources/TwrFlow.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 7013420 - * @author Joseph D. Darcy * @summary Test exception analysis of try-with-resources blocks * @compile/fail/ref=TwrFlow.out -XDrawDiagnostics TwrFlow.java */ diff --git a/test/langtools/tools/javac/TryWithResources/TwrFlow.out b/test/langtools/tools/javac/TryWithResources/TwrFlow.out index 23db6517c434..758fb778aae4 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrFlow.out +++ b/test/langtools/tools/javac/TryWithResources/TwrFlow.out @@ -1,3 +1,3 @@ -TwrFlow.java:14:11: compiler.err.except.never.thrown.in.try: java.io.IOException -TwrFlow.java:12:21: compiler.err.unreported.exception.implicit.close: CustomCloseException, twrFlow +TwrFlow.java:13:11: compiler.err.except.never.thrown.in.try: java.io.IOException +TwrFlow.java:11:21: compiler.err.unreported.exception.implicit.close: CustomCloseException, twrFlow 2 errors diff --git a/test/langtools/tools/javac/TryWithResources/TwrLint.java b/test/langtools/tools/javac/TryWithResources/TwrLint.java index 39c5ed67f8f8..ca45efc1e0a6 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrLint.java +++ b/test/langtools/tools/javac/TryWithResources/TwrLint.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 6965277 6967065 - * @author Joseph D. Darcy * @summary Check that -Xlint:twr warnings are generated as expected * @compile/ref=TwrLint.out -Xlint:try,deprecation -XDrawDiagnostics TwrLint.java */ diff --git a/test/langtools/tools/javac/TryWithResources/TwrLint.out b/test/langtools/tools/javac/TryWithResources/TwrLint.out index 6adfc5122b3b..28778b0e3a56 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrLint.out +++ b/test/langtools/tools/javac/TryWithResources/TwrLint.out @@ -1,3 +1,3 @@ -TwrLint.java:14:15: compiler.warn.try.explicit.close.call -TwrLint.java:13:21: compiler.warn.try.resource.not.referenced: r3 +TwrLint.java:13:15: compiler.warn.try.explicit.close.call +TwrLint.java:12:21: compiler.warn.try.resource.not.referenced: r3 2 warnings diff --git a/test/langtools/tools/javac/TryWithResources/TwrMultiCatch.java b/test/langtools/tools/javac/TryWithResources/TwrMultiCatch.java index dbbb633efe17..002e30277e39 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrMultiCatch.java +++ b/test/langtools/tools/javac/TryWithResources/TwrMultiCatch.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -24,7 +24,6 @@ /* * @test * @bug 6911256 6964740 7013420 - * @author Joseph D. Darcy * @summary Test that TWR and multi-catch play well together * @compile TwrMultiCatch.java * @run main TwrMultiCatch diff --git a/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.java b/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.java index ac0a72645ba3..0d6c2f4bc445 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.java +++ b/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 7013420 - * @author Joseph D. Darcy * @summary Verify invalid TWR block is not accepted. * @compile/fail/ref=TwrOnNonResource.out -XDrawDiagnostics TwrOnNonResource.java */ diff --git a/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.out b/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.out index 07488a78071f..9a01e28e1051 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.out +++ b/test/langtools/tools/javac/TryWithResources/TwrOnNonResource.out @@ -1,4 +1,4 @@ -TwrOnNonResource.java:11:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) -TwrOnNonResource.java:14:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) -TwrOnNonResource.java:17:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) +TwrOnNonResource.java:10:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) +TwrOnNonResource.java:13:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) +TwrOnNonResource.java:16:30: compiler.err.prob.found.req: (compiler.misc.try.not.applicable.to.type: (compiler.misc.inconvertible.types: TwrOnNonResource, java.lang.AutoCloseable)) 3 errors diff --git a/test/langtools/tools/javac/TryWithResources/TwrSuppression.java b/test/langtools/tools/javac/TryWithResources/TwrSuppression.java index 9834d5a17b2e..0c511d28cbcb 100644 --- a/test/langtools/tools/javac/TryWithResources/TwrSuppression.java +++ b/test/langtools/tools/javac/TryWithResources/TwrSuppression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -24,7 +24,6 @@ /* * @test * @bug 6971877 - * @author Joseph D. Darcy * @summary Verify a primary exception suppresses all throwables */ diff --git a/test/langtools/tools/javac/TryWithResources/WeirdTwr.java b/test/langtools/tools/javac/TryWithResources/WeirdTwr.java index 6331507097c4..fbfbbe6ecd8b 100644 --- a/test/langtools/tools/javac/TryWithResources/WeirdTwr.java +++ b/test/langtools/tools/javac/TryWithResources/WeirdTwr.java @@ -1,7 +1,6 @@ /* * @test /nodynamiccopyright/ * @bug 6911256 6964740 - * @author Joseph D. Darcy * @summary Strange TWRs * @compile WeirdTwr.java * @run main WeirdTwr diff --git a/test/langtools/tools/javac/annotations/pos/TrailingComma.java b/test/langtools/tools/javac/annotations/pos/TrailingComma.java index d6601ce419db..0fa4bdb3546d 100644 --- a/test/langtools/tools/javac/annotations/pos/TrailingComma.java +++ b/test/langtools/tools/javac/annotations/pos/TrailingComma.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -25,7 +25,6 @@ * @test * @bug 6337964 * @summary javac incorrectly disallows trailing comma in annotation arrays - * @author darcy * @compile TrailingComma.java */ diff --git a/test/langtools/tools/javac/boxing/BoxingCaching.java b/test/langtools/tools/javac/boxing/BoxingCaching.java index 2d7acb817f02..f4c1337f240f 100644 --- a/test/langtools/tools/javac/boxing/BoxingCaching.java +++ b/test/langtools/tools/javac/boxing/BoxingCaching.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -25,7 +25,6 @@ * @test * @bug 4990346 8200478 * @summary Verify autoboxed values are cached as required. - * @author Joseph D. Darcy */ public class BoxingCaching { diff --git a/test/langtools/tools/javac/enum/6350057/T6350057.java b/test/langtools/tools/javac/enum/6350057/T6350057.java index ff96b710af6c..8eb0aa997b6c 100644 --- a/test/langtools/tools/javac/enum/6350057/T6350057.java +++ b/test/langtools/tools/javac/enum/6350057/T6350057.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6350057 7025809 * @summary Test that parameters on implicit enum methods have the right kind - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/enum/AbstractEmptyEnum.java b/test/langtools/tools/javac/enum/AbstractEmptyEnum.java index 38c13bde8287..7f5792167e8d 100644 --- a/test/langtools/tools/javac/enum/AbstractEmptyEnum.java +++ b/test/langtools/tools/javac/enum/AbstractEmptyEnum.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary empty enum cannot be abstract - * @author Joseph D. Darcy * * @compile/fail/ref=AbstractEmptyEnum.out -XDrawDiagnostics AbstractEmptyEnum.java */ diff --git a/test/langtools/tools/javac/enum/AbstractEmptyEnum.out b/test/langtools/tools/javac/enum/AbstractEmptyEnum.out index 933363a3fe6e..b6b2460bb68a 100644 --- a/test/langtools/tools/javac/enum/AbstractEmptyEnum.out +++ b/test/langtools/tools/javac/enum/AbstractEmptyEnum.out @@ -1,2 +1,2 @@ -AbstractEmptyEnum.java:10:8: compiler.err.does.not.override.abstract: AbstractEmptyEnum, m(), AbstractEmptyEnum +AbstractEmptyEnum.java:9:8: compiler.err.does.not.override.abstract: AbstractEmptyEnum, m(), AbstractEmptyEnum 1 error diff --git a/test/langtools/tools/javac/enum/EnumImplicitPrivateConstructor.java b/test/langtools/tools/javac/enum/EnumImplicitPrivateConstructor.java index 36c090668c4f..8ed9e1489782 100644 --- a/test/langtools/tools/javac/enum/EnumImplicitPrivateConstructor.java +++ b/test/langtools/tools/javac/enum/EnumImplicitPrivateConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -25,7 +25,6 @@ * @test * @bug 5009601 5010455 5005748 * @summary enum constructors can be declared private - * @author Joseph D. Darcy */ import java.util.*; diff --git a/test/langtools/tools/javac/enum/EnumPrivateConstructor.java b/test/langtools/tools/javac/enum/EnumPrivateConstructor.java index 84a28a819769..412f79945c8b 100644 --- a/test/langtools/tools/javac/enum/EnumPrivateConstructor.java +++ b/test/langtools/tools/javac/enum/EnumPrivateConstructor.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -25,7 +25,6 @@ * @test * @bug 5009601 * @summary enum constructors can be declared private - * @author Joseph D. Darcy * * @compile EnumPrivateConstructor.java */ diff --git a/test/langtools/tools/javac/enum/EnumProtectedConstructor.java b/test/langtools/tools/javac/enum/EnumProtectedConstructor.java index 481de39319c6..298dcc738c9d 100644 --- a/test/langtools/tools/javac/enum/EnumProtectedConstructor.java +++ b/test/langtools/tools/javac/enum/EnumProtectedConstructor.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum constructors cannot be declared public or protected - * @author Joseph D. Darcy * * @compile/fail/ref=EnumProtectedConstructor.out -XDrawDiagnostics EnumProtectedConstructor.java */ diff --git a/test/langtools/tools/javac/enum/EnumProtectedConstructor.out b/test/langtools/tools/javac/enum/EnumProtectedConstructor.out index 71826a2d331d..5cc734020acd 100644 --- a/test/langtools/tools/javac/enum/EnumProtectedConstructor.out +++ b/test/langtools/tools/javac/enum/EnumProtectedConstructor.out @@ -1,2 +1,2 @@ -EnumProtectedConstructor.java:16:15: compiler.err.mod.not.allowed.here: protected +EnumProtectedConstructor.java:15:15: compiler.err.mod.not.allowed.here: protected 1 error diff --git a/test/langtools/tools/javac/enum/EnumPublicConstructor.java b/test/langtools/tools/javac/enum/EnumPublicConstructor.java index 313605970358..b5c622208efa 100644 --- a/test/langtools/tools/javac/enum/EnumPublicConstructor.java +++ b/test/langtools/tools/javac/enum/EnumPublicConstructor.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum constructors cannot be declared public or protected - * @author Joseph D. Darcy * * @compile/fail/ref=EnumPublicConstructor.out -XDrawDiagnostics EnumPublicConstructor.java */ diff --git a/test/langtools/tools/javac/enum/EnumPublicConstructor.out b/test/langtools/tools/javac/enum/EnumPublicConstructor.out index 56c099f4330c..89ba98d1d81e 100644 --- a/test/langtools/tools/javac/enum/EnumPublicConstructor.out +++ b/test/langtools/tools/javac/enum/EnumPublicConstructor.out @@ -1,2 +1,2 @@ -EnumPublicConstructor.java:16:12: compiler.err.mod.not.allowed.here: public +EnumPublicConstructor.java:15:12: compiler.err.mod.not.allowed.here: public 1 error diff --git a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.java b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.java index 5af537686846..d04a25587150 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.java +++ b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum's cannot be explicitly declared abstract - * @author Joseph D. Darcy * @compile/fail/ref=ExplicitlyAbstractEnum1.out -XDrawDiagnostics ExplicitlyAbstractEnum1.java */ diff --git a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.out b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.out index 827e331a4913..902c9e5730fb 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.out +++ b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum1.out @@ -1,2 +1,2 @@ -ExplicitlyAbstractEnum1.java:9:10: compiler.err.mod.not.allowed.here: abstract +ExplicitlyAbstractEnum1.java:8:10: compiler.err.mod.not.allowed.here: abstract 1 error diff --git a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.java b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.java index cbd9bd512d68..293c36a867d1 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.java +++ b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum's cannot be explicitly declared abstract even if they are abstract - * @author Joseph D. Darcy * @compile/fail/ref=ExplicitlyAbstractEnum2.out -XDrawDiagnostics ExplicitlyAbstractEnum2.java */ diff --git a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.out b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.out index 8a35cec31802..f2c25ca5d4e7 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.out +++ b/test/langtools/tools/javac/enum/ExplicitlyAbstractEnum2.out @@ -1,2 +1,2 @@ -ExplicitlyAbstractEnum2.java:9:10: compiler.err.mod.not.allowed.here: abstract +ExplicitlyAbstractEnum2.java:8:10: compiler.err.mod.not.allowed.here: abstract 1 error diff --git a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.java b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.java index 1dba3d0dff5e..1e2bf650ca5d 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.java +++ b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum's cannot be explicitly declared final even if they are - * @author Joseph D. Darcy * @compile/fail/ref=ExplicitlyFinalEnum1.out -XDrawDiagnostics ExplicitlyFinalEnum1.java */ diff --git a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.out b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.out index 023d00e265fb..11bbdb690b6a 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.out +++ b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum1.out @@ -1,2 +1,2 @@ -ExplicitlyFinalEnum1.java:9:7: compiler.err.mod.not.allowed.here: final +ExplicitlyFinalEnum1.java:8:7: compiler.err.mod.not.allowed.here: final 1 error diff --git a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.java b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.java index 73d3b8acb7b4..0c02799c3d3e 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.java +++ b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary enum's cannot be explicitly declared final - * @author Joseph D. Darcy * @compile/fail/ref=ExplicitlyFinalEnum2.out -XDrawDiagnostics ExplicitlyFinalEnum2.java */ diff --git a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.out b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.out index 09cbf1461add..8d67c8888644 100644 --- a/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.out +++ b/test/langtools/tools/javac/enum/ExplicitlyFinalEnum2.out @@ -1,2 +1,2 @@ -ExplicitlyFinalEnum2.java:9:7: compiler.err.mod.not.allowed.here: final +ExplicitlyFinalEnum2.java:8:7: compiler.err.mod.not.allowed.here: final 1 error diff --git a/test/langtools/tools/javac/enum/FauxEnum1.java b/test/langtools/tools/javac/enum/FauxEnum1.java index 5ae6a8b090ca..7565633032fc 100644 --- a/test/langtools/tools/javac/enum/FauxEnum1.java +++ b/test/langtools/tools/javac/enum/FauxEnum1.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009574 * @summary verify java.lang.Enum can't be directly subclassed - * @author Joseph D. Darcy * * @compile/fail/ref=FauxEnum1.out -XDrawDiagnostics FauxEnum1.java */ diff --git a/test/langtools/tools/javac/enum/FauxEnum1.out b/test/langtools/tools/javac/enum/FauxEnum1.out index ff1e8fa73155..7cae5443e258 100644 --- a/test/langtools/tools/javac/enum/FauxEnum1.out +++ b/test/langtools/tools/javac/enum/FauxEnum1.out @@ -1,4 +1,4 @@ -FauxEnum1.java:10:8: compiler.err.enum.no.subclassing +FauxEnum1.java:9:8: compiler.err.enum.no.subclassing - compiler.note.unchecked.filename: FauxEnum1.java - compiler.note.unchecked.recompile 1 error diff --git a/test/langtools/tools/javac/enum/FauxEnum3.java b/test/langtools/tools/javac/enum/FauxEnum3.java index ec53aeb59519..6cf41cfa8890 100644 --- a/test/langtools/tools/javac/enum/FauxEnum3.java +++ b/test/langtools/tools/javac/enum/FauxEnum3.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009574 * @summary verify an enum type can't be directly subclassed - * @author Joseph D. Darcy * * @compile/fail/ref=FauxEnum3.out -XDrawDiagnostics FauxEnum3.java */ diff --git a/test/langtools/tools/javac/enum/FauxEnum3.out b/test/langtools/tools/javac/enum/FauxEnum3.out index 885154d073a8..33596c87b51f 100644 --- a/test/langtools/tools/javac/enum/FauxEnum3.out +++ b/test/langtools/tools/javac/enum/FauxEnum3.out @@ -1,2 +1,2 @@ -FauxEnum3.java:10:14: compiler.err.enum.types.not.extensible +FauxEnum3.java:9:14: compiler.err.enum.types.not.extensible 1 error diff --git a/test/langtools/tools/javac/enum/FauxSpecialEnum1.java b/test/langtools/tools/javac/enum/FauxSpecialEnum1.java index 5b427bb110de..578864061d03 100644 --- a/test/langtools/tools/javac/enum/FauxSpecialEnum1.java +++ b/test/langtools/tools/javac/enum/FauxSpecialEnum1.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary verify specialized enum classes can't be abstract - * @author Joseph D. Darcy * * @compile/fail/ref=FauxSpecialEnum1.out -XDrawDiagnostics FauxSpecialEnum1.java */ diff --git a/test/langtools/tools/javac/enum/FauxSpecialEnum1.out b/test/langtools/tools/javac/enum/FauxSpecialEnum1.out index 4530bf40a884..ed9a5feaf1f5 100644 --- a/test/langtools/tools/javac/enum/FauxSpecialEnum1.out +++ b/test/langtools/tools/javac/enum/FauxSpecialEnum1.out @@ -1,2 +1,2 @@ -FauxSpecialEnum1.java:14:5: compiler.err.does.not.override.abstract: compiler.misc.anonymous.class: FauxSpecialEnum1$2, test(), compiler.misc.anonymous.class: FauxSpecialEnum1$2 +FauxSpecialEnum1.java:13:5: compiler.err.does.not.override.abstract: compiler.misc.anonymous.class: FauxSpecialEnum1$2, test(), compiler.misc.anonymous.class: FauxSpecialEnum1$2 1 error diff --git a/test/langtools/tools/javac/enum/FauxSpecialEnum2.java b/test/langtools/tools/javac/enum/FauxSpecialEnum2.java index 5c0cc610fa2f..6bf9a97f29ca 100644 --- a/test/langtools/tools/javac/enum/FauxSpecialEnum2.java +++ b/test/langtools/tools/javac/enum/FauxSpecialEnum2.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 5009601 * @summary verify specialized enum classes can't be abstract - * @author Joseph D. Darcy * * @compile/fail/ref=FauxSpecialEnum2.out -XDrawDiagnostics FauxSpecialEnum2.java */ diff --git a/test/langtools/tools/javac/enum/FauxSpecialEnum2.out b/test/langtools/tools/javac/enum/FauxSpecialEnum2.out index 81de8f41726b..aa1cbc8e9cc5 100644 --- a/test/langtools/tools/javac/enum/FauxSpecialEnum2.out +++ b/test/langtools/tools/javac/enum/FauxSpecialEnum2.out @@ -1,2 +1,2 @@ -FauxSpecialEnum2.java:12:5: compiler.err.does.not.override.abstract: compiler.misc.anonymous.class: FauxSpecialEnum2$1, test(), compiler.misc.anonymous.class: FauxSpecialEnum2$1 +FauxSpecialEnum2.java:11:5: compiler.err.does.not.override.abstract: compiler.misc.anonymous.class: FauxSpecialEnum2$1, test(), compiler.misc.anonymous.class: FauxSpecialEnum2$1 1 error diff --git a/test/langtools/tools/javac/generics/InheritanceConflict3.java b/test/langtools/tools/javac/generics/InheritanceConflict3.java index ae725d6c1e28..d9f3c76b06e9 100644 --- a/test/langtools/tools/javac/generics/InheritanceConflict3.java +++ b/test/langtools/tools/javac/generics/InheritanceConflict3.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 4984158 * @summary two inherited methods with same signature - * @author darcy * * @compile/fail/ref=InheritanceConflict3.out -XDrawDiagnostics InheritanceConflict3.java */ diff --git a/test/langtools/tools/javac/generics/InheritanceConflict3.out b/test/langtools/tools/javac/generics/InheritanceConflict3.out index 60cfe5d21488..c168d4b2b86d 100644 --- a/test/langtools/tools/javac/generics/InheritanceConflict3.out +++ b/test/langtools/tools/javac/generics/InheritanceConflict3.out @@ -1,3 +1,3 @@ -InheritanceConflict3.java:14:10: compiler.err.name.clash.same.erasure: f(java.lang.Object), f(T) -InheritanceConflict3.java:17:1: compiler.err.concrete.inheritance.conflict: f(java.lang.Object), inheritance.conflict3.X1, f(T), inheritance.conflict3.X1, inheritance.conflict3.X1 +InheritanceConflict3.java:13:10: compiler.err.name.clash.same.erasure: f(java.lang.Object), f(T) +InheritanceConflict3.java:16:1: compiler.err.concrete.inheritance.conflict: f(java.lang.Object), inheritance.conflict3.X1, f(T), inheritance.conflict3.X1, inheritance.conflict3.X1 2 errors diff --git a/test/langtools/tools/javac/importChecks/ImportIsFullyQualified.out b/test/langtools/tools/javac/importChecks/ImportIsFullyQualified.out index 33e7d2f71c39..89495c2b93dc 100644 --- a/test/langtools/tools/javac/importChecks/ImportIsFullyQualified.out +++ b/test/langtools/tools/javac/importChecks/ImportIsFullyQualified.out @@ -1,2 +1,2 @@ -ImportIsFullyQualified.java:11:1: compiler.err.doesnt.exist: JobAttributes +ImportIsFullyQualified.java:11:8: compiler.err.doesnt.exist: JobAttributes 1 error diff --git a/test/langtools/tools/javac/importChecks/ImportsObservable.out b/test/langtools/tools/javac/importChecks/ImportsObservable.out index e6b6e51e4bb3..28ba84c6aa45 100644 --- a/test/langtools/tools/javac/importChecks/ImportsObservable.out +++ b/test/langtools/tools/javac/importChecks/ImportsObservable.out @@ -1,2 +1,2 @@ -ImportsObservable.java:9:1: compiler.err.doesnt.exist: javax +ImportsObservable.java:9:8: compiler.err.doesnt.exist: javax 1 error diff --git a/test/langtools/tools/javac/modules/ConvenientAccessErrorsTest.java b/test/langtools/tools/javac/modules/ConvenientAccessErrorsTest.java index cf06bd06dfe5..24c2b0458008 100644 --- a/test/langtools/tools/javac/modules/ConvenientAccessErrorsTest.java +++ b/test/langtools/tools/javac/modules/ConvenientAccessErrorsTest.java @@ -799,7 +799,7 @@ public void testPackagesUniquelyVisibleInImportOnDemandNoPrefixes(Path base) thr .getOutputLines(Task.OutputKind.DIRECT); List expected = Arrays.asList( - "Test.java:1:31: compiler.err.doesnt.exist: ma", + "Test.java:1:38: compiler.err.doesnt.exist: ma", "1 error"); if (!expected.equals(log)) @@ -827,7 +827,7 @@ public void testPackagesUniquelyVisibleInImportOnDemandThisModule(Path base) thr .getOutputLines(Task.OutputKind.DIRECT); List expected = Arrays.asList( - "Test.java:1:15: compiler.err.doesnt.exist: ma", + "Test.java:1:22: compiler.err.doesnt.exist: ma", "1 error"); if (!expected.equals(log)) @@ -861,7 +861,7 @@ public void testPackagesUniquelyVisibleInImportOnDemandThisModuleUnnamed(Path ba .getOutputLines(Task.OutputKind.DIRECT); List expected = Arrays.asList( - "Test.java:1:15: compiler.err.doesnt.exist: ma", + "Test.java:1:22: compiler.err.doesnt.exist: ma", "1 error"); if (!expected.equals(log)) diff --git a/test/langtools/tools/javac/multicatch/Neg01.java b/test/langtools/tools/javac/multicatch/Neg01.java index 378e4f285cbd..86a2ae952a19 100644 --- a/test/langtools/tools/javac/multicatch/Neg01.java +++ b/test/langtools/tools/javac/multicatch/Neg01.java @@ -3,7 +3,6 @@ * @bug 6943289 * * @summary Project Coin: Improved Exception Handling for Java (aka 'multicatch') - * @author darcy * @compile/fail/ref=Neg01.out -XDrawDiagnostics Neg01.java */ diff --git a/test/langtools/tools/javac/multicatch/Neg01.out b/test/langtools/tools/javac/multicatch/Neg01.out index 56eb1958a526..f0ddda9bce65 100644 --- a/test/langtools/tools/javac/multicatch/Neg01.out +++ b/test/langtools/tools/javac/multicatch/Neg01.out @@ -1,2 +1,2 @@ -Neg01.java:22:19: compiler.err.except.never.thrown.in.try: Neg01.B2 +Neg01.java:21:19: compiler.err.except.never.thrown.in.try: Neg01.B2 1 error diff --git a/test/langtools/tools/javac/multicatch/Neg01eff_final.java b/test/langtools/tools/javac/multicatch/Neg01eff_final.java index e2c78f5e055c..933d7d1599dc 100644 --- a/test/langtools/tools/javac/multicatch/Neg01eff_final.java +++ b/test/langtools/tools/javac/multicatch/Neg01eff_final.java @@ -3,7 +3,6 @@ * @bug 6943289 * * @summary Project Coin: Improved Exception Handling for Java (aka 'multicatch') - * @author darcy * @compile/fail/ref=Neg01eff_final.out -XDrawDiagnostics Neg01eff_final.java */ diff --git a/test/langtools/tools/javac/multicatch/Neg01eff_final.out b/test/langtools/tools/javac/multicatch/Neg01eff_final.out index 4327ef45b9bd..b110d4468a1f 100644 --- a/test/langtools/tools/javac/multicatch/Neg01eff_final.out +++ b/test/langtools/tools/javac/multicatch/Neg01eff_final.out @@ -1,2 +1,2 @@ -Neg01eff_final.java:22:19: compiler.err.except.never.thrown.in.try: Neg01eff_final.B2 +Neg01eff_final.java:21:19: compiler.err.except.never.thrown.in.try: Neg01eff_final.B2 1 error diff --git a/test/langtools/tools/javac/multicatch/Neg07.java b/test/langtools/tools/javac/multicatch/Neg07.java index e5869e6a2ccf..a2c1704c6b2f 100644 --- a/test/langtools/tools/javac/multicatch/Neg07.java +++ b/test/langtools/tools/javac/multicatch/Neg07.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 7039822 * @summary Verify typing of lub of exception parameter w.r.t getClass - * @author Joseph D. Darcy * @compile/fail/ref=Neg07.out -XDrawDiagnostics Neg07.java */ diff --git a/test/langtools/tools/javac/multicatch/Neg07.out b/test/langtools/tools/javac/multicatch/Neg07.out index 32030e176957..0acdba265da4 100644 --- a/test/langtools/tools/javac/multicatch/Neg07.out +++ b/test/langtools/tools/javac/multicatch/Neg07.out @@ -1,2 +1,2 @@ -Neg07.java:14:56: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: java.lang.Class, java.lang.Class) +Neg07.java:13:56: compiler.err.prob.found.req: (compiler.misc.inconvertible.types: java.lang.Class, java.lang.Class) 1 error diff --git a/test/langtools/tools/javac/multicatch/Pos10.java b/test/langtools/tools/javac/multicatch/Pos10.java index c66fa5334cd1..d108c8f9671a 100644 --- a/test/langtools/tools/javac/multicatch/Pos10.java +++ b/test/langtools/tools/javac/multicatch/Pos10.java @@ -25,7 +25,6 @@ * @test * @bug 7039822 * @summary Verify lub of an exception parameter can be an intersection type - * @author Joseph D. Darcy */ public class Pos10 { diff --git a/test/langtools/tools/javac/processing/6365040/T6365040.java b/test/langtools/tools/javac/processing/6365040/T6365040.java index 4413ff1375c9..c538609800d8 100644 --- a/test/langtools/tools/javac/processing/6365040/T6365040.java +++ b/test/langtools/tools/javac/processing/6365040/T6365040.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 6365040 6358129 * @summary Test -processor foo,bar,baz - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler @@ -13,7 +12,7 @@ * @compile -processor ProcFoo,ProcBar,T6365040 -proc:only T6365040.java * @compile -processor T6365040 -proc:only T6365040.java * @compile -processor T6365040,NotThere, -proc:only T6365040.java - * @compile/fail/ref=T6365040.out -XDrawDiagnostics -processor NotThere -proc:only T6365040.java + * @compile/fail/ref=T6365040.out -XDrawDiagnostics -processor NotThere -proc:only T6365040.java * @compile/fail/ref=T6365040.out -XDrawDiagnostics -processor NotThere,T6365040 -proc:only T6365040.java */ @@ -23,7 +22,6 @@ import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.TypeElement; - public class T6365040 extends JavacTestingAbstractProcessor { public boolean process(Set annotations, RoundEnvironment roundEnvironment) { diff --git a/test/langtools/tools/javac/processing/6378728/T6378728.java b/test/langtools/tools/javac/processing/6378728/T6378728.java index 9ee620510274..791296fb7549 100644 --- a/test/langtools/tools/javac/processing/6378728/T6378728.java +++ b/test/langtools/tools/javac/processing/6378728/T6378728.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -24,7 +24,6 @@ /* @test * @bug 6378728 * @summary Verify -proc:only doesn't produce class files - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler * @compile T6378728.java diff --git a/test/langtools/tools/javac/processing/6634138/T6634138.java b/test/langtools/tools/javac/processing/6634138/T6634138.java index 872192d51eca..baf9bff3b634 100644 --- a/test/langtools/tools/javac/processing/6634138/T6634138.java +++ b/test/langtools/tools/javac/processing/6634138/T6634138.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -24,7 +24,6 @@ /* * @test * @bug 6634138 - * @author Joseph D. Darcy * @summary Verify source files output after processing is over are compiled * @library /tools/javac/lib * @modules java.compiler diff --git a/test/langtools/tools/javac/processing/completion/TestCompletions.java b/test/langtools/tools/javac/processing/completion/TestCompletions.java index 87d947f173e3..c181b0fc84de 100644 --- a/test/langtools/tools/javac/processing/completion/TestCompletions.java +++ b/test/langtools/tools/javac/processing/completion/TestCompletions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6341177 * @summary Some simple tests of the methods in Completions - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler */ diff --git a/test/langtools/tools/javac/processing/environment/TestSourceVersion.java b/test/langtools/tools/javac/processing/environment/TestSourceVersion.java index e31664b8a93b..473b14ad39c3 100644 --- a/test/langtools/tools/javac/processing/environment/TestSourceVersion.java +++ b/test/langtools/tools/javac/processing/environment/TestSourceVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6402506 8028545 8028543 * @summary Test that getSourceVersion works properly - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java b/test/langtools/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java index 33b19543ef7e..ddcaaf7b60db 100644 --- a/test/langtools/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java +++ b/test/langtools/tools/javac/processing/environment/round/TestElementsAnnotatedWith.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6397298 6400986 6425592 6449798 6453386 6508401 6498938 6911854 8030049 8038080 8032230 8190886 * @summary Tests that getElementsAnnotatedWith[Any] methods work properly. - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/errors/TestFatalityOfParseErrors.java b/test/langtools/tools/javac/processing/errors/TestFatalityOfParseErrors.java index 300afaad5248..3a7ee877c1f9 100644 --- a/test/langtools/tools/javac/processing/errors/TestFatalityOfParseErrors.java +++ b/test/langtools/tools/javac/processing/errors/TestFatalityOfParseErrors.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 6403459 * @summary Test that generating programs with syntax errors is a fatal condition - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/errors/TestOptionSyntaxErrors.java b/test/langtools/tools/javac/processing/errors/TestOptionSyntaxErrors.java index 8c397b20f629..bd1dea81a403 100644 --- a/test/langtools/tools/javac/processing/errors/TestOptionSyntaxErrors.java +++ b/test/langtools/tools/javac/processing/errors/TestOptionSyntaxErrors.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6406212 * @summary Test that annotation processor options with illegal syntax are rejected - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules jdk.compiler/com.sun.tools.javac.main * @build JavacTestingAbstractProcessor CompileFail diff --git a/test/langtools/tools/javac/processing/errors/TestReturnCode.java b/test/langtools/tools/javac/processing/errors/TestReturnCode.java index 749044edd6f6..5ca6a50e3c64 100644 --- a/test/langtools/tools/javac/processing/errors/TestReturnCode.java +++ b/test/langtools/tools/javac/processing/errors/TestReturnCode.java @@ -25,7 +25,6 @@ * @test * @bug 6403468 * @summary Test that an erroneous return code results from raising an error. - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules jdk.compiler/com.sun.tools.javac.main * @build JavacTestingAbstractProcessor CompileFail diff --git a/test/langtools/tools/javac/processing/filer/TestFilerConstraints.java b/test/langtools/tools/javac/processing/filer/TestFilerConstraints.java index e522afa9ce8f..6eac5475c0b1 100644 --- a/test/langtools/tools/javac/processing/filer/TestFilerConstraints.java +++ b/test/langtools/tools/javac/processing/filer/TestFilerConstraints.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6380018 6453386 6457283 * @summary Test that the constraints guaranteed by the Filer and maintained - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/filer/TestGetResource.java b/test/langtools/tools/javac/processing/filer/TestGetResource.java index 073757d1217a..cf8ac2aafeba 100644 --- a/test/langtools/tools/javac/processing/filer/TestGetResource.java +++ b/test/langtools/tools/javac/processing/filer/TestGetResource.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6380018 6449798 * @summary Test Filer.getResource - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/filer/TestPackageInfo.java b/test/langtools/tools/javac/processing/filer/TestPackageInfo.java index 1e0659c9b120..1b11c75acde6 100644 --- a/test/langtools/tools/javac/processing/filer/TestPackageInfo.java +++ b/test/langtools/tools/javac/processing/filer/TestPackageInfo.java @@ -25,7 +25,6 @@ * @test * @bug 6380018 6392177 6993311 8193462 * @summary Test the ability to create and process package-info.java files - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/messager/MessagerBasics.java b/test/langtools/tools/javac/processing/messager/MessagerBasics.java index 35c3b64ca2d4..896f7b579b57 100644 --- a/test/langtools/tools/javac/processing/messager/MessagerBasics.java +++ b/test/langtools/tools/javac/processing/messager/MessagerBasics.java @@ -2,7 +2,6 @@ * @test /nodynamiccopyright/ * @bug 6341173 6341072 * @summary Test presence of Messager methods - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/TestExceptions.java b/test/langtools/tools/javac/processing/model/TestExceptions.java index 993e084e157b..e9f5846a7caf 100644 --- a/test/langtools/tools/javac/processing/model/TestExceptions.java +++ b/test/langtools/tools/javac/processing/model/TestExceptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -25,7 +25,6 @@ * @test * @bug 6794071 * @summary Test that exceptions have a proper parent class - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler */ diff --git a/test/langtools/tools/javac/processing/model/TestSourceVersion.java b/test/langtools/tools/javac/processing/model/TestSourceVersion.java index 3a56bf76007f..d53368d3b6df 100644 --- a/test/langtools/tools/javac/processing/model/TestSourceVersion.java +++ b/test/langtools/tools/javac/processing/model/TestSourceVersion.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, 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 @@ -25,7 +25,6 @@ * @test * @bug 7025809 8028543 6415644 8028544 8029942 8187951 8193291 8196551 8233096 8275308 * @summary Test latest, latestSupported, underscore as keyword, etc. - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler */ diff --git a/test/langtools/tools/javac/processing/model/element/TestAnonClassNames.java b/test/langtools/tools/javac/processing/model/element/TestAnonClassNames.java index c7504da4f893..de575841d122 100644 --- a/test/langtools/tools/javac/processing/model/element/TestAnonClassNames.java +++ b/test/langtools/tools/javac/processing/model/element/TestAnonClassNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -25,7 +25,6 @@ * @test * @bug 6449781 6930508 * @summary Test that reported names of anonymous classes are non-null. - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules jdk.compiler * @build JavacTestingAbstractProcessor TestAnonSourceNames diff --git a/test/langtools/tools/javac/processing/model/element/TestElement.java b/test/langtools/tools/javac/processing/model/element/TestElement.java index 9c8783191106..4bfe6280fd58 100644 --- a/test/langtools/tools/javac/processing/model/element/TestElement.java +++ b/test/langtools/tools/javac/processing/model/element/TestElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6453386 * @summary Test basic properties of javax.lang.element.Element - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/element/TestExecutableElement.java b/test/langtools/tools/javac/processing/model/element/TestExecutableElement.java index 4a37be9d7d75..2296214555f6 100644 --- a/test/langtools/tools/javac/processing/model/element/TestExecutableElement.java +++ b/test/langtools/tools/javac/processing/model/element/TestExecutableElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -25,7 +25,6 @@ * @test * @bug 8005046 8011052 8025087 * @summary Test basic properties of javax.lang.element.ExecutableElement - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/element/TestNames.java b/test/langtools/tools/javac/processing/model/element/TestNames.java index adbbf87c8e42..7e9ed193afd6 100644 --- a/test/langtools/tools/javac/processing/model/element/TestNames.java +++ b/test/langtools/tools/javac/processing/model/element/TestNames.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6380016 * @summary Test that the constraints guaranteed by the Filer and maintained - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/element/TestPackageElement.java b/test/langtools/tools/javac/processing/model/element/TestPackageElement.java index f3749f6c5ffa..83d7515677b4 100644 --- a/test/langtools/tools/javac/processing/model/element/TestPackageElement.java +++ b/test/langtools/tools/javac/processing/model/element/TestPackageElement.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6449798 6399404 8173776 8163989 * @summary Test basic workings of PackageElement - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/element/TestResourceVariable.java b/test/langtools/tools/javac/processing/model/element/TestResourceVariable.java index a0f133779ab1..9a51613358a4 100644 --- a/test/langtools/tools/javac/processing/model/element/TestResourceVariable.java +++ b/test/langtools/tools/javac/processing/model/element/TestResourceVariable.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -25,7 +25,6 @@ * @test * @bug 6911256 6964740 6967842 6961571 7025809 * @summary Test that the resource variable kind is appropriately set - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules jdk.compiler * @build JavacTestingAbstractProcessor TestResourceVariable diff --git a/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/NpeTest.java b/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/NpeTest.java index 1e252c01cc06..849f8df7b710 100644 --- a/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/NpeTest.java +++ b/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/NpeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -25,7 +25,6 @@ * @test * @bug 6593082 * @summary MirroredTypeException constructor should not accept null - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler */ diff --git a/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java b/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java index 38c2db7ca139..2487ac779105 100644 --- a/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java +++ b/test/langtools/tools/javac/processing/model/type/MirroredTypeEx/Plurality.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -31,7 +31,6 @@ * @build JavacTestingAbstractProcessor * @compile Plurality.java * @compile -processor Plurality -proc:only Plurality.java - * @author Joseph D. Darcy */ import java.lang.annotation.*; import java.math.BigDecimal; diff --git a/test/langtools/tools/javac/processing/model/type/TestTypeKind.java b/test/langtools/tools/javac/processing/model/type/TestTypeKind.java index fc1ed62e2a58..9bc2e7e7cb62 100644 --- a/test/langtools/tools/javac/processing/model/type/TestTypeKind.java +++ b/test/langtools/tools/javac/processing/model/type/TestTypeKind.java @@ -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 @@ -25,7 +25,6 @@ * @test * @bug 6347716 * @summary Test TypeKind.isPrimitive - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler */ diff --git a/test/langtools/tools/javac/processing/model/util/deprecation/TestDeprecation.java b/test/langtools/tools/javac/processing/model/util/deprecation/TestDeprecation.java index d90b1ad34bf9..fe8e5262be4f 100644 --- a/test/langtools/tools/javac/processing/model/util/deprecation/TestDeprecation.java +++ b/test/langtools/tools/javac/processing/model/util/deprecation/TestDeprecation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6392818 * @summary Tests Elements.isDeprecated(Element) - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java b/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java index a9827b2aacc1..b0b15cf92260 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java +++ b/test/langtools/tools/javac/processing/model/util/elements/TestGetConstantExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -25,7 +25,6 @@ * @test * @bug 6471577 6517779 * @summary Test Elements.getConstantExpression - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/util/elements/TestGetPackageOf.java b/test/langtools/tools/javac/processing/model/util/elements/TestGetPackageOf.java index d82addd8b1fe..96c84db5bb7d 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/TestGetPackageOf.java +++ b/test/langtools/tools/javac/processing/model/util/elements/TestGetPackageOf.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6453386 8216404 8230337 * @summary Test Elements.getPackageOf - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/util/elements/TestIsFunctionalInterface.java b/test/langtools/tools/javac/processing/model/util/elements/TestIsFunctionalInterface.java index f8292afd8155..ae048af45cc3 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/TestIsFunctionalInterface.java +++ b/test/langtools/tools/javac/processing/model/util/elements/TestIsFunctionalInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, 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 @@ -25,7 +25,6 @@ * @test * @bug 8007574 * @summary Test Elements.isFunctionalInterface - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/util/elements/VacuousEnum.java b/test/langtools/tools/javac/processing/model/util/elements/VacuousEnum.java index 2d16a8786255..6269d5c7334a 100644 --- a/test/langtools/tools/javac/processing/model/util/elements/VacuousEnum.java +++ b/test/langtools/tools/javac/processing/model/util/elements/VacuousEnum.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 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 @@ -25,7 +25,6 @@ * @test * @bug 6937417 * @summary Test -Xprint on enum type with no constants - * @author Joseph D. Darcy * @compile -Xprint VacuousEnum.java */ public enum VacuousEnum { diff --git a/test/langtools/tools/javac/processing/model/util/filter/TestIterables.java b/test/langtools/tools/javac/processing/model/util/filter/TestIterables.java index a9bf8ecf8e69..6e9539b7a9e6 100644 --- a/test/langtools/tools/javac/processing/model/util/filter/TestIterables.java +++ b/test/langtools/tools/javac/processing/model/util/filter/TestIterables.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -25,7 +25,6 @@ * @test * @bug 6406164 * @summary Test that ElementFilter iterable methods behave properly. - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules java.compiler * jdk.compiler diff --git a/test/langtools/tools/javac/processing/model/util/types/TestPseudoTypeHandling.java b/test/langtools/tools/javac/processing/model/util/types/TestPseudoTypeHandling.java index 5359d26e53f7..b0898a30ca91 100644 --- a/test/langtools/tools/javac/processing/model/util/types/TestPseudoTypeHandling.java +++ b/test/langtools/tools/javac/processing/model/util/types/TestPseudoTypeHandling.java @@ -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 @@ -25,7 +25,6 @@ * @test * @bug 8175335 * @summary Test Types methods on module and package TypeMirrors - * @author Joseph D. Darcy * @library /tools/javac/lib * @modules jdk.compiler * @build JavacTestingAbstractProcessor TestPseudoTypeHandling diff --git a/test/langtools/tools/javac/processing/warnings/TestSourceVersionWarnings.java b/test/langtools/tools/javac/processing/warnings/TestSourceVersionWarnings.java index 54fe613acf18..24abf89ee029 100644 --- a/test/langtools/tools/javac/processing/warnings/TestSourceVersionWarnings.java +++ b/test/langtools/tools/javac/processing/warnings/TestSourceVersionWarnings.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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,11 +21,11 @@ * questions. */ + /* * @test * @bug 6376083 6376084 6458819 7025784 7025786 7025789 * @summary Test that warnings about source versions are output as expected. - * @author Joseph D. Darcy * @modules java.compiler * jdk.compiler * @compile TestSourceVersionWarnings.java diff --git a/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java b/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java index 83e381356a08..fb67ce83bbe1 100644 --- a/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java +++ b/test/lib/jdk/test/lib/artifacts/ArtifactResolver.java @@ -23,8 +23,7 @@ package jdk.test.lib.artifacts; -import jtreg.SkippedException; - +import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; @@ -90,15 +89,15 @@ public static Path resolve(String name, Map artifactDescription, * @return the local path to the artifact. If the artifact is a compressed * file that gets unpacked, this path will point to the root * directory of the uncompressed file(s). - * @throws SkippedException thrown if the artifact cannot be found + * @throws IOException thrown if the artifact cannot be found */ - public static Path fetchOne(Class klass) { + public static Path fetchOne(Class klass) throws IOException { try { return ArtifactResolver.resolve(klass).entrySet().stream() .findAny().get().getValue(); } catch (ArtifactResolverException e) { Artifact artifact = klass.getAnnotation(Artifact.class); - throw new SkippedException("Cannot find the artifact " + artifact.name(), e); + throw new IOException("Cannot find the artifact " + artifact.name(), e); } } diff --git a/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java b/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java index 3d721b598b93..eb8b630e408d 100644 --- a/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java +++ b/test/lib/jdk/test/lib/containers/docker/DockerTestUtils.java @@ -281,7 +281,9 @@ public static OutputAnalyzer dockerRunJava(DockerRunOptions opts) throws Excepti * @throws Exception */ public static void removeDockerImage(String imageNameAndTag) throws Exception { + if(!DockerTestUtils.RETAIN_IMAGE_AFTER_TEST) { execute(Container.ENGINE_COMMAND, "rmi", "--force", imageNameAndTag); + } } diff --git a/test/lib/jdk/test/lib/net/SimpleSSLContext.java b/test/lib/jdk/test/lib/net/SimpleSSLContext.java index e8611fb007f3..a4ea873ec693 100644 --- a/test/lib/jdk/test/lib/net/SimpleSSLContext.java +++ b/test/lib/jdk/test/lib/net/SimpleSSLContext.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, 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 @@ -23,69 +23,100 @@ package jdk.test.lib.net; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.*; import java.io.*; import java.security.*; -import java.security.cert.*; -import java.util.function.Supplier; import javax.net.ssl.*; /** - * Creates a simple usable SSLContext for SSLSocketFactory - * or a HttpsServer using either a given keystore or a default - * one in the test tree. - * - * Using this class with a security manager requires the following - * permissions to be granted: - * - * permission "java.util.PropertyPermission" "test.src.path", "read"; - * permission java.io.FilePermission "/path/to/test/lib/jdk/test/lib/testkeys", "read"; - * The exact path above depends on the location of the test. + * Utility for creating a simple usable {@link SSLContext} for testing purposes. */ -public class SimpleSSLContext { +public final class SimpleSSLContext { + + private static final String DEFAULT_PROTOCOL = "TLS"; + + private static final String DEFAULT_KEY_STORE_FILE_REL_PATH = "jdk/test/lib/net/testkeys"; - SSLContext ssl; + private final SSLContext ssl; + + // Made `public` for backward compatibility + public SimpleSSLContext() throws IOException { + this.ssl = findSSLContext(DEFAULT_KEY_STORE_FILE_REL_PATH, DEFAULT_PROTOCOL); + } + + // Kept for backward compatibility + public SimpleSSLContext(String keyStoreFileRelPath) throws IOException { + this.ssl = findSSLContext(Objects.requireNonNull(keyStoreFileRelPath), DEFAULT_PROTOCOL); + } /** - * loads default keystore from SimpleSSLContext - * source directory + * {@return a new {@link SSLContext} instance by searching for a key store + * file path, and loading the first found one} + * + * @throws RuntimeException if no key store file can be found or the found + * one cannot be loaded */ - public SimpleSSLContext() throws IOException { - this(() -> "TLS"); + public static SSLContext findSSLContext() throws IOException { + return findSSLContext(DEFAULT_PROTOCOL); + } + + /** + * {@return a new {@link SSLContext} instance by searching for a key store + * file path, and loading the first found one} + * + * @param protocol an {@link SSLContext} protocol + * + * @throws NullPointerException if {@code protocol} is null + * @throws RuntimeException if no key store file can be found or the found + * one cannot be loaded + */ + public static SSLContext findSSLContext(String protocol) throws IOException { + Objects.requireNonNull(protocol); + return findSSLContext(DEFAULT_KEY_STORE_FILE_REL_PATH, protocol); } + /** + * {@return a new {@link SSLContext} instance by searching for a key store + * file path, and loading the first found one} + * + * @param keyStoreFileRelPath a key store file path to be concatenated with + * the search path(s) obtained from the + * {@code test.src.path} system property + * @param protocol an {@link SSLContext} protocol + * + * @throws NullPointerException if {@code keyStoreFileRelPath} or {@code protocol} is null + * @throws RuntimeException if no key store file can be found or the found + * one cannot be loaded + */ @SuppressWarnings("removal") - private SimpleSSLContext(Supplier protocols) throws IOException { + public static SSLContext findSSLContext(String keyStoreFileRelPath, String protocol) throws IOException { + Objects.requireNonNull(keyStoreFileRelPath); + Objects.requireNonNull(protocol); + try { - final String proto = protocols.get(); - AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - String paths = System.getProperty("test.src.path"); - StringTokenizer st = new StringTokenizer(paths, File.pathSeparator); - boolean securityExceptions = false; - while (st.hasMoreTokens()) { - String path = st.nextToken(); - try { - File f = new File(path, "jdk/test/lib/net/testkeys"); - if (f.exists()) { - try (FileInputStream fis = new FileInputStream(f)) { - init(fis, proto); - return null; - } - } - } catch (SecurityException e) { - // catch and ignore because permission only required - // for one entry on path (at most) - securityExceptions = true; + SSLContext res = (SSLContext) AccessController.doPrivileged((PrivilegedExceptionAction) () -> { + String sourcePaths = System.getProperty("test.src.path"); + boolean securityExceptions = false; + for (var sourcePath : Collections.list(new StringTokenizer(sourcePaths, File.pathSeparator))) { + try { + var keyStoreFileAbsPath = Path.of((String) sourcePath, keyStoreFileRelPath); + if (Files.exists(keyStoreFileAbsPath)) { + return loadSSLContext(keyStoreFileAbsPath, protocol); } + } catch (SecurityException e) { + // catch and ignore because permission only required + // for one entry on path (at most) + securityExceptions = true; } - if (securityExceptions) { - System.err.println("SecurityExceptions thrown on loading testkeys"); - } - return null; } + if (securityExceptions) { + System.err.println("SecurityExceptions thrown on loading testkeys"); + } + return null; }); + if (res != null) return res; } catch (PrivilegedActionException pae) { Throwable t = pae.getCause() != null ? pae.getCause() : pae; if (t instanceof IOException) @@ -96,23 +127,25 @@ public Void run() throws Exception { throw (Error)t; throw new RuntimeException(t); } + throw new RuntimeException( + "Could not find any key store at source path(s) using key store file relative path '%s'".formatted( + keyStoreFileRelPath)); } /** - * loads default keystore from given directory + * {@return a new {@link SSLContext} loaded from the provided key store file + * path using the given protocol} + * + * @param keyStoreFilePath a {@link KeyStore} file path + * @param protocol an {@link SSLContext} protocol + * + * @throws RuntimeException if loading fails */ - public SimpleSSLContext(String dir) throws IOException { - String file = dir + "/testkeys"; - try (FileInputStream fis = new FileInputStream(file)) { - init(fis, "TLS"); - } - } - - private void init(InputStream i, String protocol) throws IOException { - try { + private static SSLContext loadSSLContext(Path keyStoreFilePath, String protocol) { + try (var storeStream = Files.newInputStream(keyStoreFilePath)) { char[] passphrase = "passphrase".toCharArray(); KeyStore ks = KeyStore.getInstance("PKCS12"); - ks.load(i, passphrase); + ks.load(storeStream, passphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX"); kmf.init(ks, passphrase); @@ -120,25 +153,32 @@ private void init(InputStream i, String protocol) throws IOException { TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX"); tmf.init(ks); - ssl = SSLContext.getInstance(protocol); - ssl.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); - } catch (KeyManagementException | KeyStoreException | - UnrecoverableKeyException | CertificateException | - NoSuchAlgorithmException e) { - throw new RuntimeException(e.getMessage()); + var sslContext = SSLContext.getInstance(protocol); + sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); + return sslContext; + } catch (SecurityException e) { + throw e; + } catch (Exception e) { + var message = "Failed loading 'SSLContext' from key store at location '%s' for protocol '%s'".formatted( + keyStoreFilePath, protocol); + throw new RuntimeException(message, e); } } + // Kept for backward compatibility public static SSLContext getContext(String protocol) throws IOException { - if(protocol == null || protocol.isEmpty()) { - return new SimpleSSLContext().get(); - } - else { - return new SimpleSSLContext(() -> protocol).get(); + try { + return protocol == null || protocol.isEmpty() + ? findSSLContext() + : findSSLContext(protocol); + } catch (RuntimeException re) { + throw new IOException(re); } } + // Kept for backward compatibility public SSLContext get() { return ssl; } + } diff --git a/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java b/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java index 88508f89587f..32041a93701a 100644 --- a/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java +++ b/test/lib/jdk/test/lib/security/OpensslArtifactFetcher.java @@ -23,6 +23,7 @@ package jdk.test.lib.security; +import java.io.IOException; import java.nio.file.Path; import jdk.test.lib.Platform; import jdk.test.lib.process.ProcessTools; @@ -49,42 +50,40 @@ public class OpensslArtifactFetcher { * * @return openssl binary path of the current version * @throws SkippedException if a valid version of OpenSSL cannot be found + * or if OpenSSL is not available on the target platform */ public static String getOpensslPath() { String path = getOpensslFromSystemProp(OPENSSL_BUNDLE_VERSION); if (path != null) { + System.out.println("Using OpenSSL from system property."); return path; } + path = getDefaultSystemOpensslPath(OPENSSL_BUNDLE_VERSION); if (path != null) { + System.out.println("Using OpenSSL from system."); return path; } + if (Platform.isX64()) { if (Platform.isLinux()) { - path = fetchOpenssl(LINUX_X64.class); + return fetchOpenssl(LINUX_X64.class); } else if (Platform.isOSX()) { - path = fetchOpenssl(MACOSX_X64.class); + return fetchOpenssl(MACOSX_X64.class); } else if (Platform.isWindows()) { - path = fetchOpenssl(WINDOWS_X64.class); + return fetchOpenssl(WINDOWS_X64.class); } } else if (Platform.isAArch64()) { if (Platform.isLinux()) { - path = fetchOpenssl(LINUX_AARCH64.class); + return fetchOpenssl(LINUX_AARCH64.class); } if (Platform.isOSX()) { - path = fetchOpenssl(MACOSX_AARCH64.class); + return fetchOpenssl(MACOSX_AARCH64.class); } } - if (!verifyOpensslVersion(path, OPENSSL_BUNDLE_VERSION)) { - String exMsg = "Can't find the version: " - + OpensslArtifactFetcher.getTestOpensslBundleVersion() - + " of openssl binary on this machine, please install" - + " and set openssl path with property 'test.openssl.path'"; - throw new SkippedException(exMsg); - } else { - return path; - } + throw new SkippedException(String.format("No OpenSSL %s found for %s/%s", + OPENSSL_BUNDLE_VERSION, Platform.getOsName(), Platform.getOsArch())); } private static String getOpensslFromSystemProp(String version) { @@ -120,9 +119,13 @@ private static boolean verifyOpensslVersion(String path, String version) { } private static String fetchOpenssl(Class clazz) { - return ArtifactResolver.fetchOne(clazz) - .resolve("openssl").resolve("bin").resolve("openssl") + try { + return ArtifactResolver.fetchOne(clazz) + .resolve("openssl").resolve("bin").resolve("openssl") .toString(); + } catch (IOException exc) { + throw new SkippedException("Could not find openssl", exc); + } } // retrieve the provider directory path from /bin/openssl diff --git a/test/lib/jdk/test/lib/thread/TestThreadFactory.java b/test/lib/jdk/test/lib/thread/TestThreadFactory.java new file mode 100644 index 000000000000..ac5a6b749092 --- /dev/null +++ b/test/lib/jdk/test/lib/thread/TestThreadFactory.java @@ -0,0 +1,55 @@ +/* + * 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. + */ + +package jdk.test.lib.thread; + +import java.util.concurrent.ThreadFactory; + +/* + This factory is used to start new threads in tests. + It supports creation of virtual threads when jtreg test.thread.factory plugin is enabled. +*/ + +public class TestThreadFactory { + + private static ThreadFactory threadFactory = "Virtual".equals(System.getProperty("test.thread.factory")) + ? virtualThreadFactory() : platformThreadFactory(); + + public static Thread newThread(Runnable task) { + return threadFactory.newThread(task); + } + + public static Thread newThread(Runnable task, String name) { + Thread t = threadFactory.newThread(task); + t.setName(name); + return t; + } + + private static ThreadFactory platformThreadFactory() { + return Thread.ofPlatform().factory(); + } + + private static ThreadFactory virtualThreadFactory() { + return Thread.ofVirtual().factory(); + } +}